github.com/pingcap/tiflow@v0.0.0-20240520035814-5bf52d54e205/dm/pkg/encrypt/encrypt_test.go (about) 1 // Copyright 2019 PingCAP, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 package encrypt 15 16 import ( 17 "crypto/aes" 18 "crypto/rand" 19 "testing" 20 21 "github.com/stretchr/testify/require" 22 ) 23 24 func removeChar(input []byte, c byte) []byte { 25 i := 0 26 for _, x := range input { 27 if x != c { 28 input[i] = x 29 i++ 30 } 31 } 32 return input[:i] 33 } 34 35 func TestCipher(t *testing.T) { 36 key := make([]byte, 32) 37 _, err := rand.Read(key) 38 require.NoError(t, err) 39 40 t.Cleanup(func() { 41 InitCipher(nil) 42 }) 43 InitCipher(nil) 44 require.IsType(t, ¬InitializedCipher{}, defaultCipher) 45 46 InitCipher(key) 47 require.IsType(t, &aesCipher{}, defaultCipher) 48 49 plaintext := []byte("a plain text") 50 51 // encrypt 52 ciphertext, err := Encrypt(plaintext) 53 require.NoError(t, err) 54 55 // decrypt 56 plaintext2, err := Decrypt(ciphertext) 57 require.NoError(t, err) 58 require.Equal(t, plaintext, plaintext2) 59 60 // invalid length 61 _, err = Decrypt(ciphertext[:len(ciphertext)-len(plaintext)-1]) 62 require.Error(t, err) 63 64 // invalid content 65 _, err = Decrypt(removeChar(ciphertext, ivSep[0])) 66 require.Error(t, err) 67 68 // a special case, we construct a ciphertext that can be decrypted but the 69 // plaintext is not what we want. This is because currently encrypt mechanism 70 // doesn't keep enough information to decide whether the new ciphertext is valid 71 block, err := aes.NewCipher(key) 72 require.NoError(t, err) 73 blockSize := block.BlockSize() 74 require.Greater(t, len(ciphertext), blockSize+2) 75 plaintext3, err := Decrypt(append(ciphertext[1:blockSize+1], append([]byte{ivSep[0]}, ciphertext[blockSize+2:]...)...)) 76 require.NoError(t, err) 77 require.NotEqual(t, plaintext, plaintext3) 78 }