ycc-server/pkg/lzkit/crypto/tianyuan_crypto.go
2025-06-19 17:12:48 +08:00

103 lines
2.3 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package crypto
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"encoding/hex"
"errors"
"io"
)
// TianyuanEncrypt 天远数据AES-128-CBC加密返回Base64编码的字符串
// 与Node.js中的aesEncrypt函数对应
func TianyuanEncrypt(plainText []byte, keyHex string) (string, error) {
// 将16进制密钥转换为字节
keyBuffer, err := hex.DecodeString(keyHex)
if err != nil {
return "", err
}
// 创建AES密码器
block, err := aes.NewCipher(keyBuffer)
if err != nil {
return "", err
}
blockSize := block.BlockSize() // AES块大小为16字节
// 生成随机IV
iv := make([]byte, blockSize)
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return "", err
}
// 创建CBC加密器
mode := cipher.NewCBCEncrypter(block, iv)
// PKCS7填充
paddedText := PKCS7Padding(plainText, blockSize)
// 加密
encrypted := make([]byte, len(paddedText))
mode.CryptBlocks(encrypted, paddedText)
// 将IV和加密数据连接在一起然后Base64编码
result := append(iv, encrypted...)
return base64.StdEncoding.EncodeToString(result), nil
}
// TianyuanDecrypt 天远数据AES-128-CBC解密返回解密后的字节数组
// 与Node.js中的aesDecrypt函数对应
func TianyuanDecrypt(encryptedText, keyHex string) ([]byte, error) {
// 将16进制密钥转换为字节
keyBuffer, err := hex.DecodeString(keyHex)
if err != nil {
return nil, err
}
// Base64解码
encryptedBuffer, err := base64.StdEncoding.DecodeString(encryptedText)
if err != nil {
return nil, err
}
// 创建AES密码器
block, err := aes.NewCipher(keyBuffer)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
// 检查数据长度
if len(encryptedBuffer) < blockSize {
return nil, errors.New("encrypted text too short")
}
// 提取IV和加密数据
iv := encryptedBuffer[:blockSize]
encryptedData := encryptedBuffer[blockSize:]
// 检查加密数据长度是否为块大小的倍数
if len(encryptedData)%blockSize != 0 {
return nil, errors.New("encrypted data is not a multiple of the block size")
}
// 创建CBC解密器
mode := cipher.NewCBCDecrypter(block, iv)
// 解密
decrypted := make([]byte, len(encryptedData))
mode.CryptBlocks(decrypted, encryptedData)
// 去除PKCS7填充
result, err := PKCS7UnPadding(decrypted)
if err != nil {
return nil, err
}
return result, nil
}