67 lines
1.5 KiB
Go
67 lines
1.5 KiB
Go
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...)
|
||
}
|