ZBLOG

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

以下是使用 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!

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?