// AesEncrypt 加密
// @origData 要加密的字符串
func (s *Service) AesEncrypt(encryptStr, key []byte) (string, error) {
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
blockSize := block.BlockSize()
encryptStr = s.PKCS7Padding(encryptStr, blockSize)
blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
crypted := make([]byte, len(encryptStr))
blockMode.CryptBlocks(crypted, encryptStr)
return gconv.String(crypted), nil
//// 转成字节数组
//encryptData := []byte(encryptStr)
//k := []byte(key)
//
//// 分组秘钥
//block, _ := aes.NewCipher(k)
//// 获取秘钥块的长度
//blockSize := block.BlockSize()
//// 补全码
//encryptData = s.PKCS7Padding(encryptData, blockSize)
//// 加密模式
//blockMode := cipher.NewCBCEncrypter(block, k[:blockSize])
//// 创建数组
//cryted := make([]byte, len(encryptData))
//// 加密
//blockMode.CryptBlocks(cryted, encryptData)
//
//return base64.StdEncoding.EncodeToString(cryted)
}
// AesDecrypt 解密
// @cryted 需要解密的数据
func (s *Service) AesDecrypt(cryted string, key string) string {
// 转成字节数组
crytedByte, _ := base64.StdEncoding.DecodeString(cryted)
k := []byte(key)
// 分组秘钥
block, _ := aes.NewCipher(k)
// 获取秘钥块的长度
blockSize := block.BlockSize()
// 加密模式
blockMode := cipher.NewCBCDecrypter(block, k[:blockSize])
// 创建数组
orig := make([]byte, len(crytedByte))
// 解密
blockMode.CryptBlocks(orig, crytedByte)
// 去补全码
orig = s.PKCS7UnPadding(orig)
return string(orig)
}
func (s *Service) PKCS7Padding(ciphertext []byte, blocksize int) []byte {
padding := blocksize - len(ciphertext)%blocksize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...)
}
//去码
func (s *Service) PKCS7UnPadding(origData []byte) []byte {
length := len(origData)
unpadding := int(origData[length-1])
return origData[:(length - unpadding)]
}