5

PHP code:

$key = "12345678abcdefgh12345678abcdefgh";
$iv = "12345678abcdefgh";
$plaindata = "This is a test string.";

$enc = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $plaindata, MCRYPT_MODE_CBC, $iv));

echo($enc);

Result:

QBN0Yue3D9hBrBuD01n5KWG+lv2doMf97cKm/AeusAI=

How can this be decrypted in Python?

dreftymac
  • 31,404
  • 26
  • 119
  • 182
user812120
  • 585
  • 1
  • 10
  • 21

2 Answers2

7

Try something like this (altho i do have PyCrypto installed)

from Crypto.Cipher import AES
import base64

AES.key_size=128
iv="your iv"
key="your key"
crypt_object=AES.new(key=key,mode=AES.MODE_CBC,IV=iv)

decoded=base64.b64decode(plain) # your ecrypted and encoded text goes here
decrypted=crypt_object.decrypt(decoded)

This will bring the decoded text but it will be padded with bytes for it to be a size multiple of 16.

You should probably decide on a proper padding scheme and remove it afterwards accordingly

omu_negru
  • 4,642
  • 4
  • 27
  • 38
  • Thank you very much. Just in case somebody is stuck with installing PyCrypto, follow the instructions here http://apprenticealf.wordpress.com/2011/01/14/windows-python-ebooks-and-drm/ – user812120 May 10 '12 at 15:12
  • 1
    I got this error `TypeError: argument of type 'int' is not iterable` – AKMalkadi Mar 08 '22 at 09:27
-9

Read the manual, its pretty well documented.

data = base64.b64decode('QBN0Yue3D9hBrBuD01n5KWG+lv2doMf97cKm/AeusAI=')
TJHeuvel
  • 12,403
  • 4
  • 37
  • 46
  • Your question was to decrypt the base64 result. After encrypting something one way you cant revert it. Thats the point of it. – TJHeuvel May 10 '12 at 12:59
  • `base64.decode` takes two arguments, so your code will raise a `TypeError`. I think you meant to use `base64.b64decode` or `base64.decodestring`. Also, what is with the semi-colon, and your answer does not decrypt the decoded string. – Chris May 10 '12 at 13:02
  • In PHP, there's a decrypt function for mcrypt. I believe what OP wants is an equivalent to this, in addition to `base64.b64decode` of course. http://www.php.net/manual/en/function.mcrypt-decrypt.php – jadkik94 May 10 '12 at 13:03
  • I can decrypt in PHP, I just need to decrypt the final result in Python to get back the plain data "This is a test string." – user812120 May 10 '12 at 13:06