Files
SNCTF/tools/aes.go
jiayuqi7813 7cb171bc90 default
2022-05-21 23:29:23 +08:00

55 lines
1.5 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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
}