|
|
OverviewThis script decrypt the files encrypted by Blowfish algorithm into a plain text file. To encrypt, refer to Encrypting a text file.
Flow
A sample code
use Crypt::CBC;
my $key = 'MySecretKey';
my $cipher_options = {
key => "$key",
cipher => 'Blowfish',
salt => 1,
};
my $cipher = Crypt::CBC->new($cipher_options);
my $crfile = 'encrypted.txt';
open (FILE, "< $crfile");
binmode FILE;
my $upfileenc = join '', <FILE>;
close(FILE);
my $plaintext = $cipher->encrypt($upfileenc);
my $textfile = 'orgtext.txt';
open(FILE,"> $textfile");
binmode FILE;
print FILE "$plaintext";
close(FILE);
Description of the codeuse Crypt::CBC; Load Crypt::CBC.
my $key = 'MySecretKey';
my $cipher_options = {
key => "$key",
cipher => 'Blowfish',
salt => 1,
};
Specify options to generate an object of Ctypt::CBC. It uses a reference of a hash when to pass the options to the constracter of Crypt::CBC. $key contains the key of for encryption. This should be passed from input form usually. In this example, MySecretKey is the key of this encryption. The key must be 8 characters or more. Specify cipher a Cipher mode. In this example, Blowfish algorithm is selected. Since slat is set as 1, actual encryption key and a salt of the Initialization Vector is randomly generated by the module. The plain text will be encrypted by the generated key. The generated Initialization Vector is embedded into the encrypted file. For futher options of the Crypt::CBC, Refer to http://search.cpan.org/~lds/Crypt-CBC-2.22/CBC.pm. my $cipher = Crypt::CBC->new($cipher_options); Generate an object of Crypt::CBC. Pass the reference of the hash created prior. Since it is a reference,
my %cipher_options = (
key => "$key",
cipher => 'Blowfish',
salt => 1,
);
my $cipher = Crypt::CBC->new(\%cipher_options);
It can be specify as above.
my $cipher = Crypt::CBC->new({
key => "$key",
cipher => 'Blowfish',
salt => 1,
});
And even as above. my $crfile = 'encrypted.txt'; open (FILE, "< $crfile"); binmode FILE; my $fileenc = join '', <FILE>; close(FILE); Put the contents of the encrypted file into a variable. The text is read through file handle as an array and join it with nulls. In this example, the file is read out one time and put in a veriable. It means that if the file is too big, it use memory accordingly. This method is not recommended if the original text file is huge. It may be a good idea if you use -blocksize option when you generate an object. my $plaintext = $cipher->decrypt($fileenc); Encrypt the text in the variable using the decrypt method. The result of the decryption is the return value and put it into a new variable. The size of the return value should be the same size as original encrypted file. my $textfile = 'plaintext.txt'; open(FILE,"> $textfile"); binmode FILE; print FILE "$plaintext"; close(FILE); Write out the plain text contents into a file. Where, plaintext.txt is the plain text file. |