github.com/pingcap/tiflow@v0.0.0-20240520035814-5bf52d54e205/dm/pkg/utils/encrypt_test.go (about) 1 // Copyright 2020 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 utils 15 16 import ( 17 "crypto/rand" 18 "encoding/base64" 19 "testing" 20 21 "github.com/pingcap/tiflow/dm/pkg/encrypt" 22 "github.com/pingcap/tiflow/dm/pkg/terror" 23 "github.com/stretchr/testify/require" 24 ) 25 26 func TestEncrypt(t *testing.T) { 27 t.Cleanup(func() { 28 encrypt.InitCipher(nil) 29 }) 30 key := make([]byte, 32) 31 _, err := rand.Read(key) 32 require.NoError(t, err) 33 encrypt.InitCipher(key) 34 35 plaintext := "abc@123" 36 ciphertext, err := Encrypt(plaintext) 37 require.NoError(t, err) 38 39 plaintext2, err := Decrypt(ciphertext) 40 require.NoError(t, err) 41 require.Equal(t, plaintext, plaintext2) 42 require.Equal(t, plaintext2, DecryptOrPlaintext(ciphertext)) 43 44 // invalid base64 string 45 plaintext2, err = Decrypt("invalid-base64") 46 require.True(t, terror.ErrEncCipherTextBase64Decode.Equal(err)) 47 require.Equal(t, "", plaintext2) 48 require.Equal(t, "invalid-base64", DecryptOrPlaintext("invalid-base64")) 49 50 // invalid ciphertext 51 plaintext2, err = Decrypt(base64.StdEncoding.EncodeToString([]byte("invalid-plaintext"))) 52 require.Regexp(t, ".*can not decrypt password.*", err) 53 require.Equal(t, "", plaintext2) 54 55 require.Equal(t, "invalid-plaintext", DecryptOrPlaintext("invalid-plaintext")) 56 57 encrypt.InitCipher(nil) 58 _, err = Encrypt(plaintext) 59 require.ErrorContains(t, err, "not initialized") 60 61 base64Str := base64.StdEncoding.EncodeToString([]byte("plaintext")) 62 plaintext2, err = Decrypt(base64Str) 63 require.Regexp(t, ".*can not decrypt password.*", err) 64 require.ErrorContains(t, err, "not initialized") 65 require.Equal(t, "", plaintext2) 66 require.Equal(t, base64Str, DecryptOrPlaintext(base64Str)) 67 }