From b1b5c44e050f73b399b379ca63a42a2c5780a83f Mon Sep 17 00:00:00 2001 From: CF Networking Team Date: Fri, 1 Nov 2019 14:49:24 -0700 Subject: [PATCH] fix: return friendly error on incorrect nonce --- common/secure/crypto.go | 5 +++++ common/secure/crypto_test.go | 10 ++++++++++ 2 files changed, 15 insertions(+) diff --git a/common/secure/crypto.go b/common/secure/crypto.go index bfbe55f61..7825b0e92 100644 --- a/common/secure/crypto.go +++ b/common/secure/crypto.go @@ -5,6 +5,7 @@ import ( "crypto/cipher" "crypto/rand" "crypto/sha256" + "errors" "golang.org/x/crypto/pbkdf2" ) @@ -45,6 +46,10 @@ func (gcm *AesGCM) Encrypt(plainText []byte) (cipherText, nonce []byte, err erro } func (gcm *AesGCM) Decrypt(cipherText, nonce []byte) ([]byte, error) { + if len(nonce) != gcm.NonceSize() { + return nil, errors.New("incorrect nonce length") + } + plainText, err := gcm.Open(nil, nonce, cipherText, []byte{}) if err != nil { return nil, err diff --git a/common/secure/crypto_test.go b/common/secure/crypto_test.go index 78a0ceb35..a47067af7 100644 --- a/common/secure/crypto_test.go +++ b/common/secure/crypto_test.go @@ -137,6 +137,16 @@ var _ = Describe("Crypto", func() { Expect(decryptedText).ToNot(Equal(plainText)) }) }) + + Context("when the nonce is an invalid length", func() { + It("does not panic and returns an error", func() { + otherNonce := []byte("0123") + decryptedText, err := aesGcm.Decrypt(cipherText, otherNonce) + Expect(err).To(HaveOccurred()) + Expect(err.Error()).Should(ContainSubstring("incorrect nonce length")) + Expect(decryptedText).ToNot(Equal(plainText)) + }) + }) }) Describe("RandomBytes", func() {