代码拉取完成,页面将自动刷新
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
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。