Data is being encrypted in C# and send to us, I need to write a Python code to decrypt it.
Here is the C# code for encryption:
public static string EncryptString(string key, string plainText)
{
byte[] iv = new byte[16];
byte[] array;
using (Aes aes = Aes.Create())
{
aes.Key = Encoding.UTF8.GetBytes(key);
aes.IV = iv;
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
using (MemoryStream memoryStream = new MemoryStream())
{
using (CryptoStream cryptoStream = new CryptoStream((Stream)memoryStream, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter streamWriter = new StreamWriter((Stream)cryptoStream))
{
streamWriter.Write(plainText);
}
array = memoryStream.ToArray();
}
}
}
return Convert.ToBase64String(array);
}
Here is how the decryption works in C#:
using System;
using System.Security.Cryptography;
using System.Text;
using System.IO;
public class Program
{
public static string DecryptString(string key, string text)
{
byte[] iv = new byte[16];
byte[] buffer = Convert.FromBase64String(text);
using (Aes aes = Aes.Create())
{
aes.Key = Encoding.UTF8.GetBytes(key);
aes.IV = iv;
ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
using (MemoryStream memoryStream = new MemoryStream(buffer))
{
using (CryptoStream cryptoStream = new CryptoStream((Stream)memoryStream, decryptor, CryptoStreamMode.Read))
{
using (StreamReader streamReader = new StreamReader((Stream)cryptoStream))
{
return streamReader.ReadToEnd();
}
}
}
}
}
public static void Main()
{
Console.WriteLine(DecryptString("b14ca5898a4e4133bbce2ea2315a1916","Qri3376EFpjxJdBBauGZLg=="));
}
}
Now I'm trying to decrypt it using Cryptodome, but it doesn't seem to work, either due to incorrect padding, or something else. Here is my Python code for testing purposes:
import hashlib
from Cryptodome.Cipher import AES
import base64
from Crypto import Random
import Crypto.Util.Padding as padding
password = base64.b64decode('somekey') # changed
iv = Random.new().read(16) # Because C# seems to be using Random as well
# print(iv)
aes = AES.new(password, AES.MODE_CBC, iv)
text = 'Qri3376EFpjxJdBBauGZLg==' # It should be '1'
text = base64.b64decode(text)
print(text)
print(aes.decrypt(text))
print(aes.decrypt(text).decode("UTF-16"))
This seemingly works, but returns gibberish:
b'B\xb8\xb7\xdf\xbe\x84\x16\x98\xf1%\xd0Aj\xe1\x99.' b'\x17\xcd5a\x1b-.\xb4h{\x9a\xb2}{R\xf7' 횥濢빝봅ի䁁ẹ
And, if changed to this, as suggested in similar threads:
decryptedPadded = aes.decrypt(text)
decrypted = padding.unpad(decryptedPadded, 16)
print(decrypted.decode('utf-16'))
it returns:
ValueError: Padding is incorrect.
Not sure what to do next