I have been given an existing encryption algorithm that is required to encrypt a password before sending it on an API.
I have no previous experience of any other languages than Python and so I am unable to understand what functionally I need to do to replicate this.
I believe the default mode for AES in C# is CBC. I think I've copied most of the work needed but I need to pad the data, and I don't know exactly what stage this occurs, or where the length is added. I don't understand the order things would happen in the C code. I also believe the default padding method is PKCS#7, though I'm happy to be corrected on any of this.
Original code
public static string EncryptStringToBytes_Aes(string username, string password)
{
string encrypted = string.Empty;
byte[] clearBytes = Encoding. UTF8.GetBytes(password);
using (Aes aesAlg = Aes.Create())
{
byte[] k;
byte[] iv;
byte[] bytes = Encoding.UTF8.GetBytes(username);
k = SHA256.Create().ComputeHash(bytes);
iv = MD5.Create().ComputeHash(bytes);
aesAlg.Key = k;
aesAlg.IV = iv;
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key,
aesAlg.IV);
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt,
encryptor, CryptoStreamMode.Write))
{
csEncrypt.Write(clearBytes, 0, clearBytes.Length);
}
encrypted = Convert.ToBase64String(msEncrypt.ToArray());
}
}
return encrypted;
}
python recreation
from Crypto.Cipher import AES
import hashlib
username = "example"
password = "example2"
mode = AES.MODE_CBC
clearbytes = password.encode('utf-8')
bytes = username.encode('utf-8')
key = hashlib.sha256(bytes).digest()
iv = hashlib.md5(bytes).digest()
encryptor = AES.new(key, mode, IV = iv)
length = password + '0' + str(len(clearbytes))
encrypted= encryptor.encrypt(length).encode('base64')
I'm getting a "ValueError: Input strings must be a multiple of 16 in length".
And when I've tried some padding, the encode states "AttributeError: 'bytes' object has no attribute 'encode'"
I'm hoping that someone who can read this code can help me with the final steps to recreate the functionality in Python.
Crypto.Util.Padding, or if you're using PyCrypto you can copy PyCryptodome's padding functions from github. However your C# code doesn't look good: It's using a hash as a kdf, deterministic IV, and no authentication. Those factors may reduce or even break the security of your encryption scheme.