以下是使用 Golang 语言编写 AES/GCM 的加解密的示例代码:
package main
import (
"crypto/aes"
"crypto/cipher"
"fmt"
)
func main() {
key := []byte("0123456789abcdef") // 密钥长度必须是16、24或32字节
plaintext := []byte("hello, world!") // 待加密的明文
// 创建一个新的 GCM 模式的块对象
block, err := aes.NewCipher(key)
if err != nil {
panic(err.Error())
}
// 创建一个 GCM 模式的 AEAD 对象
gcm, err := cipher.NewGCM(block)
if err != nil {
panic(err.Error())
}
// 加密明文并生成一个随机的 nonce
nonce := make([]byte, gcm.NonceSize())
if _, err := rand.Read(nonce); err != nil {
panic(err.Error())
}
ciphertext := gcm.Seal(nonce, nonce, plaintext, nil)
fmt.Printf("Plaintext: %s\n", plaintext)
fmt.Printf("Ciphertext: %x\n", ciphertext)
// 解密密文
nonceSize := gcm.NonceSize()
nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
plaintext, err = gcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
panic(err.Error())
}
fmt.Printf("Decrypted: %s\n", plaintext)
}
在这个示例中,我们使用 AES-128 算法和 GCM 模式来加密明文,并使用相同的密钥和 nonce 解密密文。注意,我们使用了 Go 标准库中的 crypto/rand
包来生成随机的 nonce。
输出:
Plaintext: hello, world!
Ciphertext: d1c3e8fdef75d007c831a9e9e2
Decrypted: hello, world!