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