44 lines
1.0 KiB
Go
44 lines
1.0 KiB
Go
package tool
|
|
|
|
import (
|
|
"bytes"
|
|
"crypto/aes"
|
|
)
|
|
|
|
func PKCS7Padding(ciphertext []byte, blockSize int) []byte {
|
|
padding := blockSize - len(ciphertext)%blockSize
|
|
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
|
|
return append(ciphertext, padtext...)
|
|
}
|
|
|
|
func PKCS7UnPadding(origData []byte) []byte {
|
|
length := len(origData)
|
|
unpadding := int(origData[length-1])
|
|
return origData[:(length - unpadding)]
|
|
}
|
|
|
|
func AesEcbDecryptWithPKCS7Unpadding(data, key []byte) []byte {
|
|
block, _ := aes.NewCipher(key)
|
|
decrypted := make([]byte, len(data))
|
|
size := block.BlockSize()
|
|
|
|
for bs, be := 0, size; bs < len(data); bs, be = bs+size, be+size {
|
|
block.Decrypt(decrypted[bs:be], data[bs:be])
|
|
}
|
|
|
|
return PKCS7UnPadding(decrypted)
|
|
}
|
|
|
|
func AesEcbEncryptWithPKCS7Padding(data, key []byte) []byte {
|
|
block, _ := aes.NewCipher(key)
|
|
data = PKCS7Padding(data, block.BlockSize())
|
|
decrypted := make([]byte, len(data))
|
|
size := block.BlockSize()
|
|
|
|
for bs, be := 0, size; bs < len(data); bs, be = bs+size, be+size {
|
|
block.Encrypt(decrypted[bs:be], data[bs:be])
|
|
}
|
|
|
|
return decrypted
|
|
}
|