from Crypto.Cipher import Blowfish from Crypto import Random key = b'my_secret_key_123' iv = Random.new().read(Blowfish.block_size) cipher = Blowfish.new(key, Blowfish.MODE_CBC, iv) message = 'Hello, world!'.encode() # Padding the message to be a multiple of 8 message = message + b'\0' * (Blowfish.block_size - len(message) % Blowfish.block_size) ciphertext = iv + cipher.encrypt(message) print("Encrypted message:", ciphertext) decipher = Blowfish.new(key, Blowfish.MODE_CBC, iv) plaintext = decipher.decrypt(ciphertext[Blowfish.block_size:]) plaintext = plaintext.rstrip(b'\0') print("Decrypted message:", plaintext.decode())
from Crypto.Cipher import Blowfish from Crypto import Random key = b'my_secret_key_123' iv = Random.new().read(Blowfish.block_size) cipher = Blowfish.new(key, Blowfish.MODE_CBC, iv) with open('filename.txt', 'rb') as source_file: with open('encrypted_file.txt', 'wb') as dest_file: dest_file.write(iv) while True: chunk = source_file.read(Blowfish.block_size) if len(chunk) == 0: break elif len(chunk) % Blowfish.block_size != 0: chunk += b'\0' * (Blowfish.block_size - len(chunk) % Blowfish.block_size) dest_file.write(cipher.encrypt(chunk))In the above examples, we used the Crypto.Cipher Blowfish package library to encrypt and decrypt a message and encrypt a file. The encryption and decryption process involves initializing the Blowfish object with a key and an initialization vector (iv) and then using it to encrypt or decrypt the message or file. We also used the padding scheme to ensure that the message or file is a multiple of the block size.