golang写一段 AES-256 CBC 解密代码 IV为16个0字节 并去补全码
以下是一段使用golang实现AES-256 CBC解密的代码,假设密文和密钥已经存在:
package main
import (
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"fmt"
)
func main() {
key := []byte("12345678901234567890123456789012") // 32字节的AES-256密钥
ciphertext, _ := base64.StdEncoding.DecodeString("p+L6LrZm5yv5lb3uZT5XOw==") // 待解密的密文
block, err := aes.NewCipher(key)
if err != nil {
panic(err)
}
iv := make([]byte, aes.BlockSize) // IV为16个0字节
stream := cipher.NewCBCDecrypter(block, iv)
stream.CryptBlocks(ciphertext, ciphertext)
fmt.Printf("解密后的明文为:%s\n", string(ciphertext))
}
需要注意的几点:
- 在使用AES-CBC加密时,需要一个16字节的初始化向量(IV),用于增加密码强度,防止相同明文加密后得到相同的密文。在这里,我们使用了16个0字节作为IV。
- 在解密时,需要先使用NewCipher函数创建一个AES-256加密块,再使用NewCBCDecrypter函数创建一个解密器,并将IV和加密块传递给解密器。最后使用CryptBlocks函数对密文进行解密
原文地址: https://www.cveoy.top/t/topic/flPK 著作权归作者所有。请勿转载和采集!