C# code uses AES to encrypt arrays of bytes.
I have written a Python program using PyCryptodome to do the same thing, but the encrypted bytes are always different from the result when I use the C# code, and I made sure to:
- set the IV to the same value in both (just for test purpose)
- ensure the key is the same in both
- ensure the raw data is the same
What I am encrypting: an array of bytes. The bytes represent primarily TLD-format data.
The Python program will be a part of a utility that will generate streams on the fly that will be processed by a Web application written in C#.
Using http://aes.online-domain-tools.com, I actually could decrypt the bytes produced by the C# code and verify that it's using AES, and that the raw data is correct.
The question is: what else could be the discriminating factor?
Python snippets:
from Crypto.Cipher import AES
from Crypto import Random
from Crypto.Util.Padding import pad
**** Correction ***
aes_cipher = AES.new(bytes(key, 'UTF-8'), AES.MODE_CBC)
#
# Correct, the above call would use a random IV value.
# For debugging & learning purpose, I halted this in the
# debugger and manually set
# aes_cipher.IV = <a given value>
# and used the same IV in the C# code to try and keep all known inputs identical.
#
aes_cipher.block_size = 128
aes_cipher.key_size = 128 # bits
encrypted_pack = aes_cipher.encrypt(pad(pack, 16))
# Tack on to the beginning the 16 bytes of the "IV"
# FYI - the C# decryption function strips off the first 16 IV bytes
encrypted_pack = aes_cipher.IV + encrypted_pack
return encrypted_pack
C# snippets
AesCipher = new RijndaelManaged();
AesCipher.KeySize = 128; // 192, 256
// BlockSize: 128-bit == 16 bytes.
// 128-bit is the default for RijndaelManaged
AesCipher.BlockSize = 128;
AesCipher.Mode = CipherMode.CBC;
AesCipher.Padding = PaddingMode.Zeros;
...
...
#
# Yes, GenerateIV() generates a random IV.
# As mentioned above, I overrode this by setting
# AesCipher.IV = <the same value as above>
#
AesCipher.GenerateIV();
setKey(key); // converts a string of decimal digits to string of hex digits
ICryptoTransform transform = AesCipher.CreateEncryptor();
byte[] encrypted = transform.TransformFinalBlock(buf, 0, buf.Length);
byte[] result = new byte[encrypted.Length + 16];
Buffer.BlockCopy(AesCipher.IV, 0, result, 0, 16);
Buffer.BlockCopy(encrypted, 0, result, 16, encrypted.Length);
return result;
***
Update
***
There was another problem that I just discovered and fixed.
The key was being saved as a 32-byte rather than 16-byte bytearray, which would explain the gigantic discrepancy from online tool results.
Solved easiy with
```byte_key = binascii.unhexlify(key)
Once I did that, the returned by both pieces of code matched, and they matched what was in the online tool, too.
Sneaky because in the debugger, it's easy to miss because the values look the same.