37 lines
1.1 KiB
Go
37 lines
1.1 KiB
Go
package shadow
|
|
|
|
import (
|
|
"bytes"
|
|
"crypto/aes"
|
|
"crypto/cipher"
|
|
)
|
|
|
|
func AesEncryptCBC(origData []byte, key []byte) []byte {
|
|
block, _ := aes.NewCipher(key)
|
|
blockSize := block.BlockSize()
|
|
origData = pkcs5Padding(origData, blockSize)
|
|
blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
|
|
encrypted := make([]byte, len(origData))
|
|
blockMode.CryptBlocks(encrypted, origData)
|
|
return encrypted
|
|
}
|
|
func AesDecryptCBC(encrypted []byte, key []byte) []byte {
|
|
block, _ := aes.NewCipher(key)
|
|
blockSize := block.BlockSize()
|
|
blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
|
|
decrypted := make([]byte, len(encrypted))
|
|
blockMode.CryptBlocks(decrypted, encrypted)
|
|
decrypted = pkcs5UnPadding(decrypted)
|
|
return decrypted
|
|
}
|
|
func pkcs5Padding(ciphertext []byte, blockSize int) []byte {
|
|
padding := blockSize - len(ciphertext)%blockSize
|
|
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
|
|
return append(ciphertext, padtext...)
|
|
}
|
|
func pkcs5UnPadding(origData []byte) []byte {
|
|
length := len(origData)
|
|
unpadding := int(origData[length-1])
|
|
return origData[:(length - unpadding)]
|
|
}
|