1

I use AesCryptoServiceProvider in order to perform encryption and decryption using AES. Encryption seems to work, but decryption throws an exception saying "Padding is invalid and cannot be removed".

Here is my code:

Public Function AESEnc(ByVal plain As String, ByVal key As String, ByVal iv As String) As AesResult
    Dim ciphertext As String
    Dim k(31) As Byte
    Dim v(15) As Byte
    Dim ret As AesResult
    Dim pBytes As Byte() = StrToByteArray(plain)
    Dim cipher As New AesCryptoServiceProvider()
    Dim enc As ICryptoTransform
    Dim ms As New MemoryStream
    Dim cs As CryptoStream

    k = StrToByteArray(key)
    v = HexStringByteArrayConverter.HexStringToBytes(iv)
    cipher.Mode = CipherMode.CFB
    cipher.Padding = PaddingMode.PKCS7

    enc = cipher.CreateEncryptor(k, v)
    cs = New CryptoStream(ms, enc, CryptoStreamMode.Write)
    cs.Write(pBytes, 0, pBytes.Length)
    cs.FlushFinalBlock()
    cs.Close()
    ciphertext = HexStringByteArrayConverter.BytesToHexString(ms.ToArray())
    ret.data = ciphertext
    ret.iv = v
    ret.key = k

    Return ret
End Function 'AESEnc

Public Function AESDec(ByVal ciphertext As String, ByVal key As String, ByVal iv As String) As AesResult
    Dim plaintext As String
    Dim k(31) As Byte
    Dim v(15) As Byte
    Dim ret As AesResult
    Dim pBytes As Byte() = StrToByteArray(ciphertext)
    Dim cipher As New AesCryptoServiceProvider()
    Dim dec As ICryptoTransform
    Dim ms As New MemoryStream
    Dim cs As CryptoStream

    k = StrToByteArray(key)
    v = HexStringByteArrayConverter.HexStringToBytes(iv)
    cipher.Mode = CipherMode.CFB
    cipher.Padding = PaddingMode.PKCS7

    dec = cipher.CreateDecryptor(k, v)
    cs = New CryptoStream(ms, dec, CryptoStreamMode.Write)
    cs.Write(pBytes, 0, pBytes.Length)
    cs.FlushFinalBlock()
    cs.Close()
    plaintext = ByteArrayToString(ms.ToArray())
    ret.data = plaintext
    ret.iv = v
    ret.key = k

    Return ret
End Function 'AESDec
  • I had similar issue when doing in WCF rest service, I used the PaddingMode.None to solve the issue. I am no expert, but try that. – surpavan Sep 22 '14 at 17:34
  • ensure that the same key and IV values are used for both encryption and decryption. Additionally, verify that the padding mode is set correctly (e.g., PaddingMode.PKCS7). – evry1falls Aug 29 '23 at 22:41

0 Answers0