Howto Perl: Crypt::CBC module with the blowfish encryption cipher

I came up with the following example a few years back. Crypt::CBCperl is quite easy to use but can be confusing to new users of it. I prefer to use the subroutines encrypt_hex and decrypt as the encoded string is hexidecimal not in binary format. This allows me to work with it as if it was a normal string, such as sending it in a tweet or email or possibly embed it in an image.

use warnings;
use strict;
use Crypt::CBC;

our $cipher = Crypt::CBC->new(
  -key => 'g0oB3r__g0oB3r',
  -cipher => 'Blowfish'
);

# Encrypts a string and returns it.
sub encrypt {
  return( $cipher->encrypt_hex($_) );
}

# Decrypts an encrypted string and returns it.
sub decrypt {
  return( $cipher->decrypt( pack("H*", $_) ) );
}

#########

my $encrypted_string = encrypt('happy')
my $decrypted_string = decrypt($encrypted_string);

printf "'happy' -> encrypted as '%s' -> decrypted to '%s'\n", $encrypted_string, $decrypted_string;
Share Button

2 Replies to “Howto Perl: Crypt::CBC module with the blowfish encryption cipher”

  1. I’m guessing you are a C programmer? I can tell by the writing style.
    Your code has a lot of lint. Here is a cleaner version of it:

    #!/usr/bin/perl
    use warnings;
    use strict;

    use Crypt::CBC;

    my $cipher = Crypt::CBC->new(
    -key => ‘g0oB3r__g0oB3r’,
    -cipher => ‘Blowfish’,
    );

    my $encrypted_string = encrypt(‘happy’);
    my $decrypted_string = decrypt($encrypted_string);

    printf “‘happy’ -> encrypted as ‘%s’ -> decrypted to ‘%s’n”, $encrypted_string, $decrypted_string;

    # Encrypts a string and returns it.
    sub encrypt {
    $cipher->encrypt_hex(shift);
    }

    # Decrypts an encrypted string and returns it.
    sub decrypt {
    $cipher->decrypt( pack(“H*”, shift) );
    }

    1. Personally I prefer subroutines at the top of the script but putting them at the bottom is okay too.

      I don’t believe using shift instead of $_ will gain us much in this case as we’re only using the first parameter to encrypt() and decrypt(). If we were looping through the parameters I could see the benefit.

Leave a Reply

Your email address will not be published. Required fields are marked *