qnc-server-old/utils/encrypt.go

79 lines
1.7 KiB
Go
Raw Normal View History

2024-09-14 10:48:09 +08:00
package utils
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"fmt"
"io"
)
// 加密函数
func EncryptCode(plainText string, key string) (string, error) {
// 创建 AES 块加密器
block, err := aes.NewCipher([]byte(key))
if err != nil {
return "", err
}
// 将原始文本转为字节数组
plainTextBytes := []byte(plainText)
// 创建加密用的 GCM (Galois/Counter Mode)
aesGCM, err := cipher.NewGCM(block)
if err != nil {
return "", err
}
// 创建随机的 nonce长度必须为 GCM 的 nonceSize
nonce := make([]byte, aesGCM.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
return "", err
}
// 加密数据并附带 nonce
cipherText := aesGCM.Seal(nonce, nonce, plainTextBytes, nil)
// 将加密后的内容用 base64 编码
return base64.StdEncoding.EncodeToString(cipherText), nil
}
// 解密函数
func DecryptCode(cipherText string, key string) (string, error) {
// 解码 base64 编码的密文
cipherTextBytes, err := base64.StdEncoding.DecodeString(cipherText)
if err != nil {
return "", err
}
// 创建 AES 块加密器
block, err := aes.NewCipher([]byte(key))
if err != nil {
return "", err
}
// 创建加密用的 GCM
aesGCM, err := cipher.NewGCM(block)
if err != nil {
return "", err
}
// 分离 nonce 和加密数据
nonceSize := aesGCM.NonceSize()
if len(cipherTextBytes) < nonceSize {
return "", fmt.Errorf("cipherText too short")
}
nonce, cipherTextBytes := cipherTextBytes[:nonceSize], cipherTextBytes[nonceSize:]
// 解密数据
plainTextBytes, err := aesGCM.Open(nil, nonce, cipherTextBytes, nil)
if err != nil {
return "", err
}
// 返回解密后的明文
return string(plainTextBytes), nil
}