Search code examples
phppython3des

3DES result in PHP produces different result from 3DES in Python


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!


Solution

  • 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.