1 Star 1 Fork 0

窦雪峰 / go-utils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
string_encript.go 2.03 KB
一键复制 编辑 原始数据 按行查看 历史
窦雪峰 提交于 2022-05-14 16:57 . rename strs to strutil
/*
* @Author: i@douxuefeng.cn
* @Date: 2021-10-23 13:44:03
* @LastEditTime: 2022-05-14 16:50:21
* @LastEditors: i@douxuefeng.cn
* @Description:
* @FilePath: \go-utils\strutil\string_encript.go
*/
package strutil
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"encoding/base64"
)
func PKCS7Padding(plaintext []byte, blockSize int) []byte {
padding := blockSize - len(plaintext)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(plaintext, padtext...)
}
func UnPKCS7Padding(origData []byte) []byte {
length := len(origData)
unpadding := int(origData[length-1])
return origData[:(length - unpadding)]
}
/**
* @name: AES加密 cbc
* @description:
* @param {*} origin 需要加密的字符串
* @param {string} cip 密文
* @return {*}
*/
func AesEncrypt(origin, cip string) (string, error) {
origData := []byte(origin)
key := []byte(cip)
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
//AES分组长度为128位,所以blockSize=16,单位字节
blockSize := block.BlockSize()
origData = PKCS7Padding(origData, blockSize)
blockMode := cipher.NewCBCEncrypter(block, key[:blockSize]) //初始向量的长度必须等于块block的长度16字节
crypted := make([]byte, len(origData))
blockMode.CryptBlocks(crypted, origData)
return base64.StdEncoding.EncodeToString(crypted), nil
}
/**
* @name: aes 解密
* @description:
* @param {*} encrypted 加密字符串
* @param {string} cip 密文
* @return {*}
*/
func AesDecrypt(encrypted, cip string) (string, error) {
crypted, _ := base64.StdEncoding.DecodeString(encrypted)
key := []byte(cip)
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
//AES分组长度为128位,所以blockSize=16,单位字节
blockSize := block.BlockSize()
blockMode := cipher.NewCBCDecrypter(block, key[:blockSize]) //初始向量的长度必须等于块block的长度16字节
origData := make([]byte, len(crypted))
blockMode.CryptBlocks(origData, crypted)
origData = UnPKCS7Padding(origData)
return string(origData), nil
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/douxuefeng/go-utils.git
git@gitee.com:douxuefeng/go-utils.git
douxuefeng
go-utils
go-utils
v0.2.2

搜索帮助

344bd9b3 5694891 D2dac590 5694891