golang实现AES对称加密
发布日期:2021-11-18 19:17:19 浏览次数:11 分类:技术文章

本文共 2021 字,大约阅读时间需要 6 分钟。

什么是AES加密算法?

  高级加密标准(英语:Advanced Encryption Standard,缩写:AES),在密码学中又称Rijndael加密法,是美国联邦政府采用的一种区块加密标准。这个标准用来替代原先的DES,已经被多方分析且广为全世界所使用。经过五年的甄选流程,高级加密标准由美国国家标准与技术研究院(NIST)于2001年11月26日发布于FIPS PUB 197,并在2002年5月26日成为有效的标准。2006年,高级加密标准已然成为对称密钥加密中最流行的算法之一。

举个栗子

发送者 -> “今晚打老虎” -> 接受者

如果明文传输,消息截获者也可以窥探到消息的内容,从而暴露了通信双方的私密。

因此我们改用加密的方式传输密文:

“今晚打老虎” -> AES加密 -> IhxKCpIsg018W2iX7xzrXw== -> AES解密 -> “今晚打老虎”

由于加密和解密的秘钥是相同的,所以AES为对称加密

代码

package mainimport (	"bytes"	"crypto/aes"	"crypto/cipher"	"encoding/base64"	"fmt")func PKCS7Padding(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext)%blockSize padtext := bytes.Repeat([]byte{
byte(padding)}, padding) return append(ciphertext, padtext...)}func PKCS7UnPadding(origData []byte) []byte {
length := len(origData) unpadding := int(origData[length-1]) return origData[:(length - unpadding)]}//AES加密func AesEncrypt(origData, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key) if err != nil {
return nil, err } blockSize := block.BlockSize() origData = PKCS7Padding(origData, blockSize) blockMode := cipher.NewCBCEncrypter(block, key[:blockSize]) crypted := make([]byte, len(origData)) blockMode.CryptBlocks(crypted, origData) return crypted, nil}//AES解密func AesDecrypt(crypted, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key) if err != nil {
return nil, err } blockSize := block.BlockSize() blockMode := cipher.NewCBCDecrypter(block, key[:blockSize]) origData := make([]byte, len(crypted)) blockMode.CryptBlocks(origData, crypted) origData = PKCS7UnPadding(origData) return origData, nil}func main() {
text := "今晚打老虎" AesKey := []byte("0f90023fc9ae101e") //秘钥长度为16的倍数 fmt.Printf("明文: %s\n秘钥: %s\n", text, string(AesKey)) encrypted, err := AesEncrypt([]byte(text), AesKey) if err != nil {
panic(err) } fmt.Printf("加密后: %s\n", base64.StdEncoding.EncodeToString(encrypted)) origin, err := AesDecrypt(encrypted, AesKey) if err != nil {
panic(err) } fmt.Printf("解密后明文: %s\n", string(origin))}

在这里插入图片描述

转载地址:https://blog.csdn.net/weixin_39172380/article/details/97891600 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:go mod使用笔记
下一篇:GO实现RSA加密

发表评论

最新留言

逛到本站,mark一下
[***.202.152.39]2024年04月10日 17时14分18秒