You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

34 lines
935 B
Go

package cryptokit
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"github.com/mizuki1412/go-core-kit/class/exception"
)
// Encrypt 实现 AES-CBC 加密(返回 Base64 编码结果)
func Encrypt(plainText string) string {
key := "1234567890123456"
iv := "1234567890123456"
block, err := aes.NewCipher([]byte(key))
if err != nil {
panic(exception.New(err.Error()))
}
// PKCS7 填充
paddedText := pkcs7Padding([]byte(plainText), block.BlockSize())
// CBC 模式加密
blockMode := cipher.NewCBCEncrypter(block, []byte(iv))
ciphertext := make([]byte, len(paddedText))
blockMode.CryptBlocks(ciphertext, paddedText)
// Base64 编码
return base64.StdEncoding.EncodeToString(ciphertext)
}
func pkcs7Padding(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...)
}