How to use the PERL Blowfish Encryption Module with Padding Capabilities

August 26, 2007

If you have a scenerio when encryption is necessary for your data, a perl script utilizing the Crypt::Blowfish module to get the job done may be your answer. The code is pretty straight foward however it has an additional padding section which helps you negotiate data not matching your designated encryption key size.

The first script encrypts and pads data from a plaintext.txt file using Crypt::Blowfish into a ciphertext.txt file. The second script decrypts the cipher and writes it to a file.

blowfish.pl

#!/usr/bin/perl
use Crypt::Blowfish;
$key = '12345678123456781234567812345678';
$cipher = Crypt::Blowfish->new($key);
open (PLAINTEXT, "plaintext.txt");
while (read(PLAINTEXT, $block, 8)) {
$len  = length $block;
$size += $len;
# Add padding if necessary
$block .= "\000"x(8-$len) if $len < 8;
$ciphertext .= $cipher->encrypt($block);
}
# Record the size of the plaintext, so that the recipient
# knows how much padding to remove.
open (CIPHERTEXT, ">ciphertext.txt");
print CIPHERTEXT "$size\n";
print CIPHERTEXT $ciphertext;

decryptblowfish.pl

#!/usr/bin/perl
use Crypt::Blowfish;
$key = '12345678123456781234567812345678';
$cipher = Crypt::Blowfish->new($key);
open (CIPHERTEXT, "ciphertext.txt");
$size = <CIPHERTEXT>;
while (read(CIPHERTEXT, $ct, 8)) {
$pt .= $cipher->decrypt($ct);
}
# Write only $size bytes of the output; ignore padding.
open (PLAINTEXT, ">decrypted.txt");
print PLAINTEXT substr($pt, 0, $size);

Comments for “How to use the PERL Blowfish Encryption Module with Padding Capabilities”

  1. “->” is “->” ?

    Thank’s. Nice tutorial

  2. Sorry for the wacky characters, I upgraded wordpress and they got messed up. I fixed it now. Glad you like the tutorial.

  3. Eduardo commented on March 11, 2014

    Thank you very much! helped me.

  4. Dominik Ernst commented on January 27, 2016

    Hello Phil

    a very good example, it helped a lot.

    Thx and greetings from Germany

    Dominik

Leave a Reply