go的AES加密

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)]
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值