# Implementation of Blowfish Encryption and Decryption in Python

We are living in a digital world, where data is stored online across many servers and warehouses. To protect data from theft, data need to be encrypted so that the end-user can’t understand without decrypting. In this article, we will learn what is the Blowfish algorithm and How to encrypt and decrypt data using the Blowfish algorithm in Python.

## Blowfish Algorithm

Blowfish algorithm is an encryption method that was created as a replacement for the DES algorithm. It is essentially quicker than DES and furnishes a good encryption rate with no powerful cryptanalysis strategy found to date.

It is one of the primary, secure block ciphers not expose to any licenses and subsequently freely accessible for anybody to utilize.

We are going to implement Blowfish Algorithm using the PyCrypto module.

PyCrypto package in Python provides various encryption algorithms. PyCrypto package can be installed by using the following command

```pip install pycrypto
```

## Blowfish Encryption

PyCrypto package has a Blowfish module that helps to encrypt and decrypt data using the Blowfish algorithm.

1. Import blowfish module from Crypto.Cipher

2. Create a cipher using the new() method in the blowfish module that new generates a key to encrypt and decrypt data.

3. Get the data that need to be encrypted (Note: length of the data must be 8 multiple).

4. Use the encrypt() method to encrypt the data.

5. Finally, print the encrypted_data.

```from Crypto.Cipher import Blowfish
cipher = Blowfish.new("key must be 4 to 56 bytes")
# input data must multiple of 8
data = input("Enter the data that need to encrypt: ")
encrypted_data = cipher.encrypt(data)
print("The encrypted message is: ", encrypted_data)```

Output

```Enter the data that need to encrypt: CodeSpeedyPython
The encrypted message is: b'\xa6\x8ap=^n\xe2\x04y+\xd7\xf7,\xd128'```

To view encrypted data in the hexadecimal format used the hex() method

`print(encrypted_data.hex())`

Output

`a68a703d5e6ee204792bd7f72cd13238`

## Blowfish Decryption

1. Use the decrypt() method to decrypt the encrypted data.

2. Finally, print the decrypted data.

```from Crypto.Cipher import Blowfish
cipher = Blowfish.new("key must be 4 to 56 bytes")
# input data must multiple of 8
data = input("Enter the data that need to encrypt: ")
encrypted_data = cipher.encrypt(data)
print("The encrypted message is: ", encrypted_data)
decrypted_data = cipher.decrypt(encrypted_data)
print("The decrypted or original message is: ", decrypted_data )```

Output

```Enter the data that need to encrypt: CodeSpeedyPython
The encrypted message is: b'\xa6\x8ap=^n\xe2\x04y+\xd7\xf7,\xd128'
The decrypted or original message is: b'CodeSpeedyPython'```

Also, refer