Files
lone-services/bff/internal/response/crypto.go
T
gjs be8f89f449
CI / changes (push) Successful in 5s
CI / docker-bff (push) Failing after 7s
CI / docker-product (push) Failing after 5s
CI / docker-admin (push) Failing after 4s
CI / docker-user (push) Failing after 6s
change layout
2026-08-20 15:41:44 +08:00

67 lines
1.5 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 response
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"lone-services/pkg/utils"
)
var (
isDebug bool
encryptKey string
)
// Init 初始化响应加密相关配置(对应旧项目 base.is_debug / encrypt.encrypt_key
func Init(debug bool, key string) {
isDebug = debug
encryptKey = key
}
type Crypto struct{}
// EncryptKey 加密
func (c Crypto) EncryptKey(data []byte, key string) (map[string]string, Error) {
info, err := c.aesCBCEncryptKey(data, key)
if err != nil {
return nil, err
}
return info, nil
}
func (c Crypto) aesCBCEncryptKey(data []byte, key string) (map[string]string, Error) {
k := []byte(key)
iv := utils.GetRandString(NumberSixteen)
// 分组密钥
block, err := aes.NewCipher(k)
if err != nil {
return nil, ErrorEncryptAesKeyError
}
// 获取密钥块的长度
blockSize := block.BlockSize()
// 补充码
data = c.pKCS7Padding(data, blockSize)
// 加密模式
blockMode := cipher.NewCBCEncrypter(block, []byte(iv))
// 创建数组
crypted := make([]byte, len(data))
// 加密
blockMode.CryptBlocks(crypted, data)
return map[string]string{
"data": base64.StdEncoding.EncodeToString(crypted),
"iv": iv,
}, nil
}
func (c Crypto) pKCS7Padding(ciphertext []byte, blockSize int) []byte {
// 判断缺少几位长度,最少为 1,最多为 blockSize
padding := blockSize - len(ciphertext)%blockSize
// 补足位数,把切片 []byte{byte(padding)} 复制 padding 个
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...)
}