Hi,
this is how I managed to get blowfish encryption and decryption working on strings that are less or more than 8 characters long.
Hope it's of come use to whoever comes across this.
#!/usr/bin/perl
use strict;
use warnings;
use Crypt::Blowfish;
my $key=pack("H16","0123456789ABCDEF");
sub encrypt_8_chars{
my $plain_text=$_[0];
my $encrypted_data;
my $encrypted_text;
my $cipher = new Crypt::Blowfish $key;
# Enlarge the string to 8 characters by appending with NULL characte
+rs
while(length($plain_text) < 8){
$plain_text=sprintf("%s\0",$plain_text);
}
$encrypted_data=$cipher->encrypt($plain_text); # Take the string and
+ encrypt using blowfish
$encrypted_text=unpack("H16",$encrypted_data);
return $encrypted_text;
} # encrypt_8_chars
sub decrypt_8_chars{
my $encrypted_text=$_[0];
my $encrypted_data;
my $plain_text;
my $cipher = new Crypt::Blowfish $key;
$encrypted_data=pack("H16",$encrypted_text);
$plain_text=$cipher->decrypt($encrypted_data); # Take the string and
+ decrypt using blowfish
$plain_text =~ s/\0//g; # Shrink the string by removing appended wit
+h NULL characters
return $plain_text;
} # decrypt_8_chars
sub encrypt_text{
my $plain_text=$_[0];
my @plain_chunks;
my $plain_chunk;
my $encrypted_text="";
@plain_chunks=($plain_text =~ /.{1,8}/g); # Chop any size of the tex
+t into up to 8 charachers and put each chunk into an array
foreach $plain_chunk (@plain_chunks){
$encrypted_text=sprintf("%s%s",$encrypted_text,encrypt_8_chars($pl
+ain_chunk));
}
return $encrypted_text;
} # encrypt_text
sub decrypt_text{
my $encrypted_text=$_[0];
my @encrypted_chunks;
my $encrypted_chunk;
my $plain_text="";
@encrypted_chunks=($encrypted_text =~ /.{1,16}/g); # Chop any size o
+f the text into up to 16 charachers and put each chunk into an array
foreach $encrypted_chunk (@encrypted_chunks){
$plain_text=sprintf("%s%s",$plain_text,decrypt_8_chars($encrypted_
+chunk));
}
return $plain_text;
} # decrypt_text
my $input;
my $encrypted;
my $decrypted;
printf("Enter the string to encrypt\n");
chomp($input=<STDIN>);
$encrypted=encrypt_text($input);
printf("The encrypted value of %s is %s\n",$input,$encrypted);
$decrypted=decrypt_text($encrypted);
printf("The decrypted value of %s is %s\n",$encrypted,$decrypted);
|