在Go语言中,可以使用crypto包来实现对称加解密。以下是一个示例代码:

package main

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

func main() {
	// 要加密的原始数据
	plaintext := []byte("Hello, World!")

	// 生成随机的密钥
	key := make([]byte, 32)
	if _, err := io.ReadFull(rand.Reader, key); err != nil {
		panic(err)
	}

	// 创建AES加密器
	block, err := aes.NewCipher(key)
	if err != nil {
		panic(err)
	}

	// 创建加密模式
	ciphertext := make([]byte, aes.BlockSize+len(plaintext))
	iv := ciphertext[:aes.BlockSize]
	if _, err := io.ReadFull(rand.Reader, iv); err != nil {
		panic(err)
	}
	stream := cipher.NewCFBEncrypter(block, iv)
	stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)

	// 将加密后的数据进行Base64编码
	encrypted := base64.StdEncoding.EncodeToString(ciphertext)
	fmt.Println("Encrypted:", encrypted)

	// 解密
	decoded, err := base64.StdEncoding.DecodeString(encrypted)
	if err != nil {
		panic(err)
	}
	decrypted := make([]byte, len(decoded)-aes.BlockSize)
	iv = decoded[:aes.BlockSize]
	decoded = decoded[aes.BlockSize:]
	stream = cipher.NewCFBDecrypter(block, iv)
	stream.XORKeyStream(decrypted, decoded)
	fmt.Println("Decrypted:", string(decrypted))
}

这个示例代码使用AES算法和CFB模式进行加解密,并使用随机生成的密钥和IV(初始向量)。加密后的数据进行了Base64编码,以便于存储和传输。最后,解密出来的数据与原始数据一致

golang 实现对称加解密

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

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