@@ -2,6 +2,7 @@ package dbcrypt_test
2
2
3
3
import (
4
4
"bytes"
5
+ "encoding/base64"
5
6
"testing"
6
7
7
8
"github.com/stretchr/testify/require"
@@ -42,6 +43,26 @@ func TestCipherAES256(t *testing.T) {
42
43
_ , err := dbcrypt .CipherAES256 (bytes .Repeat ([]byte {'a' }, 31 ))
43
44
require .ErrorContains (t , err , "key must be 32 bytes" )
44
45
})
46
+
47
+ t .Run ("TestNonce" , func (t * testing.T ) {
48
+ key := bytes .Repeat ([]byte {'a' }, 32 )
49
+ cipher , err := dbcrypt .CipherAES256 (key )
50
+ require .NoError (t , err )
51
+ require .Equal (t , "3ba3f5f" , cipher .HexDigest ())
52
+
53
+ encrypted1 , err := cipher .Encrypt ([]byte ("hello world" ))
54
+ require .NoError (t , err )
55
+ encrypted2 , err := cipher .Encrypt ([]byte ("hello world" ))
56
+ require .NoError (t , err )
57
+ require .NotEqual (t , encrypted1 , encrypted2 , "nonce should be different for each encryption" )
58
+
59
+ munged := make ([]byte , len (encrypted1 ))
60
+ copy (munged , encrypted1 )
61
+ munged [0 ] = munged [0 ] ^ 0xff
62
+ _ , err = cipher .Decrypt (munged )
63
+ var decryptErr * dbcrypt.DecryptFailedError
64
+ require .ErrorAs (t , err , & decryptErr , "munging the first byte of the encrypted data should cause decryption to fail" )
65
+ })
45
66
}
46
67
47
68
func TestCiphers (t * testing.T ) {
@@ -92,3 +113,32 @@ func TestCiphers(t *testing.T) {
92
113
_ = dbcrypt .NewCiphers (ciphers )
93
114
})
94
115
}
116
+
117
+ // This test ensures backwards compatibility. If it breaks, something is very wrong.
118
+ func TestCiphersBackwardCompatibility (t * testing.T ) {
119
+ t .Parallel ()
120
+ var (
121
+ msg = "hello world"
122
+ key = bytes .Repeat ([]byte {'a' }, 32 )
123
+ //nolint: gosec // The below is the base64-encoded result of encrypting the above message with the above key.
124
+ encoded = `M2JhM2Y1Zi3r1KSStbmfMBXDzdjVcCrtumdMFsJ4QiYlb3fV1HB8yxg9obHaz5I=`
125
+ )
126
+
127
+ // This is the code that was used to generate the above.
128
+ // Note that the output of this code will change every time it is run.
129
+ //encrypted, err := cs.Encrypt([]byte(msg))
130
+ //require.NoError(t, err)
131
+ //t.Logf("encoded: %q", base64.StdEncoding.EncodeToString(encrypted))
132
+
133
+ cipher , err := dbcrypt .CipherAES256 (key )
134
+ require .NoError (t , err )
135
+ require .Equal (t , "3ba3f5f" , cipher .HexDigest ())
136
+ cs := dbcrypt .NewCiphers (cipher )
137
+
138
+ decoded , err := base64 .StdEncoding .DecodeString (encoded )
139
+ require .NoError (t , err , "the encoded string should be valid base64" )
140
+ decrypted , err := cs .Decrypt (decoded )
141
+ require .NoError (t , err , "decryption should succeed" )
142
+ require .Equal (t , msg , string (decrypted ), "decrypted message should match original message" )
143
+
144
+ }
0 commit comments