github.com/jxskiss/gopkg/v2@v2.14.9-0.20240514120614-899f3e7952b4/encrypt/crypto/aes_test.go (about) 1 package crypto 2 3 import ( 4 "testing" 5 6 "github.com/stretchr/testify/assert" 7 ) 8 9 var ( 10 testKeyList = [][]byte{ 11 []byte("_test_test_test_"), // 16 bytes 12 []byte("_test_test_test_12345678"), // 24 bytes 13 []byte("_test_test_test_1234567890abcdef"), // 32 bytes 14 } 15 plaintext = []byte("hello 世界") 16 ) 17 18 func Test_GCM(t *testing.T) { 19 for _, testkey := range testKeyList { 20 ciphertext, err := GCMEncrypt(plaintext, testkey) 21 assert.Nil(t, err) 22 23 decrypted, err := GCMDecrypt(ciphertext, testkey) 24 assert.Nil(t, err) 25 assert.Equal(t, plaintext, decrypted) 26 } 27 } 28 29 func Test_GCM_EmptyKey(t *testing.T) { 30 emptyKey := []byte("") 31 ciphertext, err := GCMEncrypt(plaintext, emptyKey) 32 assert.Nil(t, err) 33 34 decrypted, err := GCMDecrypt(ciphertext, emptyKey) 35 assert.Nil(t, err) 36 assert.Equal(t, plaintext, decrypted) 37 } 38 39 func Test_GCM_NewKey(t *testing.T) { 40 ciphertext, key, additional, err := GCMEncryptNewKey(plaintext) 41 assert.Nil(t, err) 42 43 decrypted, err := GCMDecrypt(ciphertext, key, AdditionalData(additional)) 44 assert.Nil(t, err) 45 assert.Equal(t, plaintext, decrypted) 46 } 47 48 func Test_CBC(t *testing.T) { 49 for _, testkey := range testKeyList { 50 ciphertext, err := CBCEncrypt(plaintext, testkey) 51 assert.Nil(t, err) 52 53 decrypted, err := CBCDecrypt(ciphertext, testkey) 54 assert.Nil(t, err) 55 assert.Equal(t, plaintext, decrypted) 56 } 57 } 58 59 func Test_CFB(t *testing.T) { 60 for _, testkey := range testKeyList { 61 ciphertext, err := CFBEncrypt(plaintext, testkey) 62 assert.Nil(t, err) 63 64 decrypted, err := CFBDecrypt(ciphertext, testkey) 65 assert.Nil(t, err) 66 assert.Equal(t, plaintext, decrypted) 67 } 68 } 69 70 func Test_KeyPadding(t *testing.T) { 71 for i := 0; i < 17; i++ { 72 key := make([]byte, i) 73 key = KeyPadding(key) 74 assert.Len(t, key, 16) 75 } 76 for i := 17; i < 25; i++ { 77 key := make([]byte, i) 78 key = KeyPadding(key) 79 assert.Len(t, key, 24) 80 } 81 for i := 25; i < 50; i++ { 82 key := make([]byte, i) 83 key = KeyPadding(key) 84 assert.Len(t, key, 32) 85 } 86 }