Go AES对称加密

以下是一个使用 Go 语言实现 AES 加密和解密的示例代码:

package main

import (
    "crypto/aes"
    "crypto/cipher"
    "crypto/rand"
    "encoding/hex"
    "fmt"
    "io"
)

// 加密函数
func encryptAES(key []byte, plaintext []byte) ([]byte, error) {
    // 创建一个新的 AES 加密块
    block, err := aes.NewCipher(key)
    if err!= nil {
        return nil, err
    }

    // 创建一个 GCM 模式的 AEAD (Authenticated Encryption with Associated Data)
    aesGCM, err := cipher.NewGCM(block)
    if err!= nil {
        return nil, err
    }

    // 生成随机的 nonce
    nonce := make([]byte, aesGCM.NonceSize())
    if _, err = io.ReadFull(rand.Reader, nonce); err!= nil {
        return nil, err
    }

    // 加密并添加认证标签
    ciphertext := aesGCM.Seal(nonce, nonce, plaintext, nil)
    return ciphertext, nil
}

// 解密函数
func decryptAES(key []byte, ciphertext []byte) ([]byte, error) {
    block, err := aes.NewCipher(key)
    if err!= nil {
        return nil, err
    }

    aesGCM, err := cipher.NewGCM(block)
    if err!= nil {
        return nil, err
    }

    nonceSize := aesGCM.NonceSize()
    if len(ciphertext) < nonceSize {
        return nil, fmt.Errorf("ciphertext too short")
    }

    // 提取 nonce 和密文
    nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]

    // 解密
    plaintext, err := aesGCM.Open(nil, nonce, ciphertext, nil)
    if err!= nil {
        return nil, err
    }
    return plaintext, nil
}

func main() {
    // 密钥(必须是 16、24 或 32 字节)
    key := []byte("my_secret_key_1234567890")
    plaintext := []byte("Hello, AES!")

    ciphertext, err := encryptAES(key, plaintext)
    if err!= nil {
        fmt.Println("Encryption error:", err)
        return
    }

    fmt.Printf("Ciphertext: %x\n", ciphertext)

    decryptedText, err := decryptAES(key, ciphertext)
    if err!= nil {
        fmt.Println("Decryption error:", err)
        return
    }

    fmt.Printf("Decrypted text: %s\n", decryptedText)
}

 

在上述代码中:

  • encryptAES 函数使用给定的密钥对明文进行 AES 加密,并生成随机的 nonce 。
  • decryptAES 函数使用相同的密钥和提取的 nonce 对密文进行解密。

请注意,在实际应用中,密钥的管理和保护非常重要。

  • 6
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值