AES: 对称加密。AES的基本要求是,采用对称分组密码体制,密钥的长度最少支持为128(16字节)、192(24字节)、256(32字节),分组长度128位,算法应易于各种硬件和软件实现。
步骤:
1、创建结构体AesEncrypter
2、设置key、iv
3、添加加密方法(返回值base64编码)
4、添加解密方法(参数base64解码)
代码如下:
import (
"encoding/base64"
"crypto/aes"
"crypto/cipher"
"bytes"
)
type AesEncrypter struct {
key []byte
iv []byte
block cipher.Block
}
var AesEcpt AesEncrypter
func init() {
AesEcpt.key = []byte("bGcGfWb3Kg2s4gcG")
AesEcpt.iv = []byte("aebksHkG4jAEk2Ag")
var err error
AesEcpt.block, err = aes.NewCipher(AesEcpt.key)
if err != nil {
panic(err)
}
}
// 加密
func (a *AesEncrypter) AesBase64Encrypt(in string) (string, error) {
origData := []byte(in)
origData = PKCS5Padding(origData, a.block.BlockSize())
crypted := make([]byte, len(origData))
// 根据CryptBlocks方法的说明,如下方式初始化crypted也可以
bm := cipher.NewCBCEncrypter(a.block, a.iv)
bm.CryptBlocks(crypted, origData)
var b = base64.StdEncoding.EncodeToString(crypted)
return b, nil
}
// 解密
func (a *AesEncrypter) AesBase64Decrypt(b string) (string, error) {
crypted, err := base64.StdEncoding.DecodeString(b)
if err!=nil{
}
origData := make([]byte, len(crypted))
bm := cipher.NewCBCDecrypter(a.block, a.iv)
bm.CryptBlocks(origData, crypted)
origData = PKCS5UnPadding(origData)
var out = string(origData)
return out, nil
}
func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...)
}
func PKCS5UnPadding(origData []byte) []byte {
length := len(origData)
// 去掉最后一个字节 unpadding 次
unpadding := int(origData[length-1])
return origData[:(length - unpadding)]
}