0

PHP code:

$key = '111111111111111111111111'; //length: 24
$iv = "\0\0\0\0\0\0\0\0"; //8 bytes
$data = mcrypt_encrypt(MCRYPT_TRIPLEDES, $key, "SECRET", MCRYPT_MODE_CBC, $iv);  
base64_encode($data); 
// Result: ZGF0YQ==

Python code (using m2crypto):

cipher = Cipher(alg='des_ede3_ecb', key="111111111111111111111111", op=encrypt, iv='\0'*8)
ciphertext = cipher.update("SECRET")
ciphertext += cipher.final()
base64.b64encode(ciphertext)
# Result: LhBqW6pGRoQ=

Python code (using pyDes):

k = pyDes.triple_des('111111111111111111111111', mode=pyDes.CBC, IV=b'\0'*8, pad=None, padmode=pyDes.PAD_PKCS5)
d = k.encrypt("SECRET")
base64.b64encode(d)
# Result: LhBqW6pGRoQ=

So Python gets the same result for different library, but PHP not ;/ Anybody see here any bug?

Thank you!

Jim
  • 22,354
  • 6
  • 52
  • 80
User
  • 1,978
  • 5
  • 26
  • 47

1 Answers1

1

PHP mcrypt doesn't handle PKCS5 padding, instead it uses simple zero padding. This is why you get different results compared to Python libs which use PKCS5 padding.

Here a workaround to get PKCS5 padding in PHP: https://chrismckee.co.uk/handling-tripledes-ecb-pkcs5padding-php/

EDIT

I confirm it works with this guy's lib:

$key = '111111111111111111111111';
$x = "SECRET";
print(urldecode(encrypt($x, $key)));

(for some reason he decided to URL encode the result)

$ php test.php 
LhBqW6pGRoQ=

EDIT2

Here is how to use classic padding with pyDes:

import pyDes
import base64

k = pyDes.triple_des('111111111111111111111111', mode=pyDes.CBC, IV=b'\0'*8,
                     pad='\0', padmode=pyDes.PAD_NORMAL)
d = k.encrypt("SECRET")
print base64.b64encode(d)

It gives the same result as mcrypt.

Grapsus
  • 2,714
  • 15
  • 14
  • Thank you for the answer. But the question is how to get the same PHP result in Python? – User May 02 '14 at 15:01
  • Ok, I solved it. k = pyDes.triple_des('111111111111111111111111', mode=pyDes.CBC, IV=b'\0'*8, pad=b'\0') – User May 02 '14 at 15:09
  • No, this wasn't your original question. I edited my answer to demonstrate the usage of normal padding with `pyDes`. – Grapsus May 02 '14 at 15:10
  • You are right, it was additional question ;-) . Anyway, big thanks for help :-) – User May 02 '14 at 15:16