Search code examples
pythonencryptionblowfishcbc-mode

Python Blowfish encryption doesn't give same output as Blowfish.js


Unable to get the same output as blowfish.js in python.

I'm passing the below inputs in https://sladex.org/blowfish.js/ :

  • data_to_encrypt = 'ABCDEFGH'
  • key = 'Fd4595edcb6ddc10'
  • cipher_mode = "CBC"
  • output_type = "base64"

The result is : "tJ1xIcrzYzsk4YwjFccmbA=="

I tried to get the same output in python with the following code but it doesn't give the same output. What am I missing ?

from Crypto.Cipher import Blowfish
from Crypto.Util.Padding import pad
import base64
import os

def encrypt_data(data, key):
    # Ensure the data is a multiple of 8 bytes (64 bits)
    data = pad(data.encode(), 8)

    # Initialize the Blowfish cipher with the provided key
    cipher = Blowfish.new(key.encode(), Blowfish.MODE_CBC, os.urandom(8))

    # Encrypt the data
    ciphertext = cipher.encrypt(data)

    return base64.b64encode(ciphertext).decode()


if __name__ == "__main__":
    data_to_encrypt = 'ABCDEFGH'
    key = 'Fd4595edcb6ddc10'
    cipher_mode = "CBC"
    output_type = "base64"

    encrypted_data = encrypt_data(data_to_encrypt, key)
    print("Encrypted data:", encrypted_data)


Solution

  • The JavaScript implementation you've linked always sets the IV to zeroes:

    this.setIV("0000000000000000", crypto.outputTypes.Hex);
    

    To match that, you'll need to do that in Python too instead of os.urandom(8):

    cipher = Blowfish.new(key.encode(), Blowfish.MODE_CBC, b"\00" * 8)