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 2020/08/12 21:34:46 UTC

[mynewt-artifact] branch master updated: Encrypt AES: Don't assume nonce is 8 bytes

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


The following commit(s) were added to refs/heads/master by this push:
     new 252824c  Encrypt AES: Don't assume nonce is 8 bytes
252824c is described below

commit 252824cdbca1dc71e5bf1cd59af36552628c049a
Author: Christopher Collins <cc...@apache.org>
AuthorDate: Thu Jul 30 11:09:02 2020 -0700

    Encrypt AES: Don't assume nonce is 8 bytes
    
    For AES encryption, the client can optionally pass a nonce to use as the
    beginning of the IV.  The code assumed the nonce was exactly eight
    bytes, so it would always append eight zeros to form the 16-byte nonce.
    
    The fix is to only append as many zeros are necessary for a 16-byte IV.
---
 sec/encrypt.go | 16 +++++++++-------
 1 file changed, 9 insertions(+), 7 deletions(-)

diff --git a/sec/encrypt.go b/sec/encrypt.go
index 85d4571..8d142e3 100644
--- a/sec/encrypt.go
+++ b/sec/encrypt.go
@@ -31,9 +31,10 @@ import (
 	"crypto/sha256"
 	"crypto/x509"
 	"encoding/base64"
-	"golang.org/x/crypto/hkdf"
 	"io"
 
+	"golang.org/x/crypto/hkdf"
+
 	keywrap "github.com/NickBall/go-aes-key-wrap"
 	"github.com/apache/mynewt-artifact/errors"
 )
@@ -251,17 +252,18 @@ func (k *PrivEncKey) Decrypt(ciph []byte) ([]byte, error) {
 }
 
 func EncryptAES(plain []byte, secret []byte, nonce []byte) ([]byte, error) {
+	if len(nonce) > 16 {
+		return nil, errors.Errorf("AES nonce has invalid length: have=%d want<=16", len(nonce))
+	}
+
 	blk, err := aes.NewCipher(secret)
 	if err != nil {
 		return nil, errors.Errorf("Failed to create block cipher")
 	}
 
-	var iv []byte
-	if nonce == nil {
-		iv = make([]byte, 16)
-	} else {
-		zeros := make([]byte, 8)
-		iv = append(nonce, zeros...)
+	iv := nonce
+	for len(iv) < 16 {
+		iv = append(nonce, 0)
 	}
 
 	stream := cipher.NewCTR(blk, iv)