Invalid C # code.
The Encrypt function accepts a passphrase as a string passphrase , but then tries to refer to it in this line byte[] pwdBytes = Encoding.UTF8.GetBytes(key);
Change key to passphrase .
Two functions now give me the same results:
Python
secret_text = 'The rooster crows at midnight!' key = 'A16ByteKey......' mode = AES.MODE_CBC iv = '\x00' * 16 encoder = PKCS7Encoder() padded_text = encoder.encode(secret_text) e = AES.new(key, mode, iv) cipher_text = e.encrypt(padded_text) print(base64.b64encode(cipher_text))
C # (with the above fix)
Console.WriteLine(Encrypt("The rooster crows at midnight!", "A16ByteKey......"));
Python result
XAW5KXVbItrc3WF0xW175UJoiAfonuf + s54w2iEs + 7A =
C # result
XAW5KXVbItrc3WF0xW175UJoiAfonuf + s54w2iEs + 7A =
I suspect you are reusing 'e' in your python code several times. If you uncomment the last two lines of my python script, you will see that the result is now different. But if you uncomment the last three lines, you will see that the output is the same. As Fun said, this has to do with how CBC works .
CBC (Cipher-block chaining) works when encrypting a sequence of bytes in blocks. The first block is encrypted by including IV with the first byte of your plaintext ("Rooster ..."). The second block uses the result of this first operation instead of IV.
When you call e.encrypt() a second time (for example, by highlighting the last two lines of the python script), you select the place where you left off. Instead of using IV when encrypting the first block, it will use the output of the last encrypted block. This is why the results look different. Without commenting on the last three lines of the python script, you initialize a new cipher that will use IV for its first block, which will produce identical results.
source share