Search code examples
c#pythonvb.netaes

AES decryption works in python but not in .NET


This python code works perfectly and decrypts the cipher text:

import sys, hexdump, binascii
from Crypto.Cipher import AES
class AESCipher:
def __init__(self, key):
     self.key = key

def decrypt(self, iv, data):
     self.cipher = AES.new(self.key, AES.MODE_CBC, iv)
     return self.cipher.decrypt(data)

key = binascii.unhexlify("0602000000a400005253413100040000")
iv = binascii.unhexlify("0100010067244F436E6762F25EA8D704")
hex_str_cipher = "d690a9d0a592327f99bb4c6a6b6d4cbe" 
ciphertext = binascii.unhexlify(hex_str_cipher)
raw_un = AESCipher(key).decrypt(iv, ciphertext)
password = raw_un.decode('utf-16')
print(password)

but trying to recreate it in VB.NET like so:

Sub Main()
    Dim AesEnc = System.Security.Cryptography.Aes.Create()
    AesEnc.Mode = CipherMode.CBC
    AesEnc.KeySize = 128
    AesEnc.Key = HexToBytes("0602000000a400005253413100040000")
    AesEnc.IV = HexToBytes("0100010067244F436E6762F25EA8D704")
    Dim EncryptedBytes As Byte() = HexToBytes("d690a9d0a592327f99bb4c6a6b6d4cbe")
    Using MemStrm As New IO.MemoryStream(EncryptedBytes)
        Using CryptStrm As New CryptoStream(MemStrm, AesEnc.CreateDecryptor(), CryptoStreamMode.Read)
            Dim PlaintextBytes(EncryptedBytes.Length - 1) As Byte
            CryptStrm.Read(PlaintextBytes, 0, PlaintextBytes.Length)
            Console.WriteLine(System.Text.Encoding.Unicode.GetString(PlaintextBytes))
        End Using
    End Using
End Sub

Public Function HexToBytes(HexString As String) As Byte()
    Dim ByteLength = HexString.Length \ 2
    Dim Bytes(ByteLength - 1) As Byte
    For i = 0 To ByteLength - 1
        Bytes(i) = Convert.ToByte(HexString.Substring(i * 2, 2), 16)
    Next
    Return Bytes
End Function

Always fails on the call to CryptStrm.Read with the error "Padding is invalid and cannot be removed"

I've done AES encryption/decryption in .NET plenty of times before using the routine above, so I can't understand why this fails as if the key/IV is incorrect when its identical to what the python script is using. Any ideas?


Solution

  • Thanks to @OguzOzgul for his comment about padding, I tried adding this line to my .NET code and now it works perfectly

    AesEnc.Padding = PaddingMode.Zeros