Search code examples
phppythondjangoblowfishencryption-symmetric

Howto send encrypted messages between python and php using blowfish for encryption?


I want to encrypt a message in php with a known password using blowfish. I would then be like to decrypt this message in python.

This is useful even if you want to encrypt in one language and decrypt elsewhere.

I searched quite extensively but could not find any conclusive solution, so I thought to record my findings.

Note it is quite simple to encrypt/decrypt in same language such as python or php.


Solution

  • This solution is very simple but it took me a while to figure out.

    Blowfish Params

    • Password should be of length 16
    • use mode MODE_ECB.
    • Data being encrypted length should be always divisible by 16 pad by spaces or anyother char. I have taken a 16 length data string in example below.

    php code:

    <?php
    $passw='secretPassword12';
    $ntext='helloWorld123456';
    $enc = base64_encode(mcrypt_encrypt(MCRYPT_BLOWFISH, $passw, $ntext, MCRYPT_MODE_ECB));
    echo '<div>'.$enc.'</div';
    

    This outputs 3C8f2kaD8Of0INYk3l9qEg== python code:

    from Crypto.Cipher import Blowfish
    from base64 import b64encode, b64decode
    passw='secretPassword12'
    ntext='helloworld123456'
    
    cipher=Blowfish.new(passw, Blowfish.MODE_ECB)
    encStr=b64encode(cipher.encrypt(data))
    print encStr
    

    This code outputs 3C8f2kaD8Of0INYk3l9qEg== too

    Now suppose you want to decrypt some string in python encrypted in php. First do b64decode and then decrypt the result.

    Remember to pad your data such that the len is divisible by 16. 
    

    Happy encrypting and decrypting!!!