本问题的解决方案是使用golang的crypto/aes包。通过将密文解码为字节数组,将其传递给cipher.NewCBCDecrypter并使用给定的密钥和初始向量对其进行解密。最后,我们使用PKCS7填充机制去掉填充。
package main
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"errors"
)
func main() {
key := []byte("0123456789abcdef")
iv := []byte("abcdef0123456789")
ciphertext := []byte{0x6e, 0x9e, 0xc0, 0x1f, 0x25, 0x90, 0xee, 0x40, 0x2d, 0xb2, 0xa9, 0x39, 0xac, 0xa3, 0x3a, 0x67}
plaintext, err := aesCBCDecrypt(key, iv, ciphertext)
if err != nil {
panic(err)
}
println(string(plaintext))
}
func aesCBCDecrypt(key, iv, ciphertext []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
if len(ciphertext)%aes.BlockSize != 0 {
return nil, errors.New("ciphertext is not a multiple of the block size")
}
mode := cipher.NewCBCDecrypter(block, iv)
mode.CryptBlocks(ciphertext, ciphertext)
return pkcs7Unpad(ciphertext), nil
}
func pkcs7Unpad(data []byte) []byte {
length := len(data)
unpadding := int(data[length-1])
return data[:(length - unpadding)]
}
上一篇:AES解密错误