增加AES CBC模式工具函数

This commit is contained in:
dushixiang
2021-04-13 23:56:53 +08:00
parent 4f73cd3673
commit 5cee2dd50e
3 changed files with 61 additions and 1 deletions

View File

@ -2,6 +2,8 @@ package utils
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/md5"
"database/sql/driver"
"encoding/base64"
@ -224,3 +226,43 @@ func Check(f func() error) {
logrus.Error("Received error:", err)
}
}
func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext)%blockSize
padText := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padText...)
}
func PKCS5UnPadding(origData []byte) []byte {
length := len(origData)
unPadding := int(origData[length-1])
return origData[:(length - unPadding)]
}
func AesEncryptCBC(origData, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
origData = PKCS5Padding(origData, blockSize)
blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
encrypted := make([]byte, len(origData))
blockMode.CryptBlocks(encrypted, origData)
return encrypted, nil
}
func AesDecryptCBC(encrypted, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
origData := make([]byte, len(encrypted))
blockMode.CryptBlocks(origData, encrypted)
origData = PKCS5UnPadding(origData)
return origData, nil
}