You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@mynewt.apache.org by cc...@apache.org on 2019/10/24 16:45:19 UTC

[mynewt-artifact] 03/06: sec: Add `EncType` type

This is an automated email from the ASF dual-hosted git repository.

ccollins pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/mynewt-artifact.git

commit 267010c1118567257abd8e7f56db369f81907ebe
Author: Christopher Collins <cc...@apache.org>
AuthorDate: Wed Oct 23 14:57:37 2019 -0700

    sec: Add `EncType` type
    
    Enumerate the list of encryption types and add the ability to query an
    encryption key for its type.
---
 sec/encrypt.go | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 50 insertions(+)

diff --git a/sec/encrypt.go b/sec/encrypt.go
index 0fc83d1..b9a579e 100644
--- a/sec/encrypt.go
+++ b/sec/encrypt.go
@@ -34,6 +34,14 @@ import (
 	"github.com/apache/mynewt-artifact/errors"
 )
 
+type EncType int
+
+const (
+	ENC_TYPE_AES_128 EncType = iota
+	ENC_TYPE_AES_256
+	ENC_TYPE_RSA_2048
+)
+
 // XXX: Only RSA supported for now.
 type PrivEncKey struct {
 	Rsa *rsa.PrivateKey
@@ -44,6 +52,31 @@ type PubEncKey struct {
 	Aes cipher.Block
 }
 
+var encTypeNameMap = map[EncType]string{
+	ENC_TYPE_AES_128:  "aes128",
+	ENC_TYPE_AES_256:  "aes256",
+	ENC_TYPE_RSA_2048: "rsa2048",
+}
+
+func EncTypeString(typ EncType) string {
+	s := encTypeNameMap[typ]
+	if s == "" {
+		return "unknown"
+	} else {
+		return s
+	}
+}
+
+func EncStringType(s string) (EncType, error) {
+	for k, v := range encTypeNameMap {
+		if s == v {
+			return k, nil
+		}
+	}
+
+	return 0, errors.Errorf("unknown enc type name: \"%s\"", s)
+}
+
 func parsePubKePem(b []byte) (PubEncKey, error) {
 	key := PubEncKey{}
 
@@ -102,6 +135,23 @@ func (key *PubEncKey) AssertValid() {
 	}
 }
 
+func (key *PubEncKey) EncType() (EncType, error) {
+	if key.Rsa != nil {
+		return ENC_TYPE_RSA_2048, nil
+	} else if key.Aes != nil {
+		switch key.Aes.BlockSize() {
+		case 128 / 8:
+			return ENC_TYPE_AES_128, nil
+		case 256 / 8:
+			return ENC_TYPE_AES_256, nil
+		default:
+			return 0, errors.Errorf("illegal AES key block size: %d", key.Aes.BlockSize())
+		}
+	} else {
+		return 0, errors.Errorf("invalid enc key: all members nil")
+	}
+}
+
 func encryptRsa(pubk *rsa.PublicKey, plainSecret []byte) ([]byte, error) {
 	rng := rand.Reader
 	cipherSecret, err := rsa.EncryptOAEP(