Files
lone-services/bff/internal/response/crypto.go
T
gjs 6c20427b0a
CI / changes (push) Successful in 2s
CI / docker-bff (push) Successful in 3m7s
CI / docker-product (push) Has been skipped
CI / docker-admin (push) Successful in 3m26s
bff config to nacos
2026-08-13 16:27:18 +08:00

68 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"
"pkg.local/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...)
}