1 Star 0 Fork 0

育子/nuciotsdk

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
encrypt.go 2.03 KB
一键复制 编辑 原始数据 按行查看 历史
育子 提交于 2021-11-21 19:39 . init
package utils
import (
"bytes"
"crypto/aes"
"crypto/cipher"
)
// 定义常量
const (
// 秘钥
PUBLICKEY = "XWCtbPwDn4e6glqc"
// 偏移量
IV = "0000000000000000"
)
// @title PKCS5Padding
// @description 填充明文
func PKCS5Padding(plaintext []byte, blockSize int) []byte {
padding := blockSize - len(plaintext)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(plaintext, padtext...)
}
// @title PKCS5UnPadding
// @description 去除填充数据
func PKCS5UnPadding(origData []byte) []byte {
length := len(origData)
unpadding := int(origData[length-1])
return origData[:(length - unpadding)]
}
// @title PKCS7Padding
// @description 填充明文
func PKCS7Padding(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...)
}
// @title PKCS7UnPadding
// @description 去除填充数据
func PKCS7UnPadding(origData []byte) []byte {
length := len(origData)
unpadding := int(origData[length-1])
return origData[:(length - unpadding)]
}
// @title AesEncrypt
// @description AES加密
func AesEncrypt(origData []byte) ([]byte, error) {
block, err := aes.NewCipher([]byte(PUBLICKEY))
if err != nil {
return nil, err
}
//AES分组长度为 128 位,所以 blockSize=16 字节
blockSize := block.BlockSize()
origData = PKCS5Padding(origData, blockSize)
//初始向量的长度必须等于块block的长度16字节
blockMode := cipher.NewCBCEncrypter(block, []byte(IV))
crypted := make([]byte, len(origData))
blockMode.CryptBlocks(crypted, origData)
return crypted, nil
}
// @title AesDecrypt
// @description AES解密
func AesDecrypt(crypted []byte) ([]byte, error) {
block, err := aes.NewCipher([]byte(PUBLICKEY))
if err != nil {
return nil, err
}
blockMode := cipher.NewCBCDecrypter(block, []byte(IV))
origData := make([]byte, len(crypted))
blockMode.CryptBlocks(origData, crypted)
origData = PKCS5UnPadding(origData)
return origData, nil
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/magicyu90/nuciotsdk.git
git@gitee.com:magicyu90/nuciotsdk.git
magicyu90
nuciotsdk
nuciotsdk
v1.1.8

搜索帮助