1 Star 0 Fork 0

Wsage/go-framework

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
aes.go 2.69 KB
一键复制 编辑 原始数据 按行查看 历史
sage 提交于 2024-04-03 17:30 . add catch
package utils
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"encoding/hex"
"errors"
"fmt"
)
// AesEncrypt AES加密,CBC
// 注意:aes密钥key的长度必须为16,24,32个字符
func AesEncrypt(origData, key []byte) (string, error) {
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
blockSize := block.BlockSize()
origData = PKCS7Padding(origData, blockSize)
blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
crypted := make([]byte, len(origData))
blockMode.CryptBlocks(crypted, origData)
return EncodeBase64(crypted), nil
}
// AesDecrypt AES解密
func AesDecrypt(baseStr string, key []byte) (origData []byte, aesErr error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
defer func() {
if err := recover(); err != nil {
aesErr = errors.New(fmt.Sprintf("AesDecrypt error: %s", err))
}
}()
crypted, err := DecodeBase64(baseStr)
if err != nil {
return nil, errors.New("baseStr error")
}
blockSize := block.BlockSize()
blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
origData = make([]byte, len(crypted))
blockMode.CryptBlocks(origData, crypted)
origData = PKCS7UnPadding(origData)
return origData, nil
}
// CBCEncrypt CBC加密
func CBCEncrypt(text string, key []byte, iv []byte) (string, error) {
//生成cipher.Block 数据块
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
//填充内容,如果不足16位字符
blockSize := block.BlockSize()
originData := PKCS7Padding([]byte(text), blockSize)
//加密方式
blockMode := cipher.NewCBCEncrypter(block, iv)
//加密,输出到[]byte数组
crypted := make([]byte, len(originData))
blockMode.CryptBlocks(crypted, originData)
return hex.EncodeToString(crypted), nil
}
// CBCDecrypt CBC解密
func CBCDecrypt(sign string, key, iv []byte) (string, error) {
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
//if len(iv)%block.BlockSize() != 0 {
// return "", fmt.Errorf("Invalid iv length %d", block.BlockSize())
//}
ciphertext, err := hex.DecodeString(sign)
if err != nil {
return "", err
}
origin_data := make([]byte, len(ciphertext))
mode := cipher.NewCBCDecrypter(block, iv)
mode.CryptBlocks(origin_data, ciphertext)
return string(PKCS7UnPadding(origin_data)), nil
}
// PKCS7Padding 填充加密块
func PKCS7Padding(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...)
}
// PKCS7UnPadding 清除加密块中填充字节
func PKCS7UnPadding(origData []byte) []byte {
length := len(origData)
unpadding := int(origData[length-1])
return origData[:(length - unpadding)]
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/scottq/go-framework.git
git@gitee.com:scottq/go-framework.git
scottq
go-framework
go-framework
v1.1.46

搜索帮助