Search code examples
perlencryptionblowfish

Perl Blowfish/CBC Encryption and Decryption functions


New to Perl and Cryptography here. Does anyone have any simple Encrypt/Decrypt functions (using Blowfish or CBC) that encapsulate all the under-the-hood dirty work? I want to have one fixed KEY to use and be able to pass a string of any length for encryption.

For clarity, I want to encrypt credentials using the Encrypt function, save the result somewhere, and Decrypt it when needed... all the while using the same key.

I basically want to do this:

$fixedKey = "0123456789ABCDEF";
$plainText = "A string of any length..........";

$encryptedString = Encrypt($fixedKey, $plainText); 

$retrievedText = Decrypt($fixedKey, $encryptedString);

Appreciated.


Solution

  • The following uses Crypt::CBC for salting, padding and chaining, and it uses Crypt::Rijndael (AES) for encryption.

    use strict;
    use warnings;
    use feature qw( say );
    use Crypt::CBC qw( );
    
    sub encrypt {
       my ($key, $plaintext) = @_;
    
       my $iv = Crypt::CBC->random_bytes(16);
    
       my $cipher = Crypt::CBC->new(
          -cipher      => 'Rijndael',
          -literal_key => 1,
          -key         => $key,
          -iv          => $iv,
          -header      => 'none',
       );
    
       return $iv . $cipher->encrypt($plaintext);
    }
    
    sub decrypt {
       my ($key, $ciphertext) = @_;
    
       my $iv = substr($ciphertext, 0, 16, '');
    
       my $cipher = Crypt::CBC->new(
          -cipher      => 'Rijndael',
          -literal_key => 1,
          -key         => $key,
          -iv          => $iv,
          -header      => 'none',
       );
    
       return $cipher->decrypt($ciphertext);
    }
    
    {
       my $key = Crypt::CBC->random_bytes(32);
       say "Key: ", unpack "H*", $key;
    
       my $expect = 'secret';
       say "Plaintext: $expect";
    
       my $ciphertext = encrypt($key, $expect);
       say "Ciphertext: ", unpack "H*", $ciphertext;
    
       my $got = decrypt($key, $ciphertext);
       say "Plaintext: $got";
       say $expect eq $got ? "ok" : "not ok";
    }