github.com/kaisenlinux/docker.io@v0.0.0-20230510090727-ea55db55fac7/swarmkit/manager/encryption/fernet_test.go (about) 1 package encryption 2 3 import ( 4 cryptorand "crypto/rand" 5 "io" 6 "testing" 7 8 "github.com/docker/swarmkit/api" 9 "github.com/stretchr/testify/require" 10 ) 11 12 // Using the same key to encrypt the same message, this encrypter produces two 13 // different ciphertexts because the underlying algorithm uses different IVs. 14 // Both of these can be decrypted into the same data though. 15 func TestFernet(t *testing.T) { 16 key := make([]byte, 32) 17 _, err := io.ReadFull(cryptorand.Reader, key) 18 require.NoError(t, err) 19 keyCopy := make([]byte, 32) 20 copy(key, keyCopy) 21 22 crypter1 := NewFernet(key) 23 crypter2 := NewFernet(keyCopy) 24 data := []byte("Hello again world") 25 26 er1, err := crypter1.Encrypt(data) 27 require.NoError(t, err) 28 29 er2, err := crypter2.Encrypt(data) 30 require.NoError(t, err) 31 32 require.NotEqual(t, er1.Data, er2.Data) 33 require.Empty(t, er1.Nonce) 34 require.Empty(t, er2.Nonce) 35 36 // it doesn't matter what the nonce is, it's ignored 37 _, err = io.ReadFull(cryptorand.Reader, er1.Nonce) 38 require.NoError(t, err) 39 40 // both crypters can decrypt the other's text 41 for i, decrypter := range []Decrypter{crypter1, crypter2} { 42 for j, record := range []*api.MaybeEncryptedRecord{er1, er2} { 43 result, err := decrypter.Decrypt(*record) 44 require.NoError(t, err, "error decrypting ciphertext produced by cryptor %d using cryptor %d", j+1, i+1) 45 require.Equal(t, data, result) 46 } 47 } 48 } 49 50 func TestFernetInvalidAlgorithm(t *testing.T) { 51 key := make([]byte, 32) 52 _, err := io.ReadFull(cryptorand.Reader, key) 53 require.NoError(t, err) 54 55 crypter := NewFernet(key) 56 er, err := crypter.Encrypt([]byte("Hello again world")) 57 require.NoError(t, err) 58 er.Algorithm = api.MaybeEncryptedRecord_NotEncrypted 59 60 _, err = crypter.Decrypt(*er) 61 require.Error(t, err) 62 require.Contains(t, err.Error(), "not a Fernet message") 63 } 64 65 func TestFernetCannotDecryptWithoutRightKey(t *testing.T) { 66 key := make([]byte, 32) 67 _, err := io.ReadFull(cryptorand.Reader, key) 68 require.NoError(t, err) 69 70 crypter := NewFernet(key) 71 er, err := crypter.Encrypt([]byte("Hello again world")) 72 require.NoError(t, err) 73 74 crypter = NewFernet([]byte{}) 75 _, err = crypter.Decrypt(*er) 76 require.Error(t, err) 77 }