以下是使用Golang进行AES加解密的示例代码:

package main

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

func main() {
	// 原始数据
	plainText := "Hello, World!"

	// 密钥(16字节)
	key := []byte("0123456789abcdef")

	// 加密
	cipherText, err := encrypt(plainText, key)
	if err != nil {
		fmt.Println("加密失败:", err)
		return
	}
	fmt.Println("加密后的数据:", cipherText)

	// 解密
	decryptedText, err := decrypt(cipherText, key)
	if err != nil {
		fmt.Println("解密失败:", err)
		return
	}
	fmt.Println("解密后的数据:", decryptedText)
}

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

	// 创建一个GCM模式的AES加密器
	gcm, err := cipher.NewGCM(block)
	if err != nil {
		return "", err
	}

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

	// 加密数据
	cipherText := gcm.Seal(nil, nonce, []byte(plainText), nil)

	// 返回Base64编码的加密数据
	return base64.StdEncoding.EncodeToString(cipherText), nil
}

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

	// 创建一个GCM模式的AES解密器
	gcm, err := cipher.NewGCM(block)
	if err != nil {
		return "", err
	}

	// 解码Base64编码的加密数据
	decodedCipherText, err := base64.StdEncoding.DecodeString(cipherText)
	if err != nil {
		return "", err
	}

	// 提取Nonce
	nonceSize := gcm.NonceSize()
	if len(decodedCipherText) < nonceSize {
		return "", fmt.Errorf("加密数据无效")
	}
	nonce := decodedCipherText[:nonceSize]
	cipherText = string(decodedCipherText[nonceSize:])

	// 解密数据
	plainText, err := gcm.Open(nil, nonce, []byte(cipherText), nil)
	if err != nil {
		return "", err
	}

	return string(plainText), nil
}

该示例代码使用AES-256-GCM模式进行加解密,并使用Base64编码对加密数据进行转换。请注意,这里的密钥长度为16字节,如果需要使用其他密钥长度,需要相应地调整代码。

golang aes加解密

原文地址: https://www.cveoy.top/t/topic/ig2O 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录