github.com/trustbloc/kms-go@v1.1.2/wrapper/localsuite/encrypter_test.go (about) 1 /* 2 Copyright Gen Digital Inc. All Rights Reserved. 3 SPDX-License-Identifier: Apache-2.0 4 */ 5 6 package localsuite 7 8 import ( 9 "errors" 10 "testing" 11 12 "github.com/stretchr/testify/require" 13 mockcrypto "github.com/trustbloc/kms-go/mock/crypto" 14 mockkms "github.com/trustbloc/kms-go/mock/kms" 15 ) 16 17 func TestEncrypterDecrypter(t *testing.T) { 18 t.Run("success", func(t *testing.T) { 19 cipher := []byte("nusutto ni torinokosareshi") 20 21 msg := []byte("the thief left it behind") 22 aad := []byte("the moon, at my window") 23 kid := "foo" 24 nonce := []byte("e49tow4nho") 25 26 crypter := newEncrypterDecrypter(&mockkms.KeyManager{}, &mockcrypto.Crypto{ 27 EncryptValue: cipher, 28 EncryptNonceValue: nonce, 29 DecryptValue: msg, 30 }) 31 32 encMessage, gotNonce, err := crypter.Encrypt(msg, aad, kid) 33 require.NoError(t, err) 34 require.Equal(t, cipher, encMessage) 35 require.Equal(t, nonce, gotNonce) 36 37 gotMsg, err := crypter.Decrypt(encMessage, aad, nonce, kid) 38 require.NoError(t, err) 39 require.Equal(t, gotMsg, msg) 40 }) 41 42 t.Run("kms get err", func(t *testing.T) { 43 errExpected := errors.New("expected error") 44 45 crypter := newEncrypterDecrypter(&mockkms.KeyManager{ 46 GetKeyErr: errExpected, 47 }, &mockcrypto.Crypto{}) 48 49 enc, nonce, err := crypter.Encrypt(nil, nil, "") 50 require.ErrorIs(t, err, errExpected) 51 require.Nil(t, enc) 52 require.Nil(t, nonce) 53 54 msg, err := crypter.Decrypt(nil, nil, nil, "") 55 require.ErrorIs(t, err, errExpected) 56 require.Nil(t, msg) 57 }) 58 59 t.Run("crypto err", func(t *testing.T) { 60 errExpected := errors.New("expected error") 61 62 crypter := newEncrypterDecrypter( 63 &mockkms.KeyManager{}, 64 &mockcrypto.Crypto{ 65 EncryptErr: errExpected, 66 DecryptErr: errExpected, 67 }, 68 ) 69 70 enc, nonce, err := crypter.Encrypt(nil, nil, "") 71 require.ErrorIs(t, err, errExpected) 72 require.Nil(t, enc) 73 require.Nil(t, nonce) 74 75 msg, err := crypter.Decrypt(nil, nil, nil, "") 76 require.ErrorIs(t, err, errExpected) 77 require.Nil(t, msg) 78 }) 79 }