golang aes128加密
下面是使用Go语言进行AES-128加密的示例代码:
package main
import (
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"fmt"
)
func main() {
// 待加密的数据
plaintext := []byte("Hello, World!")
// 密钥,长度必须为16字节(128位)
key := []byte("0123456789abcdef")
// 创建一个AES加密算法实例
block, err := aes.NewCipher(key)
if err != nil {
panic(err)
}
// 使用CBC模式加密
iv := make([]byte, aes.BlockSize)
stream := cipher.NewCTR(block, iv)
// 加密
ciphertext := make([]byte, len(plaintext))
stream.XORKeyStream(ciphertext, plaintext)
// 将密文编码为Base64字符串
encoded := base64.StdEncoding.EncodeToString(ciphertext)
fmt.Println("Plaintext:", string(plaintext))
fmt.Println("Ciphertext:", encoded)
}
在上面的示例中,我们使用CBC模式加密,并将密文编码为Base64字符串。如果你需要使用其他的加密模式,可以在创建stream变量时传入相应的参数来实现。
另外,需要注意的是,使用CTR模式加密时,IV(Initialization Vector,初始化向量)需要是一个全零的字节切片。因为CTR模式中不需要IV,但是为了兼容其他加密模式,需要提供一个全零的IV
原文地址: https://www.cveoy.top/t/topic/emX9 著作权归作者所有。请勿转载和采集!