golang实现AES加密和解密

package main

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"fmt"
)

func padding(src []byte,blocksize int) []byte {
	padnum:=blocksize-len(src)%blocksize
	pad:=bytes.Repeat([]byte{byte(padnum)},padnum)
	return append(src,pad...)
}

func unpadding(src []byte) []byte {
	n:=len(src)
	unpadnum:=int(src[n-1])
	return src[:n-unpadnum]
}

func encryptAES(src []byte,key []byte) []byte {
	block,_:=aes.NewCipher(key)
	src=padding(src,block.BlockSize())
	blockmode:=cipher.NewCBCEncrypter(block,key)
	blockmode.CryptBlocks(src,src)
	return src
}

func decryptAES(src []byte,key []byte) []byte {
	block,_:=aes.NewCipher(key)
	blockmode:=cipher.NewCBCDecrypter(block,key)
	blockmode.CryptBlocks(src,src)
	src=unpadding(src)
	return src
}

func main()  {
	x:=[]byte("世界上最邪恶最专制的现代奴隶制国家--朝鲜")
	key:=[]byte("hgfedcba87654321")
	x1:=encryptAES(x,key)
	x2:=decryptAES(x1,key)
	fmt.Print(string(x2))
}

 

以下是使用Golang实现AES加密解密的示例代码: ```go package main import ( "crypto/aes" "crypto/cipher" "crypto/rand" "encoding/base64" "fmt" "io" ) func main() { // 原始数据 plaintext := []byte("Hello, World!") // 生成随机的AES密钥 key := make([]byte, 32) if _, err := io.ReadFull(rand.Reader, key); err != nil { panic(err.Error()) } // 创建AES加密器 block, err := aes.NewCipher(key) if err != nil { panic(err.Error()) } // 创建GCM模式的加密器 aesGCM, err := cipher.NewGCM(block) if err != nil { panic(err.Error()) } // 生成随机的Nonce nonce := make([]byte, aesGCM.NonceSize()) if _, err = io.ReadFull(rand.Reader, nonce); err != nil { panic(err.Error()) } // 加密数据 ciphertext := aesGCM.Seal(nil, nonce, plaintext, nil) // 将密钥、Nonce和密文进行Base64编码 encodedKey := base64.StdEncoding.EncodeToString(key) encodedNonce := base64.StdEncoding.EncodeToString(nonce) encodedCiphertext := base64.StdEncoding.EncodeToString(ciphertext) fmt.Println("Encoded Key:", encodedKey) fmt.Println("Encoded Nonce:", encodedNonce) fmt.Println("Encoded Ciphertext:", encodedCiphertext) // 解密数据 decodedKey, _ := base64.StdEncoding.DecodeString(encodedKey) decodedNonce, _ := base64.StdEncoding.DecodeString(encodedNonce) decodedCiphertext, _ := base64.StdEncoding.DecodeString(encodedCiphertext) // 创建AES解密器 decBlock, err := aes.NewCipher(decodedKey) if err != nil { panic(err.Error()) } // 创建GCM模式的解密器 decGCM, err := cipher.NewGCM(decBlock) if err != nil { panic(err.Error()) } // 解密数据 plaintext, err = decGCM.Open(nil, decodedNonce, decodedCiphertext, nil) if err != nil { panic(err.Error()) } fmt.Println("Decrypted Plaintext:", string(plaintext)) } ```
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值