Recently i had a task to add security to file storing. Files had to be encrypted. I chose AES encryption for this.
There are some Perl modules and php classes that can encrypt/decrypt with this encryption.
But there was the system where a file must be encrypted with Perl and then decrypted with PHP. And that was the problem.
Here i will describe how to encrypt/decrypt using AES with Perl. And then in next posts how to do this with PHP and with both together.
First i must to say that AES also known as Rijndael. Curently AES and Rijndael encryption are the same.
There are few Perl modules in the cpan.org that can work with this encryption. They are Crypt::Rijndael, Crypt::OpenSSL::AES and some other. But these 2 are most used as i understand.
First i tried to install Crypt::OpenSSL::AES and i had gotten erro, something like “perl version is too old”. So i had installed Crypt::Rijndael and it works perfect.
There is simple example of encryption a file.
#!/usr/bin/perl -w
use Crypt::Rijndael;
use Digest::MD5 qw(md5 md5_hex md5_base64);
my $key='123';
my $keymd5=md5_hex($key);
$cipher = Crypt::Rijndael->new( $keymd5, Crypt::Rijndael::MODE_CBC() );
open FILE, "image.gif" or die $!;
open FI, "> cryptedimage.gif" or die $!;
binmode FILE;
binmode FI;
my ($buf, $data, $n);
while (($n = read FILE, $data, 16) != 0) {
if($n<16){
$data.="\0" x (16-$n)
}
$crypted = $cipher->encrypt($data);
print FI $crypted;
}
close(FILE);
close(FI);
There is small trick
if($n<16){
$data.="\0" x (16-$n)
}
This encryption can encrypt 16 chars, no more or less. So there i add nulls if length of next part of the file is less 16. It must be the end of the file.
And the code to decrypt the file.
#!/usr/bin/perl -w
use Crypt::Rijndael;
use Digest::MD5 qw(md5 md5_hex md5_base64);
my $key='my key';
my $keymd5=md5_hex($key);
$cipher = Crypt::Rijndael->new( $keymd5, Crypt::Rijndael::MODE_CBC() );
$filesize = -s "cryptedimage.gif";
open FILE, "cryptedimage.gif" or die $!;
open FI, "> image2.gif" or die $!;
binmode FILE;
binmode FI;
my ($buf, $data, $n,$read);
$read=0;
while (($n = read FILE, $data, 16) != 0) {
$read+=$n;
$encrypted = $plaintext = $cipher->decrypt($data);
$encrypted=$1 if($read==$filesize && $encrypted=~/^(.*[^\0])\0+$/);
print FI $encrypted;
}
close(FILE);
close(FI);
In the line
$encrypted=$1 if($read==$filesize && $encrypted=~/^(.*[^\0])\0+$/);
there are deleted nulls in the end of the file. Maybe this was not good idea to add nulls to the end because file can have own nulls. But currently i have no better solution.
So in the next post i am going to describe how to use Rijndael encryption in PHP.