github.com/pingcap/tiflow@v0.0.0-20240520035814-5bf52d54e205/dm/pkg/utils/encrypt.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 utils 15 16 import ( 17 "encoding/base64" 18 19 "github.com/pingcap/tiflow/dm/pkg/encrypt" 20 "github.com/pingcap/tiflow/dm/pkg/terror" 21 ) 22 23 // Encrypt tries to encrypt plaintext to base64 encoded ciphertext. 24 func Encrypt(plaintext string) (string, error) { 25 ciphertext, err := encrypt.Encrypt([]byte(plaintext)) 26 if err != nil { 27 return "", err 28 } 29 30 return base64.StdEncoding.EncodeToString(ciphertext), nil 31 } 32 33 // EncryptOrPlaintext tries to encrypt plaintext to base64 encoded ciphertext or return plaintext. 34 // dm-master might not set customized key, so we should handle the error and return plaintext directly. 35 func EncryptOrPlaintext(plaintext string) string { 36 ciphertext, err := Encrypt(plaintext) 37 if err != nil { 38 return plaintext 39 } 40 return ciphertext 41 } 42 43 // Decrypt tries to decrypt base64 encoded ciphertext to plaintext. 44 func Decrypt(ciphertextB64 string) (string, error) { 45 ciphertext, err := base64.StdEncoding.DecodeString(ciphertextB64) 46 if err != nil { 47 return "", terror.ErrEncCipherTextBase64Decode.Delegate(err, ciphertextB64) 48 } 49 50 plaintext, err := encrypt.Decrypt(ciphertext) 51 if err != nil { 52 return "", terror.Annotatef(err, "can not decrypt password %s", ciphertextB64) 53 } 54 return string(plaintext), nil 55 } 56 57 // DecryptOrPlaintext tries to decrypt base64 encoded ciphertext to plaintext or return plaintext. 58 // when a customized key is provided, we support both plaintext and ciphertext as password, 59 // if not provided, only plaintext is supported. 60 func DecryptOrPlaintext(ciphertextB64 string) string { 61 plaintext, err := Decrypt(ciphertextB64) 62 if err != nil { 63 return ciphertextB64 64 } 65 return plaintext 66 }