golang aes256解密
以下是使用Golang进行AES 256位解密的示例代码:
package main
import (
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"fmt"
)
func main() {
key := []byte("my-secret-key-123") // 32字节的秘钥
ciphertext := "encrypted-base64-encoded-string" // 加密后的Base64编码字符串
// 解码加密字符串为字节数组
cipherBytes, err := base64.StdEncoding.DecodeString(ciphertext)
if err != nil {
panic(err.Error())
}
// 创建一个新的AES块,使用给定的密钥
block, err := aes.NewCipher(key)
if err != nil {
panic(err.Error())
}
// 创建一个解密器
mode := cipher.NewCBCDecrypter(block, key[:aes.BlockSize])
// 解密数据
plaintext := make([]byte, len(cipherBytes))
mode.CryptBlocks(plaintext, cipherBytes)
// 去除填充,得到原始数据
plaintext = unpad(plaintext)
fmt.Printf("Decrypted text: %s\n", string(plaintext))
}
// 去除填充
func unpad(data []byte) []byte {
padding := int(data[len(data)-1])
return data[:len(data)-padding]
}
注意,此代码中使用了CBC模式,并且需要使用填充来保证数据块的长度是AES块大小的倍数。在实际使用中,尽量避免使用CBC模式,而使用更安全的GCM模式。另外,秘钥应该是随机生成的,而不是硬编码在代码中
原文地址: https://www.cveoy.top/t/topic/emFR 著作权归作者所有。请勿转载和采集!