This commit is contained in:
jiayuqi7813
2022-05-21 23:29:23 +08:00
parent b8859af6d8
commit 7cb171bc90
83 changed files with 1687 additions and 0 deletions

55
tools/aes.go Normal file
View File

@@ -0,0 +1,55 @@
package tools
import (
"bytes"
"crypto/aes"
"crypto/cipher"
)
var Aeskey = []byte("snowywar12345678") //aeskey
//@brief:填充明文
func PKCS5Padding(plaintext []byte, blockSize int) []byte{
padding := blockSize-len(plaintext)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)},padding)
return append(plaintext,padtext...)
}
//@brief:去除填充数据
func PKCS5UnPadding(origData []byte) []byte{
length := len(origData)
unpadding := int(origData[length-1])
return origData[:(length - unpadding)]
}
//@brief:AES加密
func AesEncrypt(origData, key []byte) ([]byte, error){
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
//AES分组长度为128位所以blockSize=16单位字节
blockSize := block.BlockSize()
origData = PKCS5Padding(origData,blockSize)
blockMode := cipher.NewCBCEncrypter(block,key[:blockSize]) //初始向量的长度必须等于块block的长度16字节
crypted := make([]byte, len(origData))
blockMode.CryptBlocks(crypted,origData)
return crypted, nil
}
//@brief:AES解密
func AesDecrypt(crypted, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, 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 = PKCS5UnPadding(origData)
return origData, nil
}