在IT开发中,经常会涉及到对数据进行加密解密的操作,因此像RSA,AES这些加密解密都是非常常用的。本文主要介绍下AES对称加密解密的案例。示例代码如下:
package main
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"fmt"
"io"
)
func main() {
secret := "1234567890123456"
str := "这是一个测试加密解密的案例"
encryStr := AESCbcEncrypt(secret, str)
fmt.Println("加密后的结果是", encryStr)
decryStr := AESCbcDecrypt(secret, encryStr)
fmt.Println("解密后的结果是", decryStr)
}
/*
*
加密
*/
func AESCbcEncrypt(secretKey, src string) string {
key := []byte(secretKey)
if len(key) > 16 {
key = key[:16]
}
plaintext := []byte(src)
block, err := aes.NewCipher(key)
if err != nil {
panic(err)
}
blockSize := block.BlockSize()
plaintext = Padding(plaintext, blockSize)
if len(plaintext)%aes.BlockSize != 0 {
panic("plaintext is not a multiple of the block size")
}
ciphertext := make([]byte, aes.BlockSize+len(plaintext))
iv := ciphertext[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
panic(err)
}
mode := cipher.NewCBCEncrypter(block, iv)
mode.CryptBlocks(ciphertext[aes.BlockSize:], plaintext)
return base64.StdEncoding.EncodeToString(ciphertext)
}
/*
*
解密
*/
func AESCbcDecrypt(secretKey, src string) string {
key := []byte(secretKey)
ciphertext, _ := base64.StdEncoding.DecodeString(src)
block, err := aes.NewCipher(key)
if err != nil {
panic(err)
}
if len(ciphertext) < aes.BlockSize {
panic("ciphertext too short")
}
iv := ciphertext[:aes.BlockSize]
ciphertext = ciphertext[aes.BlockSize:]
if len(ciphertext)%aes.BlockSize != 0 {
panic("ciphertext is not a multiple of the block size")
}
mode := cipher.NewCBCDecrypter(block, iv)
mode.CryptBlocks(ciphertext, ciphertext)
ciphertext = UnPadding(ciphertext)
return string(ciphertext)
}
func Padding(plainText []byte, blockSize int) []byte {
padding := blockSize - len(plainText)%blockSize
char := []byte{byte(padding)}
newPlain := bytes.Repeat(char, padding)
return append(plainText, newPlain...)
}
func UnPadding(plainText []byte) []byte {
length := len(plainText)
lastChar := plainText[length-1]
padding := int(lastChar)
return plainText[:length-padding]
}这里的加密和解密方法我们直接进行了封装,在使用的时候进行调用即可。最后看看效果:
展示的结果完整的实现了AES加密解密的结果。
备注:
AES加密或者解密的时候需要一个secret。这个secret的字符长度必须是16,24,32个字节长度。即len(secret)必须是16或者24或者32。一定要切记这一点。


还没有评论,来说两句吧...