1 Star 3 Fork 1

Joshua Conero/uymas

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
cbc.go 1.44 KB
一键复制 编辑 原始数据 按行查看 历史
package aesutil
import (
"crypto/aes"
"crypto/cipher"
"errors"
)
func checkAndGenIv(key, iv []byte, blockSize int) []byte {
if len(iv) == 0 {
iv = key[:blockSize]
} else if len(iv) >= blockSize {
iv = iv[:blockSize]
} else {
iv = ZeroPadding(iv, blockSize)
}
return iv
}
// CbcEncrypt aes cbc encrypt, refer to https://pkg.go.dev/crypto/cipher@latest#example-NewCBCDecrypter
func CbcEncrypt(plaintext, key, iv []byte) (ciphertext []byte, err error) {
block, err := AdjustKey(key)
if err != nil {
return nil, err
}
blockSize := block.BlockSize()
if len(plaintext)%blockSize != 0 {
plaintext = ZeroPadding(plaintext, block.BlockSize())
}
ciphertext = make([]byte, len(plaintext))
iv = checkAndGenIv(key, iv, blockSize)
mode := cipher.NewCBCEncrypter(block, iv)
mode.CryptBlocks(ciphertext, plaintext)
return ciphertext, nil
}
func CbcDecrypt(cipherText, key, iv []byte) (plaintext []byte, err error) {
block, err := AdjustKey(key)
if err != nil {
return nil, err
}
if len(cipherText) < aes.BlockSize {
return nil, errors.New("ciphertext too short")
}
blockSize := block.BlockSize()
if len(cipherText)%blockSize != 0 {
return nil, errors.New("ciphertext is not a multiple of the block size")
}
plaintext = make([]byte, len(cipherText))
iv = checkAndGenIv(key, iv, blockSize)
mode := cipher.NewCBCDecrypter(block, iv)
mode.CryptBlocks(plaintext, cipherText)
plaintext = ZeroUnPadding(plaintext)
return plaintext, nil
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/conero/uymas.git
git@gitee.com:conero/uymas.git
conero
uymas
uymas
v2.0.0-rc.4

搜索帮助