1 Star 0 Fork 0

h79/goutils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
pkcs7.go 2.65 KB
一键复制 编辑 原始数据 按行查看 历史
huqiuyun 提交于 2023-07-17 12:17 . BUG: aes 算法
package algorithm
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"fmt"
"io"
)
// PKCS7 for aes
type PKCS7 struct {
}
func NewPKCS7() *PKCS7 {
return &PKCS7{}
}
func (pk *PKCS7) padding(ciphertext []byte, blockSize int) []byte {
return pkcs7Padding(ciphertext, blockSize)
}
func (pk *PKCS7) unPadding(data []byte) []byte {
return pkcs7UnPadding(data)
}
// aes加密,填充秘钥key的16位,24,32分别对应AES-128, AES-192, or AES-256.
func (pk *PKCS7) aesCbcEncrypt(raw, key []byte, iv []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
//填充原文
blockSize := block.BlockSize()
raw = pk.padding(raw, blockSize)
//初始向量IV必须是唯一,但不需要保密
var cipherText []byte
if len(iv) < blockSize {
//block大小 16
cipherText = make([]byte, blockSize+len(raw))
iv = cipherText[:blockSize]
if _, er := io.ReadFull(rand.Reader, iv); er != nil {
return nil, er
}
} else {
cipherText = make([]byte, len(raw))
blockSize = 0
}
//block大小和初始向量大小一定要一致
mode := cipher.NewCBCEncrypter(block, iv)
mode.CryptBlocks(cipherText[blockSize:], raw)
return cipherText, nil
}
func (pk *PKCS7) aesCbcDecrypt(encryptData, aesKey []byte, iv []byte) ([]byte, error) {
block, err := aes.NewCipher(aesKey)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
if len(encryptData) < blockSize {
return nil, fmt.Errorf("ciphertext too short")
}
if len(iv) == 0 {
iv = encryptData[:blockSize]
encryptData = encryptData[blockSize:]
}
// CBC mode always works in whole blocks.
if len(encryptData)%blockSize != 0 {
return nil, fmt.Errorf("ciphertext is not a multiple of the block size")
}
mode := cipher.NewCBCDecrypter(block, iv)
// CryptBlocks can work in-place if the two arguments are the same.
mode.CryptBlocks(encryptData, encryptData)
//解填充
return pk.unPadding(encryptData), nil
}
// Encrypt PKCS interface
func (pk *PKCS7) Encrypt(raw, key []byte) (string, error) {
return pk.EncryptIv(raw, key, nil)
}
// EncryptIv
// 带IV
func (pk *PKCS7) EncryptIv(raw, aesKey []byte, iv []byte) (string, error) {
data, err := pk.aesCbcEncrypt(raw, aesKey, iv)
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(data), nil
}
// Decrypt PKCS interface
func (pk *PKCS7) Decrypt(raw string, key []byte) ([]byte, error) {
return pk.DecryptIv(raw, key, nil)
}
// DecryptIv
// 带IV
func (pk *PKCS7) DecryptIv(raw string, aesKey []byte, iv []byte) ([]byte, error) {
data, err := base64.StdEncoding.DecodeString(raw)
if err != nil {
return nil, err
}
return pk.aesCbcDecrypt(data, aesKey, iv)
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/h79/goutils.git
git@gitee.com:h79/goutils.git
h79
goutils
goutils
v1.8.71

搜索帮助

0d507c66 1850385 C8b1a773 1850385