Handle malformed encrypted requests without panics

Signed-off-by: Sean Du <do4suki@gmail.com>
This commit is contained in:
2026-07-13 08:03:18 +08:00
parent aebbc4b889
commit b1dfc68a0f
7 changed files with 135 additions and 91 deletions
+24 -10
View File
@@ -4,6 +4,7 @@ import (
"bytes"
"crypto/aes"
"crypto/cipher"
"fmt"
)
var (
@@ -17,32 +18,45 @@ func padding(plainText []byte, blockSize int) []byte {
return plainText
}
func unPadding(cipherText []byte) []byte {
func unPadding(cipherText []byte) ([]byte, error) {
if len(cipherText) == 0 {
return nil, fmt.Errorf("AES plaintext is empty")
}
end := cipherText[len(cipherText)-1]
cipherText = cipherText[:len(cipherText)-int(end)]
return cipherText
if end == 0 || int(end) > len(cipherText) {
return nil, fmt.Errorf("invalid AES padding")
}
for _, value := range cipherText[len(cipherText)-int(end):] {
if value != end {
return nil, fmt.Errorf("invalid AES padding")
}
}
return cipherText[:len(cipherText)-int(end)], nil
}
func AESCBCEncrypt(plainText []byte, key []byte) []byte {
func AESCBCEncrypt(plainText []byte, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
panic(err)
return nil, err
}
plainText = padding(plainText, block.BlockSize())
blockMode := cipher.NewCBCEncrypter(block, iv)
cipherText := make([]byte, len(plainText))
blockMode.CryptBlocks(cipherText, plainText)
return cipherText
return cipherText, nil
}
func AESCBCDecrypt(cipherText []byte, key []byte) []byte {
func AESCBCDecrypt(cipherText []byte, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
panic(err)
return nil, err
}
if len(cipherText) == 0 || len(cipherText)%block.BlockSize() != 0 {
return nil, fmt.Errorf("AES ciphertext must be a non-empty multiple of the block size")
}
plainText := make([]byte, len(cipherText))
blockMode := cipher.NewCBCDecrypter(block, iv)
blockMode.CryptBlocks(plainText, cipherText)
plainText = unPadding(plainText)
return plainText
return unPadding(plainText)
}