59 lines
1.4 KiB
Go
59 lines
1.4 KiB
Go
package encrypt
|
||
|
||
import (
|
||
"crypto/aes"
|
||
"crypto/cipher"
|
||
"errors"
|
||
)
|
||
|
||
// AesEncrypt 使用 AES-CBC 模式对数据进行加密。
|
||
//
|
||
// 参数:
|
||
// - plainText: 原始明文数据(必须是任意长度)
|
||
// - key: 加密密钥(长度必须是 16、24 或 32 字节)
|
||
// - iv: 初始化向量(必须是 16 字节)
|
||
//
|
||
// 返回值:
|
||
// - 加密后的密文
|
||
// - 错误信息(如果加密失败)
|
||
func AesEncrypt(plainText, key, iv []byte) ([]byte, error) {
|
||
block, err := aes.NewCipher(key)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
if len(iv) != aes.BlockSize {
|
||
return nil, errors.New("IV 长度必须为 16 字节")
|
||
}
|
||
|
||
plainText = pkcs7Padding(plainText, aes.BlockSize)
|
||
cipherText := make([]byte, len(plainText))
|
||
|
||
mode := cipher.NewCBCEncrypter(block, iv)
|
||
mode.CryptBlocks(cipherText, plainText)
|
||
|
||
return cipherText, nil
|
||
}
|
||
|
||
// pkcs7Padding 对数据进行 PKCS7 填充。
|
||
//
|
||
// 参数:
|
||
// - data: 原始数据
|
||
// - blockSize: 块大小(通常为 16)
|
||
//
|
||
// 返回值:
|
||
// - 填充后的数据
|
||
func pkcs7Padding(data []byte, blockSize int) []byte {
|
||
padding := blockSize - len(data)%blockSize
|
||
padText := bytesRepeat(byte(padding), padding)
|
||
return append(data, padText...)
|
||
}
|
||
|
||
// bytesRepeat 返回一个重复 count 次的字节切片。
|
||
func bytesRepeat(b byte, count int) []byte {
|
||
buf := make([]byte, count)
|
||
for i := 0; i < count; i++ {
|
||
buf[i] = b
|
||
}
|
||
return buf
|
||
}
|