You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
34 lines
785 B
Go
34 lines
785 B
Go
1 month ago
|
package security
|
||
|
|
||
|
import (
|
||
|
"crypto/aes"
|
||
|
"crypto/cipher"
|
||
|
"errors"
|
||
|
)
|
||
|
|
||
|
func AESDecrypt(crypted []byte, key []byte) ([]byte, error) {
|
||
|
block, err := aes.NewCipher(key)
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
blockSize := block.BlockSize()
|
||
|
if len(crypted) < blockSize {
|
||
|
return nil, errors.New("ciphertext too short")
|
||
|
}
|
||
|
iv := key[:blockSize]
|
||
|
if len(crypted)%blockSize != 0 {
|
||
|
return nil, errors.New("ciphertext is not a multiple of the block size")
|
||
|
}
|
||
|
blockMode := cipher.NewCBCDecrypter(block, iv)
|
||
|
blockMode.CryptBlocks(crypted, crypted)
|
||
|
crypted = crypted[blockSize:]
|
||
|
crypted = PKCS7UnPadding(crypted)
|
||
|
return crypted, nil
|
||
|
}
|
||
|
|
||
|
func PKCS7UnPadding(origData []byte) []byte {
|
||
|
length := len(origData)
|
||
|
unpadding := int(origData[length-1])
|
||
|
return origData[:(length - unpadding)]
|
||
|
}
|