Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AES-ECB encryption (Difference between Python Crypto.Cipher and openssl)

i have a problem with encryption using python and openssl.

i wrote this small python script:

#!/usr/bin/python
from Crypto.Cipher import AES

obj = AES.new('Thisisakey123456', AES.MODE_ECB)
message = "Sample text....."
ciphertext = obj.encrypt(message)
print ciphertext

When i run the script with this command:

$ ./enc.py | base64

i get E0lNh0wtSg9lxxKClBEITAo= as a result.

If i do the same (or obviously it's not the same ;) ) in openssl i get another result:

$ echo -n "Sample text....." | openssl aes-128-ecb -k "Thisisakey123456" -nosalt -nopad | base64
yvNTGC+gwUK38uyJXIk/sQ==

What i am doing wrong?? i would expect the same base64 encoded string.

btw: i know ecb is bad, but i just play around, so it's no problem... ;)

like image 833
mg. Avatar asked May 11 '26 11:05

mg.


1 Answers

You can try this command:

echo -n "Sample text....." | openssl aes-128-ecb -K 546869736973616b6579313233343536 -nopad | openssl base64

this explicitly specifies the key in hexadecimals. With -k the following "key" is actually a password, which is converted through an OpenSSL Password Based Key Derivation Function (PBKDF) called EVP_BytesToKey (using one iteration of SHA-1).

The result is E0lNh0wtSg9lxxKClBEITA==. This is not identical to E0lNh0wtSg9lxxKClBEITAo= but that's because Python adds a single newline character \n to the ciphertext, resulting in one extra byte to encode.

like image 157
Maarten Bodewes Avatar answered May 14 '26 02:05

Maarten Bodewes