ZBLOG

Golang 语言编写 AES/GCM 的加解密

以下是使用 Golang 语言编写 AES/GCM 的加解密的示例代码:

  1. package main
  2. import (
  3. "crypto/aes"
  4. "crypto/cipher"
  5. "fmt"
  6. )
  7. func main() {
  8. key := []byte("0123456789abcdef") // 密钥长度必须是16、24或32字节
  9. plaintext := []byte("hello, world!") // 待加密的明文
  10. // 创建一个新的 GCM 模式的块对象
  11. block, err := aes.NewCipher(key)
  12. if err != nil {
  13. panic(err.Error())
  14. }
  15. // 创建一个 GCM 模式的 AEAD 对象
  16. gcm, err := cipher.NewGCM(block)
  17. if err != nil {
  18. panic(err.Error())
  19. }
  20. // 加密明文并生成一个随机的 nonce
  21. nonce := make([]byte, gcm.NonceSize())
  22. if _, err := rand.Read(nonce); err != nil {
  23. panic(err.Error())
  24. }
  25. ciphertext := gcm.Seal(nonce, nonce, plaintext, nil)
  26. fmt.Printf("Plaintext: %s\n", plaintext)
  27. fmt.Printf("Ciphertext: %x\n", ciphertext)
  28. // 解密密文
  29. nonceSize := gcm.NonceSize()
  30. nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
  31. plaintext, err = gcm.Open(nil, nonce, ciphertext, nil)
  32. if err != nil {
  33. panic(err.Error())
  34. }
  35. fmt.Printf("Decrypted: %s\n", plaintext)
  36. }

在这个示例中,我们使用 AES-128 算法和 GCM 模式来加密明文,并使用相同的密钥和 nonce 解密密文。注意,我们使用了 Go 标准库中的 crypto/rand 包来生成随机的 nonce。

输出:

  1. Plaintext: hello, world!
  2. Ciphertext: d1c3e8fdef75d007c831a9e9e2
  3. Decrypted: hello, world!

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=655

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?