Crypt-CBC-3.04/0000755000175000017500000000000014050502334012500 5ustar lsteinlsteinCrypt-CBC-3.04/README0000644000175000017500000000442312043731413013365 0ustar lsteinlsteinThis is Crypt::CBC, a Perl-only implementation of the cryptographic cipher block chaining mode (CBC). In combination with a block cipher such as Crypt::DES or Crypt::IDEA, you can encrypt and decrypt messages of arbitrarily long length. The encrypted messages are compatible with the encryption format used by B. WARNING: Crypt::CBC versions 2.17 and higher will not decrypt messages encrypted with versions 2.16 and lower unless you pass certain options to the new() call. This was done for very good reasons. Please see README.compatibility for details. Prerequisites ------------- In addition to this module you will need to install the MD5 module, and one or more of: Crypt::DES, Crypt::DES_EDE3, Crypt::IDEA, Crypt::Blowfish, or Crypt::Rijndael modules. 1. Digest::MD5 Required for key and iteration vector generation. 2. Crypt::DES Required for the DES encryption algorithm. 3. Crypt::DES_EDE3 Required for the triple DES encryption algorithm in Encrypt Decrypt Encrypt mode. Note, this depends on Crypt::DES. 4. Crypt::IDEA Required for the IDEA encryption algorithm. 5. Crypt::Blowfish Required for the Blowfish encryption algorithm. 6. Crypt::Blowfish_PP Required for the Blowfish_PP encryption algorithm. 7. Crypt::Rijndael Required for the Rijndael/AES encryption algorithm. You can find these modules on a CPAN server near you! Unfortunately, Crypt::TripleDES does not work with this module, owing to the fact that it does not follow the same API as the other Crypt::* modules. Please write to TripleDES's author, Vipul Ved Prakash and ask him to fix this. Installing Crypt::CBC --------------------- The rest is easy 1. perl Makefile.PL 2. make 3. make test 4. make install Versions 1.22 and greater generate a random initialization vector, rather than generating one based on the key. Not only is this much more secure, but it maintains compatibility with the current version of OpenSSL, which does the same thing as of version 0.9.5. For backwards compatibility, messages encrypted with older versions of Crypt::CBC can be decrypted with the newer version. The reverse is not true -- the beginning messages encrypted by the new version and decrypted by the old may be contaminated with "junk". Lincoln D. Stein lstein@cshl.org Crypt-CBC-3.04/t/0000755000175000017500000000000014050502334012743 5ustar lsteinlsteinCrypt-CBC-3.04/t/null_data.t0000644000175000017500000000224614010243174015077 0ustar lsteinlstein#!/usr/bin/perl use strict; use lib './lib','./blib/lib'; sub test; my (@mods,@pads,@in,$pad,$test_data,$mod,$tnum,$c,$i,$p); @mods = qw/ Cipher::AES Rijndael Blowfish Blowfish_PP IDEA DES /; @pads = qw/standard oneandzeroes space null/; for $mod (@mods) { eval "use Crypt::$mod(); 1" && push @in,$mod; } unless ($#in > -1) { print "1..0 # Skipped: no cryptographic modules found\n"; exit; } print '1..', 128*($#in + 1) * ($#pads + 1) + 1, "\n"; sub test { local($^W) = 0; my($num, $true,$msg) = @_; $$num++; print($true ? "ok $$num\n" : "not ok $$num $msg\n"); } $tnum = 0; eval "use Crypt::CBC"; test(\$tnum,!$@,"Couldn't load module"); for my $mod (@in) { for my $pad (@pads) { my $cipher = Crypt::CBC->new(-key => 'secret', -cipher => $mod, -padding => $pad, -pbkdf => 'opensslv2', ); for my $length (1..128) { my $test_data = 'a'x$length . '0'; my $encrypted = $cipher->encrypt_hex($test_data); my $decrypted = $cipher->decrypt_hex($encrypted); test(\$tnum,$test_data eq $decrypted,"$mod/$pad: match failed on zero-terminated data length $length"); } } } Crypt-CBC-3.04/t/func.t0000644000175000017500000000610414010243174014064 0ustar lsteinlstein#!/usr/local/bin/perl use lib '../lib','./lib','./blib/lib'; # using globals and uninit variables here for convenience no warnings; @mods = qw/ Cipher::AES Rijndael Blowfish Blowfish_PP IDEA DES /; @pads = qw/standard oneandzeroes space null/; for $mod (@mods) { eval "use Crypt::$mod(); 1" && push @in,$mod; } unless ($#in > -1) { print "1..0 # Skipped: no cryptographic modules found\n"; exit; } # ($#in + 1): number of installed modules # ($#pads + 1): number of padding methods # 64: number of per-module, per-pad tests # 1: the first test -- loading Crypt::CBC module print '1..', ($#in + 1) * ($#pads + 1) * 64 + 1, "\n"; $tnum = 0; eval "use Crypt::CBC"; test(\$tnum,!$@,"Couldn't load module"); for $mod (@in) { for $pad (@pads) { $test_data = <new(-key => 'secret', -cipher => $mod, -padding => $pad, -pbkdf => 'opensslv2', ), "Couldn't create new object"); test(\$tnum,$c = $i->encrypt($test_data),"Couldn't encrypt"); test(\$tnum,$p = $i->decrypt($c),"Couldn't decrypt"); test(\$tnum,$p eq $test_data,"Decrypted ciphertext doesn't match plaintext with cipher=$mod, pad=$pad and plaintext size=".length $test_data); # now try various truncations of the whole string. # iteration 3 ends in ' ' so 'space should fail for ($c=1;$c<=7;$c++) { substr($test_data,-$c) = ''; if ($c == 3 && $pad eq 'space') { test(\$tnum,$i->decrypt($i->encrypt($test_data)) ne $test_data); } else { test(\$tnum,$i->decrypt($i->encrypt($test_data)) eq $test_data); } } # try various short strings for ($c=0;$c<=18;$c++) { $test_data = 'i' x $c; test(\$tnum,$i->decrypt($i->encrypt($test_data)) eq $test_data); } # try adding a "\001" to the end of the string for ($c=0;$c<=31;$c++) { $test_data = 'i' x $c; $test_data .= "\001"; test(\$tnum,$i->decrypt($i->encrypt($test_data)) eq $test_data,"failed to decrypt with cipher=$mod, padding=$pad, and plaintext length=".($c+1)); } # 'space' should fail. others should succeed. $test_data = "This string ends in some spaces "; if ($pad eq 'space') { test(\$tnum,$i->decrypt($i->encrypt($test_data)) ne $test_data); } else { test(\$tnum,$i->decrypt($i->encrypt($test_data)) eq $test_data); } # 'null' should fail. others should succeed. $test_data = "This string ends in a null\0"; if ($pad eq 'null') { test(\$tnum,$i->decrypt($i->encrypt($test_data)) ne $test_data); } else { test(\$tnum,$i->decrypt($i->encrypt($test_data)) eq $test_data); } } } sub test { my($num, $true, $msg) = @_; $msg ||= "cipher=$mod, padding=$pad, plaintext length=$c"; $$num++; print($true ? "ok $$num\n" : "not ok $$num $msg\n"); } Crypt-CBC-3.04/t/onezeropadding.t0000644000175000017500000000201414010243174016135 0ustar lsteinlstein#!/usr/local/bin/perl use lib './lib','./blib/lib'; my (@mods,@pads,@in,$tnum); @mods = qw/ Cipher::AES Rijndael Blowfish Blowfish_PP IDEA DES /; for $mod (@mods) { eval "use Crypt::$mod(); 1" && push @in,$mod; } unless ($#in > -1) { print "1..0 # Skipped: no cryptographic modules found\n"; exit; } else { print "1..2\n"; } sub test { local($^W) = 0; my($num, $true,$msg) = @_; $$num++; print($true ? "ok $$num\n" : "not ok $$num $msg\n"); } $tnum = 0; eval "use Crypt::CBC"; print STDERR "using Crypt\:\:$in[0] for testing\n"; test(\$tnum,!$@,"Couldn't load module"); my $cipher = Crypt::CBC->new( -key => 'aaab', -cipher => $in[0], -padding => "oneandzeroes", -pbkdf => 'opensslv2', ); my $string = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAX'; my $work = $cipher->encrypt($string); #Encrypt string my $plain = $cipher->decrypt($work); #...and decrypt test(\$tnum,$string eq $plain,"oneandzeroes padding not working\n"); Crypt-CBC-3.04/t/Blowfish.t0000644000175000017500000000264214010243174014711 0ustar lsteinlstein#!/usr/local/bin/perl use lib './lib','../lib','./blib/lib'; eval "use Crypt::Blowfish()"; if ($@) { print "1..0 # Skipped: Crypt::Blowfish not installed\n"; exit; } print "1..33\n"; sub test { local($^W) = 0; my($num, $true,$msg) = @_; print($true ? "ok $num\n" : "not ok $num $msg\n"); } $test_data = <new(-pass=>'secret',-cipher=>'Blowfish',-nodeprecate=>1),"Couldn't create new object"); test(3,$c = $i->encrypt($test_data),"Couldn't encrypt"); test(4,$p = $i->decrypt($c),"Couldn't decrypt"); test(5,$p eq $test_data,"Decrypted ciphertext doesn't match plaintext"); # now try various truncations of the whole for (my $c=1;$c<=7;$c++) { substr($test_data,-$c) = ''; # truncate test(5+$c,$i->decrypt($i->encrypt($test_data)) eq $test_data); } # now try various short strings for (my $c=0;$c<=18;$c++) { $test_data = 'i' x $c; test (13+$c,$i->decrypt($i->encrypt($test_data)) eq $test_data); } # make sure that strings that end in spaces or nulls are treated correctly $test_data = "This string ends in a null\0"; test (32,$i->decrypt($i->encrypt($test_data)) eq $test_data); $test_data = "This string ends in some spaces "; test (33,$i->decrypt($i->encrypt($test_data)) eq $test_data); Crypt-CBC-3.04/t/AES.t0000644000175000017500000000270014010243174013537 0ustar lsteinlstein#!/usr/bin/perl use lib '../lib','./lib','./blib/lib'; eval "use Crypt::Cipher::AES()"; if ($@) { print "1..0 # Skipped: Crypt::Cipher::AES not installed\n"; exit; } print "1..33\n"; sub test { local($^W) = 0; my($num, $true,$msg) = @_; print($true ? "ok $num\n" : "not ok $num $msg\n"); } $test_data = <new(-pass=>'secret', -cipher => 'Cipher::AES', -pbkdf => 'pbkdf2' ),"Couldn't create new object"); test(3,$c = $i->encrypt($test_data),"Couldn't encrypt"); test(4,$p = $i->decrypt($c),"Couldn't decrypt"); test(5,$p eq $test_data,"Decrypted ciphertext doesn't match plaintext"); # now try various truncations of the whole for (my $c=1;$c<=7;$c++) { substr($test_data,-$c) = ''; # truncate test(5+$c,$i->decrypt($i->encrypt($test_data)) eq $test_data); } # now try various short strings for (my $c=0;$c<=18;$c++) { $test_data = 'i' x $c; test (13+$c,$i->decrypt($i->encrypt($test_data)) eq $test_data); } # make sure that strings that end in spaces or nulls are treated correctly $test_data = "This string ends in a null\0"; test (32,$i->decrypt($i->encrypt($test_data)) eq $test_data); $test_data = "This string ends in some spaces "; test (33,$i->decrypt($i->encrypt($test_data)) eq $test_data); Crypt-CBC-3.04/t/DES.t0000644000175000017500000000261014010243174013542 0ustar lsteinlstein#!/usr/bin/perl -w use lib './lib','./blib/lib'; eval "use Crypt::DES()"; if ($@) { print "1..0 # Skipped: Crypt::DES not installed\n"; exit; } print "1..33\n"; sub test { local($^W) = 0; my($num, $true,$msg) = @_; print($true ? "ok $num\n" : "not ok $num $msg\n"); } $test_data = <new(-pass=>'secret',-cipher=>'DES',-pbkdf=>'pbkdf2'),"Couldn't create new object"); test(3,$c = $i->encrypt($test_data),"Couldn't encrypt"); test(4,$p = $i->decrypt($c),"Couldn't decrypt"); test(5,$p eq $test_data,"Decrypted ciphertext doesn't match plaintext"); # now try various truncations of the whole for (my $c=1;$c<=7;$c++) { substr($test_data,-$c) = ''; # truncate test(5+$c,$i->decrypt($i->encrypt($test_data)) eq $test_data); } # now try various short strings for (my $c=0;$c<=18;$c++) { $test_data = 'i' x $c; test (13+$c,$i->decrypt($i->encrypt($test_data)) eq $test_data); } # make sure that strings that end in spaces or nulls are treated correctly $test_data = "This string ends in a null\0"; test (32,$i->decrypt($i->encrypt($test_data)) eq $test_data); $test_data = "This string ends in some spaces "; test (33,$i->decrypt($i->encrypt($test_data)) eq $test_data); Crypt-CBC-3.04/t/pbkdf.t0000644000175000017500000000165014010243174014220 0ustar lsteinlstein#!/usr/local/bin/perl use lib '../blib/lib','../lib','./lib'; use strict; use Test; my $open_ssl_expected; BEGIN { $open_ssl_expected = { opensslv1 => {key => 'DFB4CADC622054E432B94423894DED3FF1CD3887DED9E23EB943C316F57A7901', iv => 'A43CCFB9D40566E759BF1E890833C05D' }, opensslv2 => {key => '429D56D40A7BAEB4462F9024DB29AD7C3F1ABF6DF91A6AA4EB461D76CA238317', iv => '104179D56A0EB898EF3254F3F81901C5' }, pbkdf2 => {iv => '8BD84A68D9F1C640A1530C21D31CAF7C', key=> 'F383A9DF2698C85EF21FCC8C3394182BAA344E733D71A11F65FEE88DC001C01A'}, }; plan tests => keys(%$open_ssl_expected) * 2; } use Crypt::CBC::PBKDF; for my $method (keys %$open_ssl_expected) { my $pb = Crypt::CBC::PBKDF->new($method); my ($key,$iv) = $pb->key_and_iv('12345678','foobar'); ok(uc unpack('H*',$key),$open_ssl_expected->{$method}{key}); ok(uc unpack('H*',$iv),$open_ssl_expected->{$method}{iv}); } exit 0; Crypt-CBC-3.04/t/nopadding.t0000644000175000017500000000207014037170232015075 0ustar lsteinlstein#!/usr/local/bin/perl use lib '../lib','./lib','./blib/lib'; my (@mods,@pads,@in,$tnum); @mods = qw/ Cipher::AES Rijndael Blowfish Blowfish_PP IDEA DES /; for $mod (@mods) { eval "use Crypt::$mod(); 1" && push @in,$mod; } unless ($#in > -1) { print "1..0 # Skipped: no cryptographic modules found\n"; exit; } else { print "1..2\n"; } sub test { local($^W) = 0; my($num, $true,$msg) = @_; $$num++; print($true ? "ok $$num\n" : "not ok $$num $msg\n"); } $tnum = 0; eval "use Crypt::CBC"; print STDERR "using Crypt\:\:$in[0] for testing\n"; test(\$tnum,!$@,"Couldn't load module"); my $key = "\x00" x "Crypt::$in[0]"->keysize; my $iv = "\x00" x "Crypt::$in[0]"->blocksize; my $cipher = Crypt::CBC->new( { cipher => $in[0], key => $key, iv => $iv, literal_key => 1, header => 'none', padding => 'none', nodeprecate=>1, } ); my $string = 'A' x "Crypt::$in[0]"->blocksize; test(\$tnum,length $cipher->encrypt($string) == "Crypt::$in[0]"->blocksize,"nopadding not working\n"); exit 0; Crypt-CBC-3.04/t/Rijndael.t0000644000175000017500000000264114010243174014663 0ustar lsteinlstein#!/usr/local/bin/perl -Tw use lib './lib','./blib/lib'; eval "use Crypt::Rijndael()"; if ($@) { print "1..0 # Skipped: Crypt::Rijndael not installed\n"; exit; } print "1..33\n"; sub test { local($^W) = 0; my($num, $true,$msg) = @_; print($true ? "ok $num\n" : "not ok $num $msg\n"); } $test_data = <new(-pass=>'secret',-cipher=>'Rijndael',-pbkdf=>'opensslv2'),"Couldn't create new object"); test(3,$c = $i->encrypt($test_data),"Couldn't encrypt"); test(4,$p = $i->decrypt($c),"Couldn't decrypt"); test(5,$p eq $test_data,"Decrypted ciphertext doesn't match plaintext"); # now try various truncations of the whole for (my $c=1;$c<=7;$c++) { substr($test_data,-$c) = ''; # truncate test(5+$c,$i->decrypt($i->encrypt($test_data)) eq $test_data); } # now try various short strings for (my $c=0;$c<=18;$c++) { $test_data = 'i' x $c; test (13+$c,$i->decrypt($i->encrypt($test_data)) eq $test_data); } # make sure that strings that end in spaces or nulls are treated correctly $test_data = "This string ends in a null\0"; test (32,$i->decrypt($i->encrypt($test_data)) eq $test_data); $test_data = "This string ends in some spaces "; test (33,$i->decrypt($i->encrypt($test_data)) eq $test_data); Crypt-CBC-3.04/t/preexisting.t0000644000175000017500000000463614010243174015502 0ustar lsteinlstein#!/usr/local/bin/perl -w use strict; use lib './lib','./blib/lib'; my (@mods,$cipherclass,$i,$c,$p,$test_data); @mods = qw/ Cipher::AES Eksblowfish Rijndael Blowfish Blowfish_PP IDEA DES /; for my $mod (@mods) { if (eval "use Crypt::$mod(); 1") { $cipherclass = $mod eq 'IDEA' ? $mod : "Crypt::$mod"; warn "Using $cipherclass for test\n"; last; } } unless ($cipherclass) { print "1..0 # Skipped: No cryptographic module suitable for testing\n"; exit; } print "1..34\n"; sub test { local($^W) = 0; my($num, $true,$msg) = @_; print($true ? "ok $num\n" : "not ok $num $msg\n"); } $test_data = <blocksize} || 8; my $ks = eval{$cipherclass->keysize} || $bs; my $key = Crypt::CBC->_get_random_bytes($ks); my $cipher = $cipherclass eq 'Crypt::Eksblowfish' ? $cipherclass->new(8,Crypt::CBC->_get_random_bytes(16),$key) :$cipherclass->new($key); test(2,$i = Crypt::CBC->new(-cipher=>$cipher,-pbkdf=>'opensslv2'),"Couldn't create new object"); test(3,$c = $i->encrypt($test_data),"Couldn't encrypt"); test(4,$p = $i->decrypt($c),"Couldn't decrypt"); test(5,$p eq $test_data,"Decrypted ciphertext doesn't match plaintext"); # now try various truncations of the whole for (my $c=1;$c<=7;$c++) { substr($test_data,-$c) = ''; # truncate test(5+$c,$i->decrypt($i->encrypt($test_data)) eq $test_data); } # now try various short strings for (my $c=0;$c<=18;$c++) { $test_data = 'i' x $c; test (13+$c,$i->decrypt($i->encrypt($test_data)) eq $test_data); } # make sure that strings that end in spaces or nulls are treated correctly $test_data = "This string ends in a null\0"; test (32,$i->decrypt($i->encrypt($test_data)) eq $test_data); $test_data = "This string ends in some spaces "; test (33,$i->decrypt($i->encrypt($test_data)) eq $test_data); # test that we can change the hasher if (eval "use Crypt::PBKDF2::Hash::HMACSHA1; 1") { my $hasher = Crypt::PBKDF2::Hash::HMACSHA1->new; $i = Crypt::CBC->new(-cipher => $cipher, -hasher => $hasher, -pbkdf => 'pbkdf2', ); test(34,$i->decrypt($i->encrypt($test_data)) eq $test_data); } else { print "ok 34 # skip Crypt::PBKDF2::Hash::HMACSHA1 not found\n"; } Crypt-CBC-3.04/t/parameters.t0000644000175000017500000003322314050501615015277 0ustar lsteinlstein#!/usr/bin/perl use strict; use lib '../lib','./lib','./blib/lib'; sub test ($$); my $plaintext = <new(-bad_parm=>1,-pass=>'test')}; test(!$crypt,"new() accepted an unknown parameter"); test($@ =~ /not a recognized argument/,"bad parameter error message not emitted"); $crypt = eval {Crypt::CBC->new( -cipher => 'Crypt::Crypt8', -key => 'test key', -nodeprecate=>1) }; test(defined $crypt,"$@Can't continue!"); test($crypt->header_mode eq 'salt',"Default header mode is not 'salt'"); exit 0 unless $crypt; # tests for the salt header $crypt = eval {Crypt::CBC->new(-cipher => 'Crypt::Crypt8', -key => 'test key', -header => 'salt', -nodeprecate=>1, ) }; test(defined $crypt,"$@Can't continue!"); exit 0 unless $crypt; test(!defined $crypt->iv, "IV is defined after new() but it shouldn't be"); test(!defined $crypt->salt,"salt is defined after new() but it shouldn't be"); test(!defined $crypt->key, "key is defined after new() but it shouldn't be"); $ciphertext1 = $crypt->encrypt($plaintext); test($ciphertext1 =~ /^Salted__/s,"salted header not present"); test(defined $crypt->iv, "IV not defined after encrypt"); test(defined $crypt->salt, "salt not defined after encrypt"); test(defined $crypt->key, "key not defined after encrypt"); my ($old_iv,$old_salt,$old_key) = ($crypt->iv,$crypt->salt,$crypt->key); $ciphertext2 = $crypt->encrypt($plaintext); test($ciphertext2 =~ /^Salted__/s,"salted header not present"); test($old_iv ne $crypt->iv, "IV didn't change after an encrypt"); test($old_salt ne $crypt->salt, "salt didn't change after an encrypt"); test($old_key ne $crypt->key, "key didn't change after an encrypt"); test($plaintext eq $crypt->decrypt($ciphertext1),"decrypted text doesn't match original"); test($old_iv eq $crypt->iv, "original IV wasn't restored after decryption"); test($old_salt eq $crypt->salt, "original salt wasn't restored after decryption"); test($old_key eq $crypt->key, "original key wasn't restored after decryption"); test($crypt->passphrase eq 'test key',"get passphrase()"); $crypt->passphrase('new key'); test($crypt->passphrase eq 'new key',"set passphrase()"); test(length($crypt->random_bytes(20)) == 20,"get_random_bytes()"); # tests for the randomiv header $crypt = eval {Crypt::CBC->new(-cipher => 'Crypt::Crypt8', -key => 'test key', -header => 'randomiv', -nodeprecate=>1, ) }; test(defined $crypt,"$@\nCan't continue!"); exit 0 unless $crypt; test($crypt->header_mode eq 'randomiv',"wrong header mode"); test($crypt->pbkdf eq 'randomiv',"wrong key derivation mode"); test(!defined $crypt->iv, "IV is defined after new() but it shouldn't be"); test(!defined $crypt->salt,"salt is defined after new() but it shouldn't be"); test(!defined $crypt->key, "key is defined after new() but it shouldn't be"); $ciphertext1 = $crypt->encrypt($plaintext); test($ciphertext1 =~ /^RandomIV/s,"RandomIV header not present"); test(defined $crypt->iv, "IV not defined after encrypt"); test(!defined $crypt->salt, "there shouldn't be a salt after randomIV encryption"); test(defined $crypt->key, "key not defined after encrypt"); ($old_iv,$old_salt,$old_key) = ($crypt->iv,$crypt->salt,$crypt->key); $ciphertext2 = $crypt->encrypt($plaintext); test($ciphertext2 =~ /^RandomIV/s,"RandomIV header not present"); test($old_iv ne $crypt->iv, "IV didn't change after an encrypt"); test($old_key eq $crypt->key, "key changed after an encrypt"); test($plaintext eq $crypt->decrypt($ciphertext1),"decrypted text doesn't match original"); test($old_iv eq $crypt->iv, "original IV wasn't restored after decryption"); # tests for headerless operation $crypt = eval {Crypt::CBC->new(-cipher => 'Crypt::Crypt8', -key => 'test key', -iv => '01234567', -nodeprecate=>1, -header => 'none') }; test(defined $crypt,"$@Can't continue!"); exit 0 unless $crypt; test($crypt->header_mode eq 'none',"wrong header mode"); test($crypt->iv eq '01234567', "IV doesn't match settings"); test(!defined $crypt->key, "key is defined after new() but it shouldn't be"); $ciphertext1 = $crypt->encrypt($plaintext); test(length($ciphertext1) - length($plaintext) <= 8, "ciphertext grew too much"); test($crypt->decrypt($ciphertext1) eq $plaintext,"decrypted ciphertext doesn't match plaintext"); my $crypt2 = Crypt::CBC->new(-cipher => 'Crypt::Crypt8', -salt => $crypt->salt, -key => 'test key', -iv => '01234567', -nodeprecate=>1, -header => 'none'); test($crypt2->decrypt($ciphertext1) eq $plaintext,"decrypted ciphertext doesn't match plaintext"); $crypt2 = Crypt::CBC->new(-cipher => 'Crypt::Crypt8', -key => 'test key', -iv => '76543210', -nodeprecate=>1, -header => 'none'); test($crypt2->decrypt($ciphertext1) ne $plaintext,"decrypted ciphertext matches plaintext but shouldn't"); test($crypt->iv eq '01234567',"iv changed and it shouldn't have"); test($crypt2->iv eq '76543210',"iv changed and it shouldn't have"); # check various bad combinations of parameters that should cause a fatal error my $good_key = Crypt::CBC->random_bytes(Crypt::Crypt8->keysize); my $bad_key = 'foo'; $crypt = eval {Crypt::CBC->new(-cipher => 'Crypt::Crypt8', -key => $good_key, -iv => '01234567', -nodeprecate=>1, -pbkdf => 'none' )}; test(defined $crypt,"$@Can't continue!"); exit 0 unless $crypt; test($crypt->literal_key,"pbkdf 'none' should set literal key flag, but didn't"); test($crypt->key eq $good_key,"couldn't set literal key"); test($crypt->header_mode eq 'none',"-pbkdf=>'none' should set header_mode to 'none', but didn't"); test( !eval{ Crypt::CBC->new(-cipher => 'Crypt::Crypt8', -header => 'randomiv', -key => $bad_key, -iv => '01234567', -nodeprecate=>1, -pbkdf => 'none', ) }, "module accepted a literal key of invalid size"); test( !eval{ Crypt::CBC->new(-cipher => 'Crypt::Crypt16', -header => 'randomiv', -key => $good_key, -iv => '01234567', -nodeprecate=>1, -pbkdf => 'none', ) }, "module accepted a literal key of invalid size"); test( !eval{ Crypt::CBC->new(-cipher => 'Crypt::Crypt8', -header => 'randomiv', -key => $good_key, -iv => '01234567891', -nodeprecate=>1, -pbkdf => 'none' ) }, "module accepted an IV of invalid size"); test( !eval{ Crypt::CBC->new(-cipher => 'Crypt::Crypt16', -header => 'randomiv', -nodeprecate=>1, -key => 'test key') }, "module allowed randomiv headers with a 16-bit blocksize cipher"); if (0) { $crypt = Crypt::CBC->new(-cipher => 'Crypt::Crypt16', -header => 'randomiv', -key => 'test key', -nodeprecate => 1, -insecure_legacy_decrypt => 1); test(defined $crypt,"module didn't honor the -insecure_legacy_decrypt flag:$@Can't continue!"); exit 0 unless $crypt; test($crypt->decrypt("RandomIV01234567".'a'x256),"module didn't allow legacy decryption"); test(!defined eval{$crypt->encrypt('foobar')},"module allowed legacy encryption and shouldn't have"); } else { skip ('-insecure_legacy_decrypt is no longer supported') foreach (53..55); } test( !defined eval {Crypt::CBC->new(-cipher => 'Crypt::Crypt16', -header => 'salt', -key => 'test key', -nodeprecate => 1, -salt => 'bad bad salt!'); }, "module allowed setting of a bad salt"); test( defined eval {Crypt::CBC->new(-cipher => 'Crypt::Crypt16', -header => 'salt', -key => 'test key', -nodeprecate => 1, -salt => 'goodsalt'); }, "module did not allow setting of a good salt"); test( Crypt::CBC->new(-cipher => 'Crypt::Crypt16', -header => 'salt', -key => 'test key', -nodeprecate => 1, -salt => 'goodsalt')->salt eq 'goodsalt', "module did not allow setting and retrieval of a good salt"); test( !defined eval {Crypt::CBC->new(-cipher => 'Crypt::Crypt16', -header => 'badheadermethod', -nodeprecate => 1, -key => 'test key')}, "module allowed setting of an invalid header method, and shouldn't have"); test( !defined eval {Crypt::CBC->new(-cipher => 'Crypt::Crypt16', -header => 'none', -pbkdf => 'none', -key => 'a'x16) }, "module allowed initialization of pbkdf method 'none' without an iv"); test( !defined eval {Crypt::CBC->new(-cipher => 'Crypt::Crypt16', -header => 'none', -nodeprecate => 1, -iv => 'a'x16) }, "module allowed initialization of header_mode 'none' without a key"); $crypt = eval {Crypt::CBC->new(-cipher => 'Crypt::Crypt8', -literal_key => 1, -header => 'none', -key => 'a'x56, -iv => 'b'x8, -nodeprecate => 1, ) }; test(defined $crypt,"unable to create a Crypt::CBC object with the -literal_key option: $@"); test($plaintext eq $crypt->decrypt($crypt->encrypt($plaintext)),'cannot decrypt encrypted data using -literal_key'); test($crypt->passphrase eq '','passphrase should be empty when -literal_key specified'); test($crypt->key eq 'a'x56,'key should match provided -key argument when -literal_key specified'); # test behavior of pbkdf option test($crypt->pbkdf eq 'none','PBKDF should default to "none" when -literal_key provided, but got '.$crypt->pbkdf); $crypt = eval {Crypt::CBC->new(-cipher => 'Crypt::Crypt8',-pass=>'very secret',-nodeprecate=>1)} or warn $@; test($crypt->pbkdf eq 'opensslv1','PBKDF should default to "opensslv1", but got '.$crypt->pbkdf); $crypt = eval {Crypt::CBC->new(-cipher => 'Crypt::Crypt8',-pass=>'very secret',-pbkdf=>'pbkdf2')} or warn $@; test($crypt->pbkdf eq 'pbkdf2','PBKDF not setting properly. Expected "pbkdf2" but got '.$crypt->pbkdf); $crypt = eval {Crypt::CBC->new(-cipher => 'Crypt::Crypt8', -pass=>'very secret', -pbkdf=>'pbkdf2', -hasher=>'HMACSHA3', -iter=>1000)} or warn $@; my $pbkdf = $crypt->pbkdf_obj; test(defined $pbkdf,"PBKDF object not created as expected"); test($pbkdf->{hash_class} eq 'HMACSHA3','pbkdf object hasher not initialized to correct class'); test($pbkdf->{iterations} == 1000,'pbkdf object hasher not initialized to correct number of iterations'); test( !eval {Crypt::CBC->new(-cipher => 'Crypt::Crypt8', -pass=>'very secret', -pbkdf=>'pbkdf2', -iv => 'b'x8, -header=>'randomiv') }, 'module should not allow a header mode of randomiv and a pbkdf not equal to randomiv' ); $crypt = eval {Crypt::CBC->new(-cipher => 'Crypt::Crypt8', -pass=>'very secret', -pbkdf=>'pbkdf2', -iv => 'b'x8, -header=>'none'), } or warn $@; # not sure this test is correct behaviour # test(73,$crypt->pbkdf eq 'none','pbkdf should be set to "none" when header mode of "none" used'); # now test that setting the -salt generates the same key and IV $crypt = eval {Crypt::CBC->new(-cipher => 'Crypt::Crypt8', -pass => 'baby knows me well', -pbkdf => 'pbkdf2', -salt => '01234567')} or warn $@; test($crypt->salt eq '01234567',"can't set salt properly"); $crypt->set_key_and_iv(); # need to do this before there is a key and iv my ($key,$iv) = ($crypt->key,$crypt->iv); $crypt = eval {Crypt::CBC->new(-cipher => 'Crypt::Crypt8', -pass => 'baby knows me well', -pbkdf => 'pbkdf2', -salt => '01234567')} or warn $@; $crypt->set_key_and_iv(); test($crypt->key eq $key,"key changed even when salt was forced"); test($crypt->iv eq $iv,"iv changed even when salt was forced"); $crypt = eval {Crypt::CBC->new(-cipher => 'Crypt::Crypt8', -pass => 'baby knows me well', -pbkdf => 'pbkdf2', -salt => '76543210')} or warn $@; $crypt->set_key_and_iv(); test($crypt->key ne $key,"key didn't change when salt was changed"); $crypt = eval { Crypt::CBC->new(-cipher => 'Crypt::Crypt8', -key => 'xyz', -header => 'salt', -salt => 1); }; test($crypt,"-salt=>1 is generating an exception: $@"); exit 0; my $number = 1; sub test ($$){ local($^W) = 0; my($true,$msg) = @_; $msg =~ s/\n$//; ++$number; print($true ? "ok $number\n" : "not ok $number # $msg\n"); } sub skip { my ($msg) = @_; ++$number; print "ok $number # skip $msg\n"; } package Crypt::Crypt16; sub new { return bless {},shift } sub blocksize { return 16 } sub keysize { return 56 } sub encrypt { return $_[1] } sub decrypt { return $_[1] } package Crypt::Crypt8; sub new { return bless {},shift } sub blocksize { return 8 } sub keysize { return 56 } sub encrypt { return $_[1] } sub decrypt { return $_[1] } Crypt-CBC-3.04/t/CAST5.t0000644000175000017500000000261214010243174013750 0ustar lsteinlstein#!/usr/bin/perl -w use lib './lib','./blib/lib'; eval "use Crypt::CAST5()"; if ($@) { print "1..0 # Skipped: Crypt::CAST5 not installed\n"; exit; } print "1..33\n"; sub test { local($^W) = 0; my($num, $true,$msg) = @_; print($true ? "ok $num\n" : "not ok $num $msg\n"); } $test_data = <new({key=>'secret',cipher=>'CAST5',nodeprecate=>1}),"Couldn't create new object"); test(3,$c = $i->encrypt($test_data),"Couldn't encrypt"); test(4,$p = $i->decrypt($c),"Couldn't decrypt"); test(5,$p eq $test_data,"Decrypted ciphertext doesn't match plaintext"); # now try various truncations of the whole for (my $c=1;$c<=7;$c++) { substr($test_data,-$c) = ''; # truncate test(5+$c,$i->decrypt($i->encrypt($test_data)) eq $test_data); } # now try various short strings for (my $c=0;$c<=18;$c++) { $test_data = 'i' x $c; test (13+$c,$i->decrypt($i->encrypt($test_data)) eq $test_data); } # make sure that strings that end in spaces or nulls are treated correctly $test_data = "This string ends in a null\0"; test (32,$i->decrypt($i->encrypt($test_data)) eq $test_data); $test_data = "This string ends in some spaces "; test (33,$i->decrypt($i->encrypt($test_data)) eq $test_data); Crypt-CBC-3.04/t/Rijndael_compat.t0000644000175000017500000000460214010243174016225 0ustar lsteinlstein#!/usr/bin/perl use strict; use lib '../lib','./lib','./blib/lib'; my ($i, $j, $test_data); eval "use Crypt::Rijndael"; if ($@) { print "1..0 # Skipped: Crypt::Rijndael not installed\n"; exit; } print "1..59\n"; sub test { local($^W) = 0; my($num, $true,$msg) = @_; print($true ? "ok $num\n" : "not ok $num $msg\n"); } sub pad { my ($s,$decrypt) = @_; if ($decrypt eq 'd') { $s =~ s/10*$//s; } else { $s .= '1' . ('0' x (16 - length($s) % 16 - 1) ); } return $s; } $test_data = <blocksize; my $ks = Crypt::Rijndael->keysize; test(1,!$@,"Couldn't load module"); test(2,$i = Crypt::CBC->new(-key => 'a' x $ks, -cipher => 'Rijndael', -iv => 'f' x $bs, -pbkdf => 'none', -header => 'none', -padding => 'rijndael_compat', ), "Couldn't create new object"); test(3,$j = Crypt::Rijndael->new('a' x $ks, Crypt::Rijndael->MODE_CBC), "Couldn't create new object"); test(4,$j->set_iv('f' x $bs)); test(5,$i->decrypt($i->encrypt($test_data)) eq $j->decrypt($j->encrypt($test_data)),"Decrypt doesn't match"); test(6,$i->decrypt($j->encrypt($test_data)) eq $test_data,"Crypt::CBC can't decrypt Rijndael encryption"); test(7,$j->decrypt($i->encrypt($test_data)) eq $test_data,"Rijndael can't decrypt Crypt::CBC encryption"); # now try various truncations of the whole my $t = $test_data; for (my $c=1;$c<=7;$c++) { substr($t,-$c) = ''; # truncate test(7+$c,$t eq pad($i->decrypt($j->encrypt(pad($t,'e'))),'d'),"Crypt::CBC can't decrypt Rijndael encryption"); } $t = $test_data; for (my $c=1;$c<=7;$c++) { substr($t,-$c) = ''; # truncate test(14+$c,$t eq pad($j->decrypt($i->encrypt(pad($t,'e'))),'d'),"Rijndael can't decrypt Crypt::CBC encryption"); } # now try various short strings for (my $c=0;$c<=18;$c++) { my $t = 'i' x $c; test(22+$c,$t eq pad($j->decrypt($i->encrypt(pad($t,'e'))),'d'),"Rijndael can't decrypt Crypt::CBC encryption"); } # now try various short strings for (my $c=0;$c<=18;$c++) { my $t = 'i' x $c; test(41+$c,$t eq pad($j->decrypt($i->encrypt(pad($t,'e'))),'d'),"Rijndael can't decrypt Crypt::CBC encryption"); } Crypt-CBC-3.04/t/OFB.t0000644000175000017500000000300114010243174013530 0ustar lsteinlstein#!/usr/bin/perl use lib './lib','./blib/lib','../lib'; eval "use Crypt::Cipher::AES"; if ($@) { print "1..0 # Skipped: Crypt::Cipher::AES not installed\n"; exit; } print "1..33\n"; sub test { local($^W) = 0; my($num, $true,$msg) = @_; print($true ? "ok $num\n" : "not ok $num $msg\n"); } $test_data = <new(-key => 'secret', -cipher => 'Cipher::AES', -chain_mode => 'ofb', -pbkdf => 'opensslv2', ),"Couldn't create new object"); test(3,$c = $i->encrypt($test_data),"Couldn't encrypt"); test(4,$p = $i->decrypt($c),"Couldn't decrypt"); test(5,$p eq $test_data,"Decrypted ciphertext doesn't match plaintext"); # now try various truncations of the whole for (my $c=1;$c<=7;$c++) { substr($test_data,-$c) = ''; # truncate test(5+$c,$i->decrypt($i->encrypt($test_data)) eq $test_data); } # now try various short strings for (my $c=0;$c<=18;$c++) { $test_data = 'i' x $c; test (13+$c,$i->decrypt($i->encrypt($test_data)) eq $test_data); } # make sure that strings that end in spaces or nulls are treated correctly $test_data = "This string ends in a null\0"; test (32,$i->decrypt($i->encrypt($test_data)) eq $test_data); $test_data = "This string ends in some spaces "; test (33,$i->decrypt($i->encrypt($test_data)) eq $test_data); Crypt-CBC-3.04/t/PCBC.t0000644000175000017500000000273514010243174013646 0ustar lsteinlstein#!/usr/local/bin/perl use lib './lib','./blib/lib'; eval "use Crypt::Cipher::AES"; if ($@) { print "1..0 # Skipped: Crypt::Cipher::AES not installed\n"; exit; } print "1..33\n"; sub test { local($^W) = 0; my($num, $true,$msg) = @_; print($true ? "ok $num\n" : "not ok $num $msg\n"); } $test_data = <new(-key=>'secret', -cipher=>'Cipher::AES', -chain_mode => 'pcbc', -pbkdf => 'pbkdf2', ),"Couldn't create new object"); test(3,$c = $i->encrypt($test_data),"Couldn't encrypt"); test(4,$p = $i->decrypt($c),"Couldn't decrypt"); test(5,$p eq $test_data,"Decrypted ciphertext doesn't match plaintext"); # now try various truncations of the whole for (my $c=1;$c<=7;$c++) { substr($test_data,-$c) = ''; # truncate test(5+$c,$i->decrypt($i->encrypt($test_data)) eq $test_data); } # now try various short strings for (my $c=0;$c<=18;$c++) { $test_data = 'i' x $c; test (13+$c,$i->decrypt($i->encrypt($test_data)) eq $test_data); } # make sure that strings that end in spaces or nulls are treated correctly $test_data = "This string ends in a null\0"; test (32,$i->decrypt($i->encrypt($test_data)) eq $test_data); $test_data = "This string ends in some spaces "; test (33,$i->decrypt($i->encrypt($test_data)) eq $test_data); Crypt-CBC-3.04/t/Blowfish_PP.t0000644000175000017500000000264614010243174015314 0ustar lsteinlstein#!/usr/local/bin/perl -Tw use lib './lib','./blib/lib'; eval "use Crypt::Blowfish_PP()"; if ($@) { print "1..0 # Skipped: Crypt::Blowfish_PP not installed\n"; exit; } print "1..33\n"; sub test { local($^W) = 0; my($num, $true,$msg) = @_; print($true ? "ok $num\n" : "not ok $num $msg\n"); } $test_data = <new(-pass=>'secret',-cipher=>'Blowfish_PP',-nodeprecate=>1),"Couldn't create new object"); test(3,$c = $i->encrypt($test_data),"Couldn't encrypt"); test(4,$p = $i->decrypt($c),"Couldn't decrypt"); test(5,$p eq $test_data,"Decrypted ciphertext doesn't match plaintext"); # now try various truncations of the whole for (my $c=1;$c<=7;$c++) { substr($test_data,-$c) = ''; # truncate test(5+$c,$i->decrypt($i->encrypt($test_data)) eq $test_data); } # now try various short strings for (my $c=0;$c<=18;$c++) { $test_data = 'i' x $c; test (13+$c,$i->decrypt($i->encrypt($test_data)) eq $test_data); } # make sure that strings that end in spaces or nulls are treated correctly $test_data = "This string ends in a null\0"; test (32,$i->decrypt($i->encrypt($test_data)) eq $test_data); $test_data = "This string ends in some spaces "; test (33,$i->decrypt($i->encrypt($test_data)) eq $test_data); Crypt-CBC-3.04/t/IDEA.t0000644000175000017500000000265014010243174013635 0ustar lsteinlstein#!/usr/local/bin/perl -Tw use lib './lib','./blib/lib'; eval "use Crypt::IDEA()"; if ($@) { print "1..0 # Skipped: Crypt::IDEA not installed\n"; exit; } print "1..33\n"; sub test { local($^W) = 0; my($num, $true,$msg) = @_; print($true ? "ok $num\n" : "not ok $num $msg\n"); } $test_data = <new(-pass=>'secret', -cipher=>'IDEA', -nodeprecate=>1, ),"Couldn't create new object"); test(3,$c = $i->encrypt($test_data),"Couldn't encrypt"); test(4,$p = $i->decrypt($c),"Couldn't decrypt"); test(5,$p eq $test_data,"Decrypted ciphertext doesn't match plaintext"); # now try various truncations of the whole for (my $c=1;$c<=7;$c++) { substr($test_data,-$c) = ''; # truncate test(5+$c,$i->decrypt($i->encrypt($test_data)) eq $test_data); } # now try various short strings for (my $c=0;$c<=18;$c++) { $test_data = 'i' x $c; test (13+$c,$i->decrypt($i->encrypt($test_data)) eq $test_data); } # make sure that strings that end in spaces or nulls are treated correctly $test_data = "This string ends in a null\0"; test (32,$i->decrypt($i->encrypt($test_data)) eq $test_data); $test_data = "This string ends in some spaces "; test (33,$i->decrypt($i->encrypt($test_data)) eq $test_data); Crypt-CBC-3.04/eg/0000755000175000017500000000000014050502334013073 5ustar lsteinlsteinCrypt-CBC-3.04/eg/aes.pl0000755000175000017500000000353614034672217014224 0ustar lsteinlstein#!/usr/bin/perl use lib '../blib/lib'; use Getopt::Std; use Crypt::CBC; use strict vars; my %options; getopts('edk:p:i:o:',\%options) || die <$options{'o'}") or die "$options{'o'}: $!" if $options{'o'}; my $decrypt = $options{'d'} and !$options{'e'}; my $key = $options{'k'} || $options{'p'} || get_key(!$decrypt); my $cipher = Crypt::CBC->new(-pass => $key, -cipher => 'Crypt::Cipher::AES', -pbkdf => 'pbkdf2', -chain_mode => 'ctr', ) || die "Couldn't create CBC object"; $cipher->start($decrypt ? 'decrypt' : 'encrypt'); my $in; while (@ARGV) { my $file = shift @ARGV; open(ARGV,$file) || die "$file: $!"; print $cipher->crypt($in) while read(ARGV,$in,1024); close ARGV; } print $cipher->finish; sub get_key { my $verify = shift; local($|) = 1; local(*TTY); open(TTY,"/dev/tty"); my ($key1,$key2); system "stty -echo ); if ($verify) { print STDERR "\r\nRe-type key: "; chomp($key2 = ); print STDERR "\r\n"; print STDERR "The two keys don't match. Try again.\r\n" unless $key1 eq $key2; } else { $key2 = $key1; } } until $key1 eq $key2; system "stty echo $options{'o'}") || die "$options{'o'}: $!" if $options{'o'}; my $key = $options{'k'} || get_key(); # DES used by default my $cipher = Crypt::CBC->new(-key => $key, -cipher=> 'DES', -salt => 1) || die "Couldn't create CBC object"; my $decrypt = $options{'d'} and !$options{'e'}; $cipher->start($decrypt ? 'decrypt' : 'encrypt'); my $in; while (@ARGV) { my $file = shift @ARGV; open(ARGV,$file) || die "$file: $!"; print $cipher->crypt($in) while read(ARGV,$in,1024); close ARGV; } print $cipher->finish; sub get_key { local($|) = 1; local(*TTY); open(TTY,"/dev/tty"); my ($key1,$key2); system "stty -echo ); print STDERR "\r\nRe-type key: "; chomp($key2 = ); print STDERR "\r\n"; print STDERR "The two keys don't match. Try again.\r\n" unless $key1 eq $key2; } until $key1 eq $key2; system "stty echo $options{'o'}") or die "$options{'o'}: $!" if $options{'o'}; my $key = $options{'k'} || get_key(); my $cipher = Crypt::CBC->new(-key => $key, -cipher => 'IDEA', -salt => 1, ) || die "Couldn't create CBC object"; my $decrypt = $options{'d'} and !$options{'e'}; $cipher->start($decrypt ? 'decrypt' : 'encrypt'); my $in; while (@ARGV) { my $file = shift @ARGV; open(ARGV,$file) || die "$file: $!"; print $cipher->crypt($in) while read(ARGV,$in,1024); close ARGV; } print $cipher->finish; sub get_key { local($|) = 1; local(*TTY); open(TTY,"/dev/tty"); my ($key1,$key2); system "stty -echo ); print STDERR "\r\nRe-type key: "; chomp($key2 = ); print STDERR "\r\n"; print STDERR "The two keys don't match. Try again.\r\n" unless $key1 eq $key2; } until $key1 eq $key2; system "stty echo key derivation functions use strict; use File::Basename 'dirname','basename'; use Carp 'croak'; sub new { my $class = shift; my $subclass = shift; my $options = shift; my $package = __PACKAGE__."::$subclass"; eval "use $package; 1" or croak "Could not load $subclass: $@"; return $package->create(%$options); } # returns a series of subclasses sub list { my $self = shift; my $dir = dirname(__FILE__); my @pm_files = <$dir/PBKDF/*.pm>; my @subclasses; foreach (@pm_files) { my $base = basename($_); $base =~ s/\.pm$//; push @subclasses,$base; } return @subclasses; } sub generate_hash { my $self = shift; my ($salt,$passphrase) = @_; croak "generate() method not implemented in this class. Use one of the subclasses",join(',',$self->list); } sub key_and_iv { my $self = shift; croak 'usage $obj->salt_key_iv($salt,$passphrase)' unless @_ == 2; my $hash = $self->generate_hash(@_); my $key = substr($hash,0,$self->{key_len}); my $iv = substr($hash,$self->{key_len},$self->{iv_len}); return ($key,$iv); } 1; Crypt-CBC-3.04/lib/Crypt/CBC/PBKDF/0000755000175000017500000000000014050502334015564 5ustar lsteinlsteinCrypt-CBC-3.04/lib/Crypt/CBC/PBKDF/opensslv1.pm0000644000175000017500000000126214010243174020055 0ustar lsteinlsteinpackage Crypt::CBC::PBKDF::opensslv1; use strict; use base 'Crypt::CBC::PBKDF'; use Digest::MD5 'md5'; # options: # salt_len => 8 default # key_len => 32 default # iv_len => 16 default sub create { my $class = shift; my %options = @_; $options{salt_len} ||= 8; $options{key_len} ||= 32; $options{iv_len} ||= 16; return bless \%options,$class; } sub generate_hash { my $self = shift; my ($salt,$passphrase) = @_; my $desired_len = $self->{key_len} + $self->{iv_len}; my $data = ''; my $d = ''; while (length $data < $desired_len) { $d = md5($d . $passphrase . $salt); $data .= $d; } return $data; } 1; Crypt-CBC-3.04/lib/Crypt/CBC/PBKDF/randomiv.pm0000644000175000017500000000157514010243174017751 0ustar lsteinlsteinpackage Crypt::CBC::PBKDF::randomiv; # This is for compatibility with early (pre v1.0) versions of OpenSSL # THE KEYS GENERATED BY THIS ALGORITHM ARE INSECURE!!! use strict; use base 'Crypt::CBC::PBKDF'; use Digest::MD5 'md5'; # options: # salt_len => 8 default # key_len => 32 default # iv_len => 16 default sub create { my $class = shift; my %options = @_; $options{salt_len} ||= 8; $options{key_len} ||= 32; $options{iv_len} ||= 16; return bless \%options,$class; } sub generate_hash { my $self = shift; my ($salt,$passphrase) = @_; my $desired_len = $self->{key_len}; my $material = md5($passphrase); while (length($material) < $desired_len) { $material .= md5($material); } substr($material,$desired_len) = ''; $material .= Crypt::CBC->_get_random_bytes($self->{iv_len}); return $material; } 1; Crypt-CBC-3.04/lib/Crypt/CBC/PBKDF/none.pm0000644000175000017500000000103614010243174017061 0ustar lsteinlsteinpackage Crypt::CBC::PBKDF::none; use strict; use Carp 'croak'; use base 'Crypt::CBC::PBKDF::opensslv1'; # options: # key_len => 32 default # iv_len => 16 default sub generate_hash { my $self = shift; my ($salt,$passphrase) = @_; # ALERT: in this case passphrase IS the key and the salt is ignored # Croak unless key matches key length my $keylen = $self->{key_len}; length($passphrase) == $keylen or croak "For selected cipher, the key must be exactly $keylen bytes long"; return $passphrase; } 1; Crypt-CBC-3.04/lib/Crypt/CBC/PBKDF/pbkdf2.pm0000644000175000017500000000131314010243174017270 0ustar lsteinlsteinpackage Crypt::CBC::PBKDF::pbkdf2; use strict; use base 'Crypt::CBC::PBKDF'; use Crypt::PBKDF2; # options: # key_len => 32 default # iv_len => 16 default # iterations => 10000 default # hash_class => 'HMACSHA2' default sub create { my $class = shift; my %options = @_; $options{key_len} ||= 32; $options{iv_len} ||= 16; $options{iterations} ||= 10_000; $options{hash_class} ||= 'HMACSHA2'; return bless \%options,$class; } sub generate_hash { my $self = shift; my ($salt,$passphrase) = @_; my $pbkdf2 = Crypt::PBKDF2->new(%$self, output_len => $self->{key_len} + $self->{iv_len}); return $pbkdf2->PBKDF2($salt,$passphrase); } 1; Crypt-CBC-3.04/lib/Crypt/CBC/PBKDF/opensslv2.pm0000644000175000017500000000075114010243174020060 0ustar lsteinlsteinpackage Crypt::CBC::PBKDF::opensslv2; use strict; use base 'Crypt::CBC::PBKDF::opensslv1'; use Digest::SHA 'sha256'; # options: # key_len => 32 default # iv_len => 16 default sub generate_hash { my $self = shift; my ($salt,$passphrase) = @_; my $desired_len = $self->{key_len} + $self->{iv_len}; my $data = ''; my $d = ''; while (length $data < $desired_len) { $d = sha256($d . $passphrase . $salt); $data .= $d; } return $data; } 1; Crypt-CBC-3.04/lib/Crypt/CBC.pm0000644000175000017500000015270114050502224015300 0ustar lsteinlsteinpackage Crypt::CBC; use strict; use Carp 'croak','carp'; use Crypt::CBC::PBKDF; use bytes; use vars qw($VERSION); no warnings 'uninitialized'; $VERSION = '3.04'; use constant RANDOM_DEVICE => '/dev/urandom'; use constant DEFAULT_PBKDF => 'opensslv1'; use constant DEFAULT_ITER => 10_000; # same as OpenSSL default my @valid_options = qw( pass key cipher keysize chain_mode pbkdf nodeprecate iter hasher header iv salt padding literal_key pcbc add_header generate_key prepend_iv ); sub new { my $class = shift; # the _get_*() methods move a lot of the ugliness/legacy logic # out of new(). But the ugliness is still there! my $options = $class->_get_options(@_); eval {$class->_validate_options($options)} or croak $@; my $cipher = $class->_get_cipher_obj($options); my $header_mode = $class->_get_header_mode($options); my ($ks,$bs) = $class->_get_key_and_block_sizes($cipher,$options); my ($pass,$iv,$salt,$key, $random_salt,$random_iv) = $class->_get_key_materials($options); my $padding = $class->_get_padding_mode($bs,$options); my ($pbkdf,$iter, $hc,$nodeprecate) = $class->_get_key_derivation_options($options,$header_mode); my $chain_mode = $class->_get_chain_mode($options); ### CONSISTENCY CHECKS #### # set literal key flag if a key was passed in or the key derivation algorithm is none $key ||= $pass if $pbkdf eq 'none'; # just in case my $literal_key = defined $key; # check length of initialization vector croak "Initialization vector must be exactly $bs bytes long when using the $cipher cipher" if defined $iv and length($iv) != $bs; # chaining mode check croak "invalid cipher block chain mode: $chain_mode" unless $class->can("_${chain_mode}_encrypt"); # KEYSIZE consistency if (defined $key && length($key) != $ks) { croak "If specified by -literal_key, then the key length must be equal to the chosen cipher's key length of $ks bytes"; } # HEADER consistency if ($header_mode eq 'salt') { croak "Cannot use salt-based key generation if literal key is specified" if $literal_key; } elsif ($header_mode eq 'randomiv') { croak "Cannot encrypt using a non-8 byte blocksize cipher when using randomiv header mode" unless $bs == 8 } croak "If a key derivation function (-pbkdf) of 'none' is provided, a literal key and iv must be provided" if $pbkdf eq 'none' && (!defined $key || !defined $iv); croak "If a -header mode of 'randomiv' is provided, then the -pbkdf key derivation function must be 'randomiv' or undefined" if $header_mode eq 'randomiv' and $pbkdf ne 'randomiv'; return bless { 'cipher' => $cipher, 'passphrase' => $pass, 'key' => $key, 'iv' => $iv, 'salt' => $salt, 'padding' => $padding, 'blocksize' => $bs, 'keysize' => $ks, 'header_mode' => $header_mode, 'literal_key' => $literal_key, 'literal_iv' => defined $iv, 'chain_mode' => $chain_mode, 'make_random_salt' => $random_salt, 'make_random_iv' => $random_iv, 'pbkdf' => $pbkdf, 'iter' => $iter, 'hasher' => $hc, 'nodeprecate' => $nodeprecate, },$class; } sub filehandle { my $self = shift; $self->_load_module('Crypt::FileHandle') or croak "Optional Crypt::FileHandle module must be installed to use the filehandle() method"; if (ref $self) { # already initialized return Crypt::FileHandle->new($self); } else { # create object return Crypt::FileHandle->new($self->new(@_)); } } sub encrypt (\$$) { my ($self,$data) = @_; $self->start('encrypting'); my $result = $self->crypt($data); $result .= $self->finish; $result; } sub decrypt (\$$){ my ($self,$data) = @_; $self->start('decrypting'); my $result = $self->crypt($data); $result .= $self->finish; $result; } sub encrypt_hex (\$$) { my ($self,$data) = @_; return join('',unpack 'H*',$self->encrypt($data)); } sub decrypt_hex (\$$) { my ($self,$data) = @_; return $self->decrypt(pack 'H*',$data); } # call to start a series of encryption/decryption operations sub start (\$$) { my $self = shift; my $operation = shift; croak "Specify ncryption or ecryption" unless $operation=~/^[ed]/i; delete $self->{'civ'}; $self->{'buffer'} = ''; $self->{'decrypt'} = $operation=~/^d/i; $self->_deprecation_warning; } sub chain_mode { shift->{chain_mode} || 'cbc' } sub chaining_method { my $self = shift; my $decrypt = shift; # memoize this result return $self->{chaining_method}{$decrypt} if exists $self->{chaining_method}{$decrypt}; my $cm = $self->chain_mode; my $code = $self->can($decrypt ? "_${cm}_decrypt" : "_${cm}_encrypt"); croak "Chain mode $cm not supported" unless $code; return $self->{chaining_method}{$decrypt} = $code; } # call to encrypt/decrypt a bit of data sub crypt (\$$){ my $self = shift; my $data = shift; my $result; croak "crypt() called without a preceding start()" unless exists $self->{'buffer'}; my $d = $self->{'decrypt'}; unless ($self->{civ}) { # block cipher has not yet been initialized $result = $self->_generate_iv_and_cipher_from_datastream(\$data) if $d; $result = $self->_generate_iv_and_cipher_from_options() unless $d; } my $iv = $self->{'civ'}; $self->{'buffer'} .= $data; my $bs = $self->{'blocksize'}; croak "When using no padding, plaintext size must be a multiple of $bs" if $self->_needs_padding and $self->{'padding'} eq \&_no_padding and length($data) % $bs; croak "When using rijndael_compat padding, plaintext size must be a multiple of $bs" if $self->_needs_padding and $self->{'padding'} eq \&_rijndael_compat and length($data) % $bs; return $result unless (length($self->{'buffer'}) >= $bs); my @blocks = unpack("(a$bs)*",$self->{buffer}); $self->{buffer} = ''; # if decrypting, leave the last block in the buffer for padding if ($d) { $self->{buffer} = pop @blocks; } else { $self->{buffer} = pop @blocks if length $blocks[-1] < $bs; } my $code = $self->chaining_method($d); # $self->$code($self->{crypt},\$iv,\$result,\@blocks); # calling the code sub directly is slightly faster for some reason $code->($self,$self->{crypt},\$iv,\$result,\@blocks); $self->{'civ'} = $iv; # remember the iv return $result; } # this is called at the end to flush whatever's left sub finish (\$) { my $self = shift; my $bs = $self->{'blocksize'}; my $block = $self->{buffer}; # what's left # Special case hack for backward compatibility with Crypt::Rijndael's CBC_MODE. if (length $block == 0 && $self->{padding} eq \&_rijndael_compat) { delete $self->{'civ'}; delete $self->{'buffer'}; return ''; } $self->{civ} ||= ''; my $iv = $self->{civ}; my $code = $self->chaining_method($self->{decrypt}); my $result = ''; if ($self->{decrypt}) { $self->$code($self->{crypt},\$iv,\$result,[$block]); $result = $self->{padding}->($result,$bs,'d') if $self->_needs_padding; } else { $block = $self->{padding}->($block,$bs,'e') if $self->_needs_padding; $self->$code($self->{crypt},\$iv,\$result,[$block]) unless length $block==0 && !$self->_needs_padding } delete $self->{'civ'}; delete $self->{'buffer'}; return $result; } ############# Move the boring new() argument processing here ####### sub _get_options { my $class = shift; my $options = {}; # hashref arguments if (ref $_[0] eq 'HASH') { $options = shift; } # CGI style arguments elsif ($_[0] =~ /^-[a-zA-Z_]{1,20}$/) { my %tmp = @_; while ( my($key,$value) = each %tmp) { $key =~ s/^-//; $options->{lc $key} = $value; } } else { $options->{key} = shift; $options->{cipher} = shift; } return $options; } sub _get_cipher_obj { my $class = shift; my $options = shift; my $cipher = $options->{cipher}; $cipher = 'Crypt::Cipher::AES' unless $cipher; unless (ref $cipher) { # munge the class name if no object passed $cipher = $cipher=~/^Crypt::/ ? $cipher : "Crypt::$cipher"; $cipher->can('encrypt') or eval "require $cipher; 1" or croak "Couldn't load $cipher: $@"; # some crypt modules use the class Crypt::, and others don't $cipher =~ s/^Crypt::// unless $cipher->can('keysize'); } return $cipher; } sub _validate_options { my $self = shift; my $options = shift; my %valid_options = map {$_=>1} @valid_options; for my $o (keys %$options) { die "'$o' is not a recognized argument" unless $valid_options{$o}; } return 1; } sub _get_header_mode { my $class = shift; my $options = shift; # header mode checking my %valid_modes = map {$_=>1} qw(none salt randomiv); my $header_mode = $options->{header}; $header_mode ||= 'none' if exists $options->{prepend_iv} && !$options->{prepend_iv}; $header_mode ||= 'none' if exists $options->{add_header} && !$options->{add_header}; $header_mode ||= 'none' if $options->{literal_key} || (exists $options->{pbkdf} && $options->{pbkdf} eq 'none'); $header_mode ||= 'salt'; # default croak "Invalid -header mode '$header_mode'" unless $valid_modes{$header_mode}; return $header_mode; } sub _get_padding_mode { my $class = shift; my ($bs,$options) = @_; my $padding = $options->{padding} || 'standard'; if ($padding && ref($padding) eq 'CODE') { # check to see that this code does its padding correctly for my $i (1..$bs-1) { my $rbs = length($padding->(" "x$i,$bs,'e')); croak "padding method callback does not behave properly: expected $bs bytes back, got $rbs bytes back." unless ($rbs == $bs); } } else { $padding = $padding eq 'none' ? \&_no_padding :$padding eq 'null' ? \&_null_padding :$padding eq 'space' ? \&_space_padding :$padding eq 'oneandzeroes' ? \&_oneandzeroes_padding :$padding eq 'rijndael_compat'? \&_rijndael_compat :$padding eq 'standard' ? \&_standard_padding :croak "'$padding' padding not supported. See perldoc Crypt::CBC for instructions on creating your own."; } return $padding; } sub _get_key_and_block_sizes { my $class = shift; my $cipher = shift; my $options = shift; # allow user to override the keysize value my $ks = $options->{keysize} || eval {$cipher->keysize} || eval {$cipher->max_keysize} or croak "Cannot derive keysize from $cipher"; my $bs = eval {$cipher->blocksize} or croak "$cipher did not provide a blocksize"; return ($ks,$bs); } sub _get_key_materials { my $self = shift; my $options = shift; # "key" is a misnomer here, because it is actually usually a passphrase that is used # to derive the true key my $pass = $options->{pass} || $options->{key}; my $cipher_object_provided = $options->{cipher} && ref $options->{cipher}; if ($cipher_object_provided) { carp "Both a key and a pre-initialized Crypt::* object were passed. The key will be ignored" if defined $pass; $pass ||= ''; } croak "Please provide an encryption/decryption passphrase using -pass or -key" unless defined $pass; # Default behavior is to treat -key as a passphrase. # But if the literal_key option is true, then use key as is croak "The options -literal_key and -regenerate_key are incompatible with each other" if exists $options->{literal_key} && exists $options->{regenerate_key}; my $key = $pass if $options->{literal_key}; $key = $pass if exists $options->{regenerate_key} && !$options->{regenerate_key}; # Get the salt. my $salt = $options->{salt}; my $random_salt = 1 unless defined $salt && $salt ne '1'; croak "Argument to -salt must be exactly 8 bytes long" if defined $salt && length $salt != 8 && $salt ne '1'; # note: iv will be autogenerated by start() if not specified in options my $iv = $options->{iv}; my $random_iv = 1 unless defined $iv; my $literal_key = $options->{literal_key} || (exists $options->{regenerate_key} && !$options->{regenerate_key}); undef $pass if $literal_key; return ($pass,$iv,$salt,$key,$random_salt,$random_iv); } sub _get_key_derivation_options { my $self = shift; my ($options,$header_mode) = @_; # KEY DERIVATION PARAMETERS # Some special cases here # 1. literal key has been requested - use algorithm 'none' # 2. headerless mode - use algorithm 'none' # 3. randomiv header - use algorithm 'nosalt' my $pbkdf = $options->{pbkdf} || ($options->{literal_key} ? 'none' :$header_mode eq 'randomiv' ? 'randomiv' :DEFAULT_PBKDF); # iterations my $iter = $options->{iter} || DEFAULT_ITER; $iter =~ /[\d_]+/ && $iter >= 1 or croak "-iterations argument must be greater than or equal to 1"; $iter =~ /[\d_]+/ && $iter >= 1 or croak "-iterations argument must be greater than or equal to 1"; # hasher my $hc = $options->{hasher}; my $nodeprecate = $options->{nodeprecate}; return ($pbkdf,$iter,$hc,$nodeprecate); } sub _get_chain_mode { my $self = shift; my $options = shift; return $options->{chain_mode} ? $options->{chain_mode} :$options->{pcbc} ? 'pcbc' :'cbc'; } sub _load_module { my $self = shift; my ($module,$args) = @_; my $result = eval "use $module $args; 1;"; warn $@ if $@; return $result; } sub _deprecation_warning { my $self = shift; return if $self->nodeprecate; return if $self->{decrypt}; my $pbkdf = $self->pbkdf; carp <'pbkdf2' would be better. Pass -nodeprecate=>1 to inhibit this message. END } ######################################### chaining mode methods ################################3 sub _needs_padding { my $self = shift; $self->chain_mode =~ /^p?cbc$/ && $self->padding ne \&_no_padding; } sub _cbc_encrypt { my $self = shift; my ($crypt,$iv,$result,$blocks) = @_; # the copying looks silly, but it is slightly faster than dereferencing the # variables each time my ($i,$r) = ($$iv,$$result); foreach (@$blocks) { $r .= $i = $crypt->encrypt($i ^ $_); } ($$iv,$$result) = ($i,$r); } sub _cbc_decrypt { my $self = shift; my ($crypt,$iv,$result,$blocks) = @_; # the copying looks silly, but it is slightly faster than dereferencing the # variables each time my ($i,$r) = ($$iv,$$result); foreach (@$blocks) { $r .= $i ^ $crypt->decrypt($_); $i = $_; } ($$iv,$$result) = ($i,$r); } sub _pcbc_encrypt { my $self = shift; my ($crypt,$iv,$result,$blocks) = @_; foreach my $plaintext (@$blocks) { $$result .= $$iv = $crypt->encrypt($$iv ^ $plaintext); $$iv ^= $plaintext; } } sub _pcbc_decrypt { my $self = shift; my ($crypt,$iv,$result,$blocks) = @_; foreach my $ciphertext (@$blocks) { $$result .= $$iv = $$iv ^ $crypt->decrypt($ciphertext); $$iv ^= $ciphertext; } } sub _cfb_encrypt { my $self = shift; my ($crypt,$iv,$result,$blocks) = @_; my ($i,$r) = ($$iv,$$result); foreach my $plaintext (@$blocks) { $r .= $i = $plaintext ^ $crypt->encrypt($i) } ($$iv,$$result) = ($i,$r); } sub _cfb_decrypt { my $self = shift; my ($crypt,$iv,$result,$blocks) = @_; my ($i,$r) = ($$iv,$$result); foreach my $ciphertext (@$blocks) { $r .= $ciphertext ^ $crypt->encrypt($i); $i = $ciphertext; } ($$iv,$$result) = ($i,$r); } sub _ofb_encrypt { my $self = shift; my ($crypt,$iv,$result,$blocks) = @_; my ($i,$r) = ($$iv,$$result); foreach my $plaintext (@$blocks) { my $ciphertext = $plaintext ^ ($i = $crypt->encrypt($i)); substr($ciphertext,length $plaintext) = ''; # truncate $r .= $ciphertext; } ($$iv,$$result) = ($i,$r); } *_ofb_decrypt = \&_ofb_encrypt; # same code # According to RFC3686, the counter is 128 bits (16 bytes) # The first 32 bits (4 bytes) is the nonce # The next 64 bits (8 bytes) is the IV # The final 32 bits (4 bytes) is the counter, starting at 1 # BUT, the way that openssl v1.1.1 does it is to generate a random # IV, treat the whole thing as a blocksize-sized integer, and then # increment. sub _ctr_encrypt { my $self = shift; my ($crypt,$iv,$result,$blocks) = @_; my $bs = $self->blocksize; $self->_upgrade_iv_to_ctr($iv); my ($i,$r) = ($$iv,$$result); foreach my $plaintext (@$blocks) { my $bytes = int128_to_net($i++); # pad with leading nulls if there are insufficient bytes # (there's gotta be a better way to do this) if ($bs > length $bytes) { substr($bytes,0,0) = "\000"x($bs-length $bytes) ; } my $ciphertext = $plaintext ^ ($crypt->encrypt($bytes)); substr($ciphertext,length $plaintext) = ''; # truncate $r .= $ciphertext; } ($$iv,$$result) = ($i,$r); } *_ctr_decrypt = \&_ctr_encrypt; # same code # upgrades instance vector to a CTR counter # returns 1 if upgrade performed sub _upgrade_iv_to_ctr { my $self = shift; my $iv = shift; # this is a scalar reference return if ref $$iv; # already upgraded to an object $self->_load_module("Math::Int128" => "'net_to_int128','int128_to_net'") or croak "Optional Math::Int128 module must be installed to use the CTR chaining method"; $$iv = net_to_int128($$iv); return 1; } ######################################### chaining mode methods ################################3 sub pbkdf { shift->{pbkdf} } # get the initialized PBKDF object sub pbkdf_obj { my $self = shift; my $pbkdf = $self->pbkdf; my $iter = $self->{iter}; my $hc = $self->{hasher}; my @hash_args = $hc ? ref ($hc) ? (hasher => $hc) : (hash_class => $hc) : (); return Crypt::CBC::PBKDF->new($pbkdf => { key_len => $self->{keysize}, iv_len => $self->{blocksize}, iterations => $iter, @hash_args, } ); } ############################# generating key, iv and salt ######################## # hopefully a replacement for mess below sub set_key_and_iv { my $self = shift; if (!$self->{literal_key}) { my ($key,$iv) = $self->pbkdf_obj->key_and_iv($self->{salt},$self->{passphrase}); $self->{key} = $key; $self->{iv} = $iv if $self->{make_random_iv}; } else { $self->{iv} = $self->_get_random_bytes($self->blocksize) if $self->{make_random_iv}; } length $self->{salt} == 8 or croak "Salt must be exactly 8 bytes long"; length $self->{iv} == $self->{blocksize} or croak "IV must be exactly $self->{blocksize} bytes long"; } # derive the salt, iv and key from the datastream header + passphrase sub _read_key_and_iv { my $self = shift; my $input_stream = shift; my $bs = $self->blocksize; # use our header mode to figure out what to do with the data stream my $header_mode = $self->header_mode; if ($header_mode eq 'none') { $self->{salt} ||= $self->_get_random_bytes(8); return $self->set_key_and_iv; } elsif ($header_mode eq 'salt') { ($self->{salt}) = $$input_stream =~ /^Salted__(.{8})/s; croak "Ciphertext does not begin with a valid header for 'salt' header mode" unless defined $self->{salt}; substr($$input_stream,0,16) = ''; my ($k,$i) = $self->pbkdf_obj->key_and_iv($self->{salt},$self->{passphrase}); $self->{key} = $k unless $self->{literal_key}; $self->{iv} = $i unless $self->{literal_iv}; } elsif ($header_mode eq 'randomiv') { ($self->{iv}) = $$input_stream =~ /^RandomIV(.{8})/s; croak "Ciphertext does not begin with a valid header for 'randomiv' header mode" unless defined $self->{iv}; croak "randomiv header mode cannot be used securely when decrypting with a >8 byte block cipher.\n" unless $self->blocksize == 8; (undef,$self->{key}) = $self->pbkdf_obj->key_and_iv(undef,$self->{passphrase}); substr($$input_stream,0,16) = ''; # truncate } else { croak "Invalid header mode '$header_mode'"; } } # this subroutine will generate the actual {en,de}cryption key, the iv # and the block cipher object. This is called when reading from a datastream # and so it uses previous values of salt or iv if they are encoded in datastream # header sub _generate_iv_and_cipher_from_datastream { my $self = shift; my $input_stream = shift; $self->_read_key_and_iv($input_stream); $self->{civ} = $self->{iv}; # we should have the key and iv now, or we are dead in the water croak "Could not derive key or iv from cipher stream, and you did not specify these values in new()" unless $self->{key} && $self->{civ}; # now we can generate the crypt object itself $self->{crypt} = ref $self->{cipher} ? $self->{cipher} : $self->{cipher}->new($self->{key}) or croak "Could not create $self->{cipher} object: $@"; return ''; } sub _generate_iv_and_cipher_from_options { my $self = shift; $self->{salt} = $self->_get_random_bytes(8) if $self->{make_random_salt}; $self->set_key_and_iv; $self->{civ} = $self->{iv}; my $result = ''; my $header_mode = $self->header_mode; if ($header_mode eq 'salt') { $result = "Salted__$self->{salt}"; } elsif ($header_mode eq 'randomiv') { $result = "RandomIV$self->{iv}"; undef $self->{salt}; # shouldn't be there! } croak "key and/or iv are missing" unless defined $self->{key} && defined $self->{civ}; $self->_taintcheck($self->{key}); $self->{crypt} = ref $self->{cipher} ? $self->{cipher} : $self->{cipher}->new($self->{key}) or croak "Could not create $self->{cipher} object: $@"; return $result; } sub _taintcheck { my $self = shift; my $key = shift; return unless ${^TAINT}; my $has_scalar_util = eval "require Scalar::Util; 1"; my $tainted; if ($has_scalar_util) { $tainted = Scalar::Util::tainted($key); } else { local($@, $SIG{__DIE__}, $SIG{__WARN__}); local $^W = 0; eval { kill 0 * $key }; $tainted = $@ =~ /^Insecure/; } croak "Taint checks are turned on and your key is tainted. Please untaint the key and try again" if $tainted; } sub _digest_obj { my $self = shift; if ($self->{digest_obj}) { $self->{digest_obj}->reset(); return $self->{digest_obj}; } my $alg = $self->{digest_alg}; return $alg if ref $alg && $alg->can('digest'); my $obj = eval {Digest->new($alg)}; croak "Unable to instantiate '$alg' digest object: $@" if $@; return $self->{digest_obj} = $obj; } sub random_bytes { my $self = shift; my $bytes = shift or croak "usage: random_bytes(\$byte_length)"; $self->_get_random_bytes($bytes); } sub _get_random_bytes { my $self = shift; my $length = shift; my $result; if (-r RANDOM_DEVICE && open(F,RANDOM_DEVICE)) { read(F,$result,$length); close F; } else { $result = pack("C*",map {rand(256)} 1..$length); } # Clear taint and check length $result =~ /^(.+)$/s; length($1) == $length or croak "Invalid length while gathering $length random bytes"; return $1; } sub _standard_padding ($$$) { my ($b,$bs,$decrypt) = @_; if ($decrypt eq 'd') { my $pad_length = unpack("C",substr($b,-1)); return substr($b,0,$bs-$pad_length); } my $pad = $bs - length($b); return $b . pack("C*",($pad)x$pad); } sub _space_padding ($$$) { my ($b,$bs,$decrypt) = @_; if ($decrypt eq 'd') { $b=~ s/ *\z//s; } else { $b .= pack("C*", (32) x ($bs-length($b))); } return $b; } sub _no_padding ($$$) { my ($b,$bs,$decrypt) = @_; return $b; } sub _null_padding ($$$) { my ($b,$bs,$decrypt) = @_; return unless length $b; $b = length $b ? $b : ''; if ($decrypt eq 'd') { $b=~ s/\0*\z//s; return $b; } return $b . pack("C*", (0) x ($bs - length($b) % $bs)); } sub _oneandzeroes_padding ($$$) { my ($b,$bs,$decrypt) = @_; if ($decrypt eq 'd') { $b=~ s/\x80\0*\z//s; return $b; } return $b . pack("C*", 128, (0) x ($bs - length($b) - 1) ); } sub _rijndael_compat ($$$) { my ($b,$bs,$decrypt) = @_; return unless length $b; if ($decrypt eq 'd') { $b=~ s/\x80\0*\z//s; return $b; } return $b . pack("C*", 128, (0) x ($bs - length($b) % $bs - 1) ); } sub get_initialization_vector (\$) { my $self = shift; $self->iv(); } sub set_initialization_vector (\$$) { my $self = shift; my $iv = shift; my $bs = $self->blocksize; croak "Initialization vector must be $bs bytes in length" unless length($iv) == $bs; $self->iv($iv); } sub salt { my $self = shift; my $d = $self->{salt}; $self->{salt} = shift if @_; $d; } sub iv { my $self = shift; my $d = $self->{iv}; $self->{iv} = shift if @_; $d; } sub key { my $self = shift; my $d = $self->{key}; $self->{key} = shift if @_; $d; } sub passphrase { my $self = shift; my $d = $self->{passphrase}; if (@_) { undef $self->{key}; undef $self->{iv}; $self->{passphrase} = shift; } $d; } sub keysize { my $self = shift; $self->{keysize} = shift if @_; $self->{keysize}; } sub cipher { shift->{cipher} } sub padding { shift->{padding} } sub blocksize { shift->{blocksize} } sub pcbc { shift->{pcbc} } sub header_mode {shift->{header_mode} } sub literal_key {shift->{literal_key}} sub nodeprecate {shift->{nodeprecate}} 1; __END__ =head1 NAME Crypt::CBC - Encrypt Data with Cipher Block Chaining Mode =head1 SYNOPSIS use Crypt::CBC; $cipher = Crypt::CBC->new( -pass => 'my secret password', -cipher => 'Cipher::AES' ); # one shot mode $ciphertext = $cipher->encrypt("This data is hush hush"); $plaintext = $cipher->decrypt($ciphertext); # stream mode $cipher->start('encrypting'); open(F,"./BIG_FILE"); while (read(F,$buffer,1024)) { print $cipher->crypt($buffer); } print $cipher->finish; # do-it-yourself mode -- specify key && initialization vector yourself $key = Crypt::CBC->random_bytes(8); # assuming a 8-byte block cipher $iv = Crypt::CBC->random_bytes(8); $cipher = Crypt::CBC->new(-pbkdf => 'none', -key => $key, -iv => $iv); $ciphertext = $cipher->encrypt("This data is hush hush"); $plaintext = $cipher->decrypt($ciphertext); # encrypting via a filehandle (requires Crypt::FileHandle> $fh = Crypt::CBC->filehandle(-pass => 'secret'); open $fh,'>','encrypted.txt" or die $! print $fh "This will be encrypted\n"; close $fh; =head1 DESCRIPTION This module is a Perl-only implementation of the cryptographic cipher block chaining mode (CBC). In combination with a block cipher such as AES or Blowfish, you can encrypt and decrypt messages of arbitrarily long length. The encrypted messages are compatible with the encryption format used by the B package. To use this module, you will first create a Crypt::CBC cipher object with new(). At the time of cipher creation, you specify an encryption key to use and, optionally, a block encryption algorithm. You will then call the start() method to initialize the encryption or decryption process, crypt() to encrypt or decrypt one or more blocks of data, and lastly finish(), to pad and encrypt the final block. For your convenience, you can call the encrypt() and decrypt() methods to operate on a whole data value at once. =head2 new() $cipher = Crypt::CBC->new( -pass => 'my secret key', -cipher => 'Cipher::AES', ); # or (for compatibility with versions prior to 2.0) $cipher = new Crypt::CBC('my secret key' => 'Cipher::AES'); The new() method creates a new Crypt::CBC object. It accepts a list of -argument => value pairs selected from the following list: Argument Description -------- ----------- -pass,-key The encryption/decryption passphrase. These arguments are interchangeable, but -pass is preferred ("key" is a misnomer, as it is not the literal encryption key). -cipher The cipher algorithm (defaults to Crypt::Cipher:AES), or a previously created cipher object reference. For convenience, you may omit the initial "Crypt::" part of the classname and use the basename, e.g. "Blowfish" instead of "Crypt::Blowfish". -keysize Force the cipher keysize to the indicated number of bytes. This can be used to set the keysize for variable keylength ciphers such as AES. -chain_mode The block chaining mode to use. Current options are: 'cbc' -- cipher-block chaining mode [default] 'pcbc' -- plaintext cipher-block chaining mode 'cfb' -- cipher feedback mode 'ofb' -- output feedback mode 'ctr' -- counter mode -pbkdf The passphrase-based key derivation function used to derive the encryption key and initialization vector from the provided passphrase. For backward compatibility, Crypt::CBC will default to "opensslv1", but it is recommended to use the standard "pbkdf2"algorithm instead. If you wish to interoperate with OpenSSL, be aware that different versions of the software support a series of derivation functions. 'none' -- The value provided in -pass/-key is used directly. This is the same as passing true to -literal_key. You must also manually specify the IV with -iv. The key and the IV must match the keylength and blocklength of the chosen cipher. 'randomiv' -- Use insecure key derivation method found in prehistoric versions of OpenSSL (dangerous) 'opensslv1' -- [default] Use the salted MD5 method that was default in versions of OpenSSL through v1.0.2. 'opensslv2' -- [better] Use the salted SHA-256 method that was the default in versions of OpenSSL through v1.1.0. 'pbkdf2' -- [best] Use the PBKDF2 method that was first introduced in OpenSSL v1.1.1. More derivation functions may be added in the future. To see the supported list, use the command perl -MCrypt::CBC::PBKDF -e 'print join "\n",Crypt::CBC::PBKDF->list' -iter If the 'pbkdf2' key derivation algorithm is used, this specifies the number of hashing cycles to be applied to the passphrase+salt (longer is more secure). [default 10,000] -hasher If the 'pbkdf2' key derivation algorithm is chosen, you can use this to provide an initialized Crypt::PBKDF2::Hash object. [default HMACSHA2 for OpenSSL compatability] -header What type of header to prepend to the ciphertext. One of 'salt' -- use OpenSSL-compatible salted header (default) 'randomiv' -- Randomiv-compatible "RandomIV" header 'none' -- prepend no header at all (compatible with prehistoric versions of OpenSSL) -iv The initialization vector (IV). If not provided, it will be generated by the key derivation function. -salt The salt passed to the key derivation function. If not provided, will be generated randomly (recommended). -padding The padding method, one of "standard" (default), "space", "oneandzeroes", "rijndael_compat", "null", or "none" (default "standard"). -literal_key [deprected, use -pbkdf=>'none'] If true, the key provided by "-key" or "-pass" is used directly for encryption/decryption without salting or hashing. The key must be the right length for the chosen cipher. [default false) -pcbc [deprecated, use -chaining_mode=>'pcbc'] Whether to use the PCBC chaining algorithm rather than the standard CBC algorithm (default false). -add_header [deprecated; use -header instead] Whether to add the salt and IV to the header of the output cipher text. -regenerate_key [deprecated; use -literal_key instead] Whether to use a hash of the provided key to generate the actual encryption key (default true) -prepend_iv [deprecated; use -header instead] Whether to prepend the IV to the beginning of the encrypted stream (default true) Crypt::CBC requires three pieces of information to do its job. First it needs the name of the block cipher algorithm that will encrypt or decrypt the data in blocks of fixed length known as the cipher's "blocksize." Second, it needs an encryption/decryption key to pass to the block cipher. Third, it needs an initialization vector (IV) that will be used to propagate information from one encrypted block to the next. Both the key and the IV must be exactly the same length as the chosen cipher's blocksize. Crypt::CBC can derive the key and the IV from a passphrase that you provide, or can let you specify the true key and IV manually. In addition, you have the option of embedding enough information to regenerate the IV in a short header that is emitted at the start of the encrypted stream, or outputting a headerless encryption stream. In the first case, Crypt::CBC will be able to decrypt the stream given just the original key or passphrase. In the second case, you will have to provide the original IV as well as the key/passphrase. The B<-cipher> option specifies which block cipher algorithm to use to encode each section of the message. This argument is optional and will default to the secure Crypt::Cipher::AES algorithm. You may use any compatible block encryption algorithm that you have installed. Currently, this includes Crypt::Cipher::AES, Crypt::DES, Crypt::DES_EDE3, Crypt::IDEA, Crypt::Blowfish, Crypt::CAST5 and Crypt::Rijndael. You may refer to them using their full names ("Crypt::IDEA") or in abbreviated form ("IDEA"). Instead of passing the name of a cipher class, you may pass an already-created block cipher object. This allows you to take advantage of cipher algorithms that have parameterized new() methods, such as Crypt::Eksblowfish: my $eksblowfish = Crypt::Eksblowfish->new(8,$salt,$key); my $cbc = Crypt::CBC->new(-cipher=>$eksblowfish); The B<-pass> argument provides a passphrase to use to generate the encryption key or the literal value of the block cipher key. If used in passphrase mode (which is the default), B<-pass> can be any number of characters; the actual key will be derived by passing the passphrase through a series of hashing operations. To take full advantage of a given block cipher, the length of the passphrase should be at least equal to the cipher's blocksize. For backward compatibility, you may also refer to this argument using B<-key>. To skip this hashing operation and specify the key directly, provide the actual key as a string to B<-key> and specify a key derivation function of "none" to the B<-pbkdf> argument. Alternatively, you may pass a true value to the B<-literal_key> argument. When you manually specify the key in this way, should choose a key of length exactly equal to the cipher's key length. You will also have to specify an IV equal in length to the cipher's blocksize. These choices imply a header mode of "none." If you pass an existing Crypt::* object to new(), then the B<-pass>/B<-key> argument is ignored and the module will generate a warning. The B<-pbkdf> argument specifies the algorithm used to derive the true key and IV from the provided passphrase (PBKDF stands for "passphrase-based key derivation function"). Valid values are: "opensslv1" -- [default] A fast algorithm that derives the key by combining a random salt values with the passphrase via a series of MD5 hashes. "opensslv2" -- an improved version that uses SHA-256 rather than MD5, and has been OpenSSL's default since v1.1.0. However, it has been deprecated in favor of pbkdf2 since OpenSSL v1.1.1. "pbkdf2" -- a better algorithm implemented in OpenSSL v1.1.1, described in RFC 2898 L "none" -- don't use a derivation function, but treat the passphrase as the literal key. This is the same as B<-literal_key> true. "nosalt" -- an insecure key derivation method used by prehistoric versions of OpenSSL, provided for backward compatibility. Don't use. "opensslv1" was OpenSSL's default key derivation algorithm through version 1.0.2, but is susceptible to dictionary attacks and is no longer supported. It remains the default for Crypt::CBC in order to avoid breaking compatibility with previously-encrypted messages. Using this option will issue a deprecation warning when initiating encryption. You can suppress the warning by passing a true value to the B<-nodeprecate> option. It is recommended to specify the "pbkdf2" key derivation algorithm when compatibility with older versions of Crypt::CBC is not needed. This algorithm is deliberately computationally expensive in order to make dictionary-based attacks harder. As a result, it introduces a slight delay before an encryption or decryption operation starts. The B<-iter> argument is used in conjunction with the "pbkdf2" key derivation option. Its value indicates the number of hashing cycles used to derive the key. Larger values are more secure, but impose a longer delay before encryption/decryption starts. The default is 10,000 for compatibility with OpenSSL's default. The B<-hasher> argument is used in conjunction with the "pbkdf2" key derivation option to pass the reference to an initialized Crypt::PBKDF2::Hash object. If not provided, it defaults to the OpenSSL-compatible hash function HMACSHA2 initialized with its default options (SHA-256 hash). The B<-header> argument specifies what type of header, if any, to prepend to the beginning of the encrypted data stream. The header allows Crypt::CBC to regenerate the original IV and correctly decrypt the data without your having to provide the same IV used to encrypt the data. Valid values for the B<-header> are: "salt" -- Combine the passphrase with an 8-byte random value to generate both the block cipher key and the IV from the provided passphrase. The salt will be appended to the beginning of the data stream allowing decryption to regenerate both the key and IV given the correct passphrase. This method is compatible with current versions of OpenSSL. "randomiv" -- Generate the block cipher key from the passphrase, and choose a random 8-byte value to use as the IV. The IV will be prepended to the data stream. This method is compatible with ciphertext produced by versions of the library prior to 2.17, but is incompatible with block ciphers that have non 8-byte block sizes, such as Rijndael. Crypt::CBC will exit with a fatal error if you try to use this header mode with a non 8-byte cipher. This header type is NOT secure and NOT recommended. "none" -- Do not generate a header. To decrypt a stream encrypted in this way, you will have to provide the true key and IV manually. B When using a "salt" header, you may specify your own value of the salt, by passing the desired 8-byte character string to the B<-salt> argument. Otherwise, the module will generate a random salt for you. Crypt::CBC will generate a fatal error if you specify a salt value that isn't exactly 8 bytes long. For backward compatibility reasons, passing a value of "1" will generate a random salt, the same as if no B<-salt> argument was provided. The B<-padding> argument controls how the last few bytes of the encrypted stream are dealt with when they not an exact multiple of the cipher block length. The default is "standard", the method specified in PKCS#5. The B<-chaining_mode> argument will select among several different block chaining modes. Values are: 'cbc' -- [default] traditional Cipher-Block Chaining mode. It has the property that if one block in the ciphertext message is damaged, only that block and the next one will be rendered un-decryptable. 'pcbc' -- Plaintext Cipher-Block Chaining mode. This has the property that one damaged ciphertext block will render the remainder of the message unreadable 'cfb' -- Cipher Feedback Mode. In this mode, both encryption and decryption are performed using the block cipher's "encrypt" algorithm. The error propagation behaviour is similar to CBC's. 'ofb' -- Output Feedback Mode. Similar to CFB, the block cipher's encrypt algorithm is used for both encryption and decryption. If one bit of the plaintext or ciphertext message is damaged, the damage is confined to a single block of the corresponding ciphertext or plaintext, and error correction algorithms can be used to reconstruct the damaged part. 'ctr' -- Counter Mode. This mode uses a one-time "nonce" instead of an IV. The nonce is incremented by one for each block of plain or ciphertext, encrypted using the chosen algorithm, and then applied to the block of text. If one bit of the input text is damaged, it only affects 1 bit of the output text. To use CTR mode you will need to install the Perl Math::Int128 module. This chaining method is roughly half the speed of the others due to integer arithmetic. Passing a B<-pcbc> argument of true will have the same effect as -chaining_mode=>'pcbc', and is included for backward compatibility. [deprecated]. For more information on chaining modes, see L. The B<-keysize> argument can be used to force the cipher's keysize. This is useful for several of the newer algorithms, including AES, ARIA, Blowfish, and CAMELLIA. If -keysize is not specified, then Crypt::CBC will use the value returned by the cipher's max_keylength() method. Note that versions of CBC::Crypt prior to 2.36 could also allow you to set the blocksie, but this was never supported by any ciphers and has been removed. For compatibility with earlier versions of this module, you can provide new() with a hashref containing key/value pairs. The key names are the same as the arguments described earlier, but without the initial hyphen. You may also call new() with one or two positional arguments, in which case the first argument is taken to be the key and the second to be the optional block cipher algorithm. =head2 start() $cipher->start('encrypting'); $cipher->start('decrypting'); The start() method prepares the cipher for a series of encryption or decryption steps, resetting the internal state of the cipher if necessary. You must provide a string indicating whether you wish to encrypt or decrypt. "E" or any word that begins with an "e" indicates encryption. "D" or any word that begins with a "d" indicates decryption. =head2 crypt() $ciphertext = $cipher->crypt($plaintext); After calling start(), you should call crypt() as many times as necessary to encrypt the desired data. =head2 finish() $ciphertext = $cipher->finish(); The CBC algorithm must buffer data blocks internally until they are even multiples of the encryption algorithm's blocksize (typically 8 bytes). After the last call to crypt() you should call finish(). This flushes the internal buffer and returns any leftover ciphertext. In a typical application you will read the plaintext from a file or input stream and write the result to standard output in a loop that might look like this: $cipher = new Crypt::CBC('hey jude!'); $cipher->start('encrypting'); print $cipher->crypt($_) while <>; print $cipher->finish(); =head2 encrypt() $ciphertext = $cipher->encrypt($plaintext) This convenience function runs the entire sequence of start(), crypt() and finish() for you, processing the provided plaintext and returning the corresponding ciphertext. =head2 decrypt() $plaintext = $cipher->decrypt($ciphertext) This convenience function runs the entire sequence of start(), crypt() and finish() for you, processing the provided ciphertext and returning the corresponding plaintext. =head2 encrypt_hex(), decrypt_hex() $ciphertext = $cipher->encrypt_hex($plaintext) $plaintext = $cipher->decrypt_hex($ciphertext) These are convenience functions that operate on ciphertext in a hexadecimal representation. B is exactly equivalent to B. These functions can be useful if, for example, you wish to place the encrypted in an email message. =head2 filehandle() This method returns a filehandle for transparent encryption or decryption using Christopher Dunkle's excellent L module. This module must be installed in order to use this method. filehandle() can be called as a class method using the same arguments as new(): $fh = Crypt::CBC->filehandle(-cipher=> 'Blowfish', -pass => "You'll never guess"); or on a previously-created Crypt::CBC object: $cbc = Crypt::CBC->new(-cipher=> 'Blowfish', -pass => "You'll never guess"); $fh = $cbc->filehandle; The filehandle can then be opened using the familiar open() syntax. Printing to a filehandle opened for writing will encrypt the data. Filehandles opened for input will be decrypted. Here is an example: # transparent encryption open $fh,'>','encrypted.out' or die $!; print $fh "You won't be able to read me!\n"; close $fh; # transparent decryption open $fh,'<','encrypted.out' or die $!; while (<$fh>) { print $_ } close $fh; =head2 get_initialization_vector() $iv = $cipher->get_initialization_vector() This function will return the IV used in encryption and or decryption. The IV is not guaranteed to be set when encrypting until start() is called, and when decrypting until crypt() is called the first time. Unless the IV was manually specified in the new() call, the IV will change with every complete encryption operation. =head2 set_initialization_vector() $cipher->set_initialization_vector('76543210') This function sets the IV used in encryption and/or decryption. This function may be useful if the IV is not contained within the ciphertext string being decrypted, or if a particular IV is desired for encryption. Note that the IV must match the chosen cipher's blocksize bytes in length. =head2 iv() $iv = $cipher->iv(); $cipher->iv($new_iv); As above, but using a single method call. =head2 key() $key = $cipher->key(); $cipher->key($new_key); Get or set the block cipher key used for encryption/decryption. When encrypting, the key is not guaranteed to exist until start() is called, and when decrypting, the key is not guaranteed to exist until after the first call to crypt(). The key must match the length required by the underlying block cipher. When salted headers are used, the block cipher key will change after each complete sequence of encryption operations. =head2 salt() $salt = $cipher->salt(); $cipher->salt($new_salt); Get or set the salt used for deriving the encryption key and IV when in OpenSSL compatibility mode. =head2 passphrase() $passphrase = $cipher->passphrase(); $cipher->passphrase($new_passphrase); This gets or sets the value of the B passed to new() when B is false. =head2 $data = random_bytes($numbytes) Return $numbytes worth of random data. On systems that support the "/dev/urandom" device file, this data will be read from the device. Otherwise, it will be generated by repeated calls to the Perl rand() function. =head2 cipher(), pbkdf(), padding(), keysize(), blocksize(), chain_mode() These read-only methods return the identity of the chosen block cipher algorithm, the key derivation function (e.g. "opensslv1"), padding method, key and block size of the chosen block cipher, and what chaining mode ("cbc", "ofb" ,etc) is being used. =head2 Padding methods Use the 'padding' option to change the padding method. When the last block of plaintext is shorter than the block size, it must be padded. Padding methods include: "standard" (i.e., PKCS#5), "oneandzeroes", "space", "rijndael_compat", "null", and "none". standard: (default) Binary safe pads with the number of bytes that should be truncated. So, if blocksize is 8, then "0A0B0C" will be padded with "05", resulting in "0A0B0C0505050505". If the final block is a full block of 8 bytes, then a whole block of "0808080808080808" is appended. oneandzeroes: Binary safe pads with "80" followed by as many "00" necessary to fill the block. If the last block is a full block and blocksize is 8, a block of "8000000000000000" will be appended. rijndael_compat: Binary safe, with caveats similar to oneandzeroes, except that no padding is performed if the last block is a full block. This is provided for compatibility with Crypt::Rijndael's buit-in MODE_CBC. Note that Crypt::Rijndael's implementation of CBC only works with messages that are even multiples of 16 bytes. null: text only pads with as many "00" necessary to fill the block. If the last block is a full block and blocksize is 8, a block of "0000000000000000" will be appended. space: text only same as "null", but with "20". none: no padding added. Useful for special-purpose applications where you wish to add custom padding to the message. Both the standard and oneandzeroes paddings are binary safe. The space and null paddings are recommended only for text data. Which type of padding you use depends on whether you wish to communicate with an external (non Crypt::CBC library). If this is the case, use whatever padding method is compatible. You can also pass in a custom padding function. To do this, create a function that takes the arguments: $padded_block = function($block,$blocksize,$direction); where $block is the current block of data, $blocksize is the size to pad it to, $direction is "e" for encrypting and "d" for decrypting, and $padded_block is the result after padding or depadding. When encrypting, the function should always return a string of length, and when decrypting, can expect the string coming in to always be that length. See _standard_padding(), _space_padding(), _null_padding(), or _oneandzeroes_padding() in the source for examples. Standard and oneandzeroes padding are recommended, as both space and null padding can potentially truncate more characters than they should. =head1 Comparison to Crypt::Mode::CBC The L modules L, L, L, and L provide fast implementations of the respective cipherblock chaining modes (roughly 5x the speed of Crypt::CBC). Crypt::CBC was designed to encrypt and decrypt messages in a manner compatible with OpenSSL's "enc" function. Hence it handles the derivation of the key and IV from a passphrase using the same conventions as OpenSSL, and it writes out an OpenSSL-compatible header in the encrypted message in a manner that allows the key and IV to be regenerated during decryption. In contrast, the CryptX modules do not automatically derive the key and IV from a passphrase or write out an encrypted header. You will need to derive and store the key and IV by other means (e.g. with CryptX's Crypt::KeyDerivation module, or with Crypt::PBKDF2). =head1 EXAMPLES Three examples, aes.pl, des.pl and idea.pl can be found in the eg/ subdirectory of the Crypt-CBC distribution. These implement command-line DES and IDEA encryption algorithms using default parameters, and should be compatible with recent versions of OpenSSL. Note that aes.pl uses the "pbkdf2" key derivation function to generate its keys. The other two were distributed with pre-PBKDF2 versions of Crypt::CBC, and use the older "opensslv1" algorithm. =head1 LIMITATIONS The encryption and decryption process is about a tenth the speed of the equivalent OpenSSL tool and about a fifth of the Crypt::Mode::CBC module (both which use compiled C). =head1 BUGS Please report them. =head1 AUTHOR Lincoln Stein, lstein@cshl.org This module is distributed under the ARTISTIC LICENSE v2 using the same terms as Perl itself. =head1 SEE ALSO perl(1), CryptX, Crypt::FileHandle, Crypt::Cipher::AES, Crypt::Blowfish, Crypt::CAST5, Crypt::DES, Crypt::IDEA, Crypt::Rijndael =cut Crypt-CBC-3.04/Crypt-CBC-2.16-vulnerability.txt0000644000175000017500000001100312043731413020177 0ustar lsteinlsteinPerl Module Security Advisory ------------------------------------------------------------------------------- Title: Crypt::CBC ciphertext weakness when using certain block algorithms Severity: High Versions: All versions <= 2.16. Date: 16 February 2006 ------------------------------------------------------------------------------- Synopsis -------- The Perl Crypt::CBC module versions through 2.16 produce weak ciphertext when used with block encryption algorithms with blocksize > 8 bytes. Background ---------- Crypt::CBC implements the Cipher Block Chaining Mode (CBC) [1]. CBC allows block ciphers (which encrypt and decrypt chunks of data of a fixed block length) to act as though they are stream ciphers capable of encrypting and decrypting arbitrary length streams. It does this by randomly generating an initialization vector (IV) the same length as the cipher's block size. This IV is logically XORed with the first block of plaintext prior to encryption. The block is encrypted, and the result is used as the IV applied to the next block of plaintext. This process is repeated for each block of plaintext. In order for ciphertext encrypted by Crypt::CBC to be decrypted, the receiver must know both the key used to encrypt the data stream and the IV that was chosen. Because the IV is not secret, it can safely be appended to the encrypted message. The key, of course, is kept in a safe place and transmitted to the recipient by some secure means. Crypt::CBC can generate two types of headers for transmitting the IV. The older, deprecated, header type is known as the "RandomIV" header, and consists of the 8 byte string "RandomIV" followed by 8 bytes of IV data. This is the default header generated by Crypt::CBC versions through 2.16. The newer, recommended, type of header is known as the "Salted" header and consists of the 8 byte string "Salted__" followed by an 8 byte salt value. The salt value is used to rederive both the encryption key and the IV from a long passphrase provided by the user. The Salted header was introduced in version 2.13 and is compatible with the CBC header generated by OpenSSL [2]. Description ----------- The RandomIV style header assumes that the IV will be exactly 8 bytes in length. However, the IV must be the same length as the underlying cipher's block size, and so this assumption is not correct when using ciphers whose block size is greater than 8 bytes. Of the ciphers commonly available to Perl developers, only the Rijndael algorithm, which uses a 16 byte block size is the primary cipher affected by this issue. Rijndael is the cipher that underlies the AES encryption standard. Impact ------ Ciphertext encrypted with Crypt::CBC using the legacy RandomIV header and the Rijndael cipher is not secure. The latter 8 bytes of each block are chained using a constant effective IV of null, meaning that the ciphertext will be prone to differential cryptanalysis, particularly if the same key was used to generate multiple encrypted messages. Other >8-byte cipher algorithms will be similarly affected. The difficulty of breaking data encrypted using this flawed algorithm is unknown, but it should be assumed that all information encrypted in this way has been, or could someday be, compromised. Exploits -------- There are no active exploits known at this time. Workaround ---------- If using Crypt::CBC versions 2.16 and lower, pass the -salt=>1 option to Crypt::CBC->new(). This will generate and process IVs correctly for ciphers of all length. Resolution ---------- Upgrade to Crypt::CBC version 2.17 or higher. This module makes the Salted header the default behavior and refuses to encrypt or decrypt with non-8 byte block size ciphers when in legacy RandomIV mode. In order to decrypt ciphertext previously encrypted by pre-2.17 versions of the software with Rijndael and other >8-byte algorithms, Crypt::CBC provides an -insecure_legacy_decrypt option that will allow such ciphertext to be decrypted. The default is to refuse to decrypt such data. The most recent version of Crypt::CBC can be downloaded from the Comprehensive Perl Archive Network (CPAN; http://www.cpan.org). Contact ------- For further information about this issue, please contact the author of Crypt::CBC, Lincoln Stein . Acknowledgements ---------------- The author gratefully acknowledges the contribution of Ben Laurie, who correctly identified the issue and suggested the resolution. References ---------- [1] http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation [2] http://www.openssl.org/ Crypt-CBC-3.04/README.md0000644000175000017500000007104114034672217013774 0ustar lsteinlstein# NAME Crypt::CBC - Encrypt Data with Cipher Block Chaining Mode # SYNOPSIS use Crypt::CBC; $cipher = Crypt::CBC->new( -pass => 'my secret password', -cipher => 'Cipher::AES' ); # one shot mode $ciphertext = $cipher->encrypt("This data is hush hush"); $plaintext = $cipher->decrypt($ciphertext); # stream mode $cipher->start('encrypting'); open(F,"./BIG_FILE"); while (read(F,$buffer,1024)) { print $cipher->crypt($buffer); } print $cipher->finish; # do-it-yourself mode -- specify key && initialization vector yourself $key = Crypt::CBC->random_bytes(8); # assuming a 8-byte block cipher $iv = Crypt::CBC->random_bytes(8); $cipher = Crypt::CBC->new(-pbkdf => 'none', -key => $key, -iv => $iv); $ciphertext = $cipher->encrypt("This data is hush hush"); $plaintext = $cipher->decrypt($ciphertext); # encrypting via a filehandle (requires Crypt::FileHandle> $fh = Crypt::CBC->filehandle(-pass => 'secret'); open $fh,'>','encrypted.txt" or die $! print $fh "This will be encrypted\n"; close $fh; # DESCRIPTION This module is a Perl-only implementation of the cryptographic cipher block chaining mode (CBC). In combination with a block cipher such as AES or Blowfish, you can encrypt and decrypt messages of arbitrarily long length. The encrypted messages are compatible with the encryption format used by the **OpenSSL** package. To use this module, you will first create a Crypt::CBC cipher object with new(). At the time of cipher creation, you specify an encryption key to use and, optionally, a block encryption algorithm. You will then call the start() method to initialize the encryption or decryption process, crypt() to encrypt or decrypt one or more blocks of data, and lastly finish(), to pad and encrypt the final block. For your convenience, you can call the encrypt() and decrypt() methods to operate on a whole data value at once. ## new() $cipher = Crypt::CBC->new( -pass => 'my secret key', -cipher => 'Cipher::AES', ); # or (for compatibility with versions prior to 2.0) $cipher = new Crypt::CBC('my secret key' => 'Cipher::AES'); The new() method creates a new Crypt::CBC object. It accepts a list of \-argument => value pairs selected from the following list: Argument Description -------- ----------- -pass,-key The encryption/decryption passphrase. These arguments are interchangeable, but -pass is preferred ("key" is a misnomer, as it is not the literal encryption key). -cipher The cipher algorithm (defaults to Crypt::Cipher:AES), or a previously created cipher object reference. For convenience, you may omit the initial "Crypt::" part of the classname and use the basename, e.g. "Blowfish" instead of "Crypt::Blowfish". -keysize Force the cipher keysize to the indicated number of bytes. This can be used to set the keysize for variable keylength ciphers such as AES. -chain_mode The block chaining mode to use. Current options are: 'cbc' -- cipher-block chaining mode [default] 'pcbc' -- plaintext cipher-block chaining mode 'cfb' -- cipher feedback mode 'ofb' -- output feedback mode 'ctr' -- counter mode -pbkdf The passphrase-based key derivation function used to derive the encryption key and initialization vector from the provided passphrase. For backward compatibility, Crypt::CBC will default to "opensslv1", but it is recommended to use the standard "pbkdf2"algorithm instead. If you wish to interoperate with OpenSSL, be aware that different versions of the software support a series of derivation functions. 'none' -- The value provided in -pass/-key is used directly. This is the same as passing true to -literal_key. You must also manually specify the IV with -iv. The key and the IV must match the keylength and blocklength of the chosen cipher. 'randomiv' -- Use insecure key derivation method found in prehistoric versions of OpenSSL (dangerous) 'opensslv1' -- [default] Use the salted MD5 method that was default in versions of OpenSSL through v1.0.2. 'opensslv2' -- [better] Use the salted SHA-256 method that was the default in versions of OpenSSL through v1.1.0. 'pbkdf2' -- [best] Use the PBKDF2 method that was first introduced in OpenSSL v1.1.1. More derivation functions may be added in the future. To see the supported list, use the command perl -MCrypt::CBC::PBKDF -e 'print join "\n",Crypt::CBC::PBKDF->list' -iter If the 'pbkdf2' key derivation algorithm is used, this specifies the number of hashing cycles to be applied to the passphrase+salt (longer is more secure). [default 10,000] -hasher If the 'pbkdf2' key derivation algorithm is chosen, you can use this to provide an initialized Crypt::PBKDF2::Hash object. [default HMACSHA2 for OpenSSL compatability] -header What type of header to prepend to the ciphertext. One of 'salt' -- use OpenSSL-compatible salted header (default) 'randomiv' -- Randomiv-compatible "RandomIV" header 'none' -- prepend no header at all (compatible with prehistoric versions of OpenSSL) -iv The initialization vector (IV). If not provided, it will be generated by the key derivation function. -salt The salt passed to the key derivation function. If not provided, will be generated randomly (recommended). -padding The padding method, one of "standard" (default), "space", "oneandzeroes", "rijndael_compat", "null", or "none" (default "standard"). -literal_key [deprected, use -pbkdf=>'none'] If true, the key provided by "-key" or "-pass" is used directly for encryption/decryption without salting or hashing. The key must be the right length for the chosen cipher. [default false) -pcbc [deprecated, use -chaining_mode=>'pcbc'] Whether to use the PCBC chaining algorithm rather than the standard CBC algorithm (default false). -add_header [deprecated; use -header instead] Whether to add the salt and IV to the header of the output cipher text. -regenerate_key [deprecated; use -literal_key instead] Whether to use a hash of the provided key to generate the actual encryption key (default true) -prepend_iv [deprecated; use -header instead] Whether to prepend the IV to the beginning of the encrypted stream (default true) Crypt::CBC requires three pieces of information to do its job. First it needs the name of the block cipher algorithm that will encrypt or decrypt the data in blocks of fixed length known as the cipher's "blocksize." Second, it needs an encryption/decryption key to pass to the block cipher. Third, it needs an initialization vector (IV) that will be used to propagate information from one encrypted block to the next. Both the key and the IV must be exactly the same length as the chosen cipher's blocksize. Crypt::CBC can derive the key and the IV from a passphrase that you provide, or can let you specify the true key and IV manually. In addition, you have the option of embedding enough information to regenerate the IV in a short header that is emitted at the start of the encrypted stream, or outputting a headerless encryption stream. In the first case, Crypt::CBC will be able to decrypt the stream given just the original key or passphrase. In the second case, you will have to provide the original IV as well as the key/passphrase. The **-cipher** option specifies which block cipher algorithm to use to encode each section of the message. This argument is optional and will default to the secure Crypt::Cipher::AES algorithm. You may use any compatible block encryption algorithm that you have installed. Currently, this includes Crypt::Cipher::AES, Crypt::DES, Crypt::DES\_EDE3, Crypt::IDEA, Crypt::Blowfish, Crypt::CAST5 and Crypt::Rijndael. You may refer to them using their full names ("Crypt::IDEA") or in abbreviated form ("IDEA"). Instead of passing the name of a cipher class, you may pass an already-created block cipher object. This allows you to take advantage of cipher algorithms that have parameterized new() methods, such as Crypt::Eksblowfish: my $eksblowfish = Crypt::Eksblowfish->new(8,$salt,$key); my $cbc = Crypt::CBC->new(-cipher=>$eksblowfish); The **-pass** argument provides a passphrase to use to generate the encryption key or the literal value of the block cipher key. If used in passphrase mode (which is the default), **-pass** can be any number of characters; the actual key will be derived by passing the passphrase through a series of hashing operations. To take full advantage of a given block cipher, the length of the passphrase should be at least equal to the cipher's blocksize. For backward compatibility, you may also refer to this argument using **-key**. To skip this hashing operation and specify the key directly, provide the actual key as a string to **-key** and specify a key derivation function of "none" to the **-pbkdf** argument. Alternatively, you may pass a true value to the **-literal\_key** argument. When you manually specify the key in this way, should choose a key of length exactly equal to the cipher's key length. You will also have to specify an IV equal in length to the cipher's blocksize. These choices imply a header mode of "none." If you pass an existing Crypt::\* object to new(), then the **-pass**/**-key** argument is ignored and the module will generate a warning. The **-pbkdf** argument specifies the algorithm used to derive the true key and IV from the provided passphrase (PBKDF stands for "passphrase-based key derivation function"). Valid values are: "opensslv1" -- [default] A fast algorithm that derives the key by combining a random salt values with the passphrase via a series of MD5 hashes. "opensslv2" -- an improved version that uses SHA-256 rather than MD5, and has been OpenSSL's default since v1.1.0. However, it has been deprecated in favor of pbkdf2 since OpenSSL v1.1.1. "pbkdf2" -- a better algorithm implemented in OpenSSL v1.1.1, described in RFC 2898 L "none" -- don't use a derivation function, but treat the passphrase as the literal key. This is the same as B<-literal_key> true. "nosalt" -- an insecure key derivation method used by prehistoric versions of OpenSSL, provided for backward compatibility. Don't use. "opensslv1" was OpenSSL's default key derivation algorithm through version 1.0.2, but is susceptible to dictionary attacks and is no longer supported. It remains the default for Crypt::CBC in order to avoid breaking compatibility with previously-encrypted messages. Using this option will issue a deprecation warning when initiating encryption. You can suppress the warning by passing a true value to the **-nodeprecate** option. It is recommended to specify the "pbkdf2" key derivation algorithm when compatibility with older versions of Crypt::CBC is not needed. This algorithm is deliberately computationally expensive in order to make dictionary-based attacks harder. As a result, it introduces a slight delay before an encryption or decryption operation starts. The **-iter** argument is used in conjunction with the "pbkdf2" key derivation option. Its value indicates the number of hashing cycles used to derive the key. Larger values are more secure, but impose a longer delay before encryption/decryption starts. The default is 10,000 for compatibility with OpenSSL's default. The **-hasher** argument is used in conjunction with the "pbkdf2" key derivation option to pass the reference to an initialized Crypt::PBKDF2::Hash object. If not provided, it defaults to the OpenSSL-compatible hash function HMACSHA2 initialized with its default options (SHA-256 hash). The **-header** argument specifies what type of header, if any, to prepend to the beginning of the encrypted data stream. The header allows Crypt::CBC to regenerate the original IV and correctly decrypt the data without your having to provide the same IV used to encrypt the data. Valid values for the **-header** are: "salt" -- Combine the passphrase with an 8-byte random value to generate both the block cipher key and the IV from the provided passphrase. The salt will be appended to the beginning of the data stream allowing decryption to regenerate both the key and IV given the correct passphrase. This method is compatible with current versions of OpenSSL. "randomiv" -- Generate the block cipher key from the passphrase, and choose a random 8-byte value to use as the IV. The IV will be prepended to the data stream. This method is compatible with ciphertext produced by versions of the library prior to 2.17, but is incompatible with block ciphers that have non 8-byte block sizes, such as Rijndael. Crypt::CBC will exit with a fatal error if you try to use this header mode with a non 8-byte cipher. This header type is NOT secure and NOT recommended. "none" -- Do not generate a header. To decrypt a stream encrypted in this way, you will have to provide the true key and IV manually. **The "salt" header is now the default as of Crypt::CBC version 2.17. In all earlier versions "randomiv" was the default.** When using a "salt" header, you may specify your own value of the salt, by passing the desired 8-byte character string to the **-salt** argument. Otherwise, the module will generate a random salt for you. Crypt::CBC will generate a fatal error if you specify a salt value that isn't exactly 8 bytes long. For backward compatibility reasons, passing a value of "1" will generate a random salt, the same as if no **-salt** argument was provided. The **-padding** argument controls how the last few bytes of the encrypted stream are dealt with when they not an exact multiple of the cipher block length. The default is "standard", the method specified in PKCS#5. The **-chaining\_mode** argument will select among several different block chaining modes. Values are: 'cbc' -- [default] traditional Cipher-Block Chaining mode. It has the property that if one block in the ciphertext message is damaged, only that block and the next one will be rendered un-decryptable. 'pcbc' -- Plaintext Cipher-Block Chaining mode. This has the property that one damaged ciphertext block will render the remainder of the message unreadable 'cfb' -- Cipher Feedback Mode. In this mode, both encryption and decryption are performed using the block cipher's "encrypt" algorithm. The error propagation behaviour is similar to CBC's. 'ofb' -- Output Feedback Mode. Similar to CFB, the block cipher's encrypt algorithm is used for both encryption and decryption. If one bit of the plaintext or ciphertext message is damaged, the damage is confined to a single block of the corresponding ciphertext or plaintext, and error correction algorithms can be used to reconstruct the damaged part. 'ctr' -- Counter Mode. This mode uses a one-time "nonce" instead of an IV. The nonce is incremented by one for each block of plain or ciphertext, encrypted using the chosen algorithm, and then applied to the block of text. If one bit of the input text is damaged, it only affects 1 bit of the output text. To use CTR mode you will need to install the Perl Math::Int128 module. Passing a **-pcbc** argument of true will have the same effect as \-chaining\_mode=>'pcbc', and is included for backward compatibility. \[deprecated\]. For more information on chaining modes, see [http://www.crypto-it.net/eng/theory/modes-of-block-ciphers.html](http://www.crypto-it.net/eng/theory/modes-of-block-ciphers.html). The **-keysize** argument can be used to force the cipher's keysize. This is useful for several of the newer algorithms, including AES, ARIA, Blowfish, and CAMELLIA. If -keysize is not specified, then Crypt::CBC will use the value returned by the cipher's max\_keylength() method. Note that versions of CBC::Crypt prior to 2.36 could also allow you to set the blocksie, but this was never supported by any ciphers and has been removed. For compatibility with earlier versions of this module, you can provide new() with a hashref containing key/value pairs. The key names are the same as the arguments described earlier, but without the initial hyphen. You may also call new() with one or two positional arguments, in which case the first argument is taken to be the key and the second to be the optional block cipher algorithm. ## start() $cipher->start('encrypting'); $cipher->start('decrypting'); The start() method prepares the cipher for a series of encryption or decryption steps, resetting the internal state of the cipher if necessary. You must provide a string indicating whether you wish to encrypt or decrypt. "E" or any word that begins with an "e" indicates encryption. "D" or any word that begins with a "d" indicates decryption. ## crypt() $ciphertext = $cipher->crypt($plaintext); After calling start(), you should call crypt() as many times as necessary to encrypt the desired data. ## finish() $ciphertext = $cipher->finish(); The CBC algorithm must buffer data blocks internally until they are even multiples of the encryption algorithm's blocksize (typically 8 bytes). After the last call to crypt() you should call finish(). This flushes the internal buffer and returns any leftover ciphertext. In a typical application you will read the plaintext from a file or input stream and write the result to standard output in a loop that might look like this: $cipher = new Crypt::CBC('hey jude!'); $cipher->start('encrypting'); print $cipher->crypt($_) while <>; print $cipher->finish(); ## encrypt() $ciphertext = $cipher->encrypt($plaintext) This convenience function runs the entire sequence of start(), crypt() and finish() for you, processing the provided plaintext and returning the corresponding ciphertext. ## decrypt() $plaintext = $cipher->decrypt($ciphertext) This convenience function runs the entire sequence of start(), crypt() and finish() for you, processing the provided ciphertext and returning the corresponding plaintext. ## encrypt\_hex(), decrypt\_hex() $ciphertext = $cipher->encrypt_hex($plaintext) $plaintext = $cipher->decrypt_hex($ciphertext) These are convenience functions that operate on ciphertext in a hexadecimal representation. **encrypt\_hex($plaintext)** is exactly equivalent to **unpack('H\*',encrypt($plaintext))**. These functions can be useful if, for example, you wish to place the encrypted in an email message. ## filehandle() This method returns a filehandle for transparent encryption or decryption using Christopher Dunkle's excellent [Crypt::FileHandle](https://metacpan.org/pod/Crypt%3A%3AFileHandle) module. This module must be installed in order to use this method. filehandle() can be called as a class method using the same arguments as new(): $fh = Crypt::CBC->filehandle(-cipher=> 'Blowfish', -pass => "You'll never guess"); or on a previously-created Crypt::CBC object: $cbc = Crypt::CBC->new(-cipher=> 'Blowfish', -pass => "You'll never guess"); $fh = $cbc->filehandle; The filehandle can then be opened using the familiar open() syntax. Printing to a filehandle opened for writing will encrypt the data. Filehandles opened for input will be decrypted. Here is an example: # transparent encryption open $fh,'>','encrypted.out' or die $!; print $fh "You won't be able to read me!\n"; close $fh; # transparent decryption open $fh,'<','encrypted.out' or die $!; while (<$fh>) { print $_ } close $fh; ## get\_initialization\_vector() $iv = $cipher->get_initialization_vector() This function will return the IV used in encryption and or decryption. The IV is not guaranteed to be set when encrypting until start() is called, and when decrypting until crypt() is called the first time. Unless the IV was manually specified in the new() call, the IV will change with every complete encryption operation. ## set\_initialization\_vector() $cipher->set_initialization_vector('76543210') This function sets the IV used in encryption and/or decryption. This function may be useful if the IV is not contained within the ciphertext string being decrypted, or if a particular IV is desired for encryption. Note that the IV must match the chosen cipher's blocksize bytes in length. ## iv() $iv = $cipher->iv(); $cipher->iv($new_iv); As above, but using a single method call. ## key() $key = $cipher->key(); $cipher->key($new_key); Get or set the block cipher key used for encryption/decryption. When encrypting, the key is not guaranteed to exist until start() is called, and when decrypting, the key is not guaranteed to exist until after the first call to crypt(). The key must match the length required by the underlying block cipher. When salted headers are used, the block cipher key will change after each complete sequence of encryption operations. ## salt() $salt = $cipher->salt(); $cipher->salt($new_salt); Get or set the salt used for deriving the encryption key and IV when in OpenSSL compatibility mode. ## passphrase() $passphrase = $cipher->passphrase(); $cipher->passphrase($new_passphrase); This gets or sets the value of the **passphrase** passed to new() when **literal\_key** is false. ## $data = random\_bytes($numbytes) Return $numbytes worth of random data. On systems that support the "/dev/urandom" device file, this data will be read from the device. Otherwise, it will be generated by repeated calls to the Perl rand() function. ## cipher(), pbkdf(), padding(), keysize(), blocksize(), chain\_mode() These read-only methods return the identity of the chosen block cipher algorithm, the key derivation function (e.g. "opensslv1"), padding method, key and block size of the chosen block cipher, and what chaining mode ("cbc", "ofb" ,etc) is being used. ## Padding methods Use the 'padding' option to change the padding method. When the last block of plaintext is shorter than the block size, it must be padded. Padding methods include: "standard" (i.e., PKCS#5), "oneandzeroes", "space", "rijndael\_compat", "null", and "none". standard: (default) Binary safe pads with the number of bytes that should be truncated. So, if blocksize is 8, then "0A0B0C" will be padded with "05", resulting in "0A0B0C0505050505". If the final block is a full block of 8 bytes, then a whole block of "0808080808080808" is appended. oneandzeroes: Binary safe pads with "80" followed by as many "00" necessary to fill the block. If the last block is a full block and blocksize is 8, a block of "8000000000000000" will be appended. rijndael_compat: Binary safe, with caveats similar to oneandzeroes, except that no padding is performed if the last block is a full block. This is provided for compatibility with Crypt::Rijndael's buit-in MODE_CBC. Note that Crypt::Rijndael's implementation of CBC only works with messages that are even multiples of 16 bytes. null: text only pads with as many "00" necessary to fill the block. If the last block is a full block and blocksize is 8, a block of "0000000000000000" will be appended. space: text only same as "null", but with "20". none: no padding added. Useful for special-purpose applications where you wish to add custom padding to the message. Both the standard and oneandzeroes paddings are binary safe. The space and null paddings are recommended only for text data. Which type of padding you use depends on whether you wish to communicate with an external (non Crypt::CBC library). If this is the case, use whatever padding method is compatible. You can also pass in a custom padding function. To do this, create a function that takes the arguments: $padded_block = function($block,$blocksize,$direction); where $block is the current block of data, $blocksize is the size to pad it to, $direction is "e" for encrypting and "d" for decrypting, and $padded\_block is the result after padding or depadding. When encrypting, the function should always return a string of <blocksize> length, and when decrypting, can expect the string coming in to always be that length. See \_standard\_padding(), \_space\_padding(), \_null\_padding(), or \_oneandzeroes\_padding() in the source for examples. Standard and oneandzeroes padding are recommended, as both space and null padding can potentially truncate more characters than they should. # Comparison to Crypt::Mode::CBC The [CryptX](https://metacpan.org/pod/CryptX) modules [Crypt::Mode::CBC](https://metacpan.org/pod/Crypt%3A%3AMode%3A%3ACBC), [Crypt::Mode::OFB](https://metacpan.org/pod/Crypt%3A%3AMode%3A%3AOFB), [Crypt::Mode::CFB](https://metacpan.org/pod/Crypt%3A%3AMode%3A%3ACFB), and [Crypt::Mode::CTR](https://metacpan.org/pod/Crypt%3A%3AMode%3A%3ACTR) provide fast implementations of the respective cipherblock chaining modes (roughly 5x the speed of Crypt::CBC). Crypt::CBC was designed to encrypt and decrypt messages in a manner compatible with OpenSSL's "enc" function. Hence it handles the derivation of the key and IV from a passphrase using the same conventions as OpenSSL, and it writes out an OpenSSL-compatible header in the encrypted message in a manner that allows the key and IV to be regenerated during decryption. In contrast, the CryptX modules do not automatically derive the key and IV from a passphrase or write out an encrypted header. You will need to derive and store the key and IV by other means (e.g. with CryptX's Crypt::KeyDerivation module, or with Crypt::PBKDF2). # EXAMPLES Three examples, aes.pl, des.pl and idea.pl can be found in the eg/ subdirectory of the Crypt-CBC distribution. These implement command-line DES and IDEA encryption algorithms using default parameters, and should be compatible with recent versions of OpenSSL. Note that aes.pl uses the "pbkdf2" key derivation function to generate its keys. The other two were distributed with pre-PBKDF2 versions of Crypt::CBC, and use the older "opensslv1" algorithm. # LIMITATIONS The encryption and decryption process is about a tenth the speed of the equivalent OpenSSL tool and about a fifth of the Crypt::Mode::CBC module (both which use compiled C). # BUGS Please report them. # AUTHOR Lincoln Stein, lstein@cshl.org This module is distributed under the ARTISTIC LICENSE v2 using the same terms as Perl itself. # SEE ALSO perl(1), CryptX, Crypt::FileHandle, Crypt::Cipher::AES, Crypt::Blowfish, Crypt::CAST5, Crypt::DES, Crypt::IDEA, Crypt::Rijndael Crypt-CBC-3.04/META.yml0000664000175000017500000000107514050502334013756 0ustar lsteinlstein--- abstract: unknown author: - unknown build_requires: ExtUtils::MakeMaker: '0' configure_requires: ExtUtils::MakeMaker: '0' dynamic_config: 1 generated_by: 'ExtUtils::MakeMaker version 7.34, CPAN::Meta::Converter version 2.150010' license: unknown meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: '1.4' name: Crypt-CBC no_index: directory: - t - inc requires: Crypt::Cipher::AES: '0' Crypt::PBKDF2: '0' Digest::MD5: '0' Digest::SHA: '0' version: '3.04' x_serialization_backend: 'CPAN::Meta::YAML version 0.018' Crypt-CBC-3.04/Makefile.PL0000644000175000017500000000121014010243174014444 0ustar lsteinlsteinuse ExtUtils::MakeMaker; # See lib/ExtUtils/MakeMaker.pm for details of how to influence # the contents of the Makefile that is written. WriteMakefile( 'NAME' => 'Crypt::CBC', 'VERSION_FROM' => 'lib/Crypt/CBC.pm', # finds $VERSION 'PREREQ_PM' => { 'Digest::MD5' => 0, 'Digest::SHA' => 0, 'Crypt::PBKDF2' => 0, 'Crypt::Cipher::AES' => 0, }, 'LIBS' => [''], # e.g., '-lm' 'DEFINE' => '', # e.g., '-DHAVE_SOMETHING' 'INC' => '', # e.g., '-I/usr/include/other' 'dist' => {'COMPRESS'=>'gzip -9f', 'SUFFIX' => 'gz', 'ZIP'=>'/usr/bin/zip','ZIPFLAGS'=>'-rl'} ); Crypt-CBC-3.04/Changes0000644000175000017500000002022014050502316013767 0ustar lsteinlsteinRevision history for Perl extension Crypt::CBC. 3.04 Mon 17 May 2021 10:58:37 AM EDT - Fixed bug involving manually-specified IV not being used in some circumstances. 3.03 Sun 18 Apr 2021 10:54:19 PM EDT - Fixed bug which caused an extraneous block of garbage data to be appended to encrypted string when "nopadding" specified and plaintext is even multiple of blocksize. 3.02 - CTR mode now requires the Math::Int128 module, which gives a ~5x performance boost over Math::BigInt. 3.01 - Warn when the deprecated opensslv1 PBKDF (key derivation function) is used for encryption. Turn off with -nodeprecate=>1 or by choosing a different PBKDF, such as -pbkdf=>'pbkdf2'. - Fix a regression when passing the legacy -salt=>1 argument. 3.00 Sun Feb 7 10:28:08 EST 2021 - Released version 3.00 in recognition of multiple new features and cleanups. 2.37 Sun Feb 7 10:20:17 EST 2021 - Added better argument checking. - Fixed long-standing standard padding bug: plaintext ending with bytes between 0x00 and 0x0A would be truncated in some conditions. - Fixed Rijndael_compat padding. 2.36 Wed 03 Feb 2021 09:19:06 AM EST - Add support for OFB, CFB and CTR chain modes. - New dependency: Math::BigInt 2.35 Sun Jan 31 22:02:42 EST 2021 - Add support for PBKDF2 key derivation algorithm - New dependencies: Digest::SHA, Crypt::PBKDF2, Crypt::Cipher::AES 2.34 Fri Jan 29 18:08:12 EST 2021 - Support for openssl SHA-256 key derivation algorithm 2.33 Tue Jul 30 16:02:04 EDT 2013 - Fix minor RT bugs 83175 and 86455. 2.32 Fri Dec 14 14:20:17 EST 2012 - Fix "Taint checks are turned on and your key is tainted" error when autogenerating salt and IV. 2.31 Tue Oct 30 07:03:40 EDT 2012 - Fixes to regular expressions to avoid rare failures to correctly strip padding in decoded messages. - Add padding type = "none". - Both fixes contributed by Bas van Sisseren. 2.29 Tue Apr 22 10:22:37 EDT 2008 - Fixed errors that occurred when encrypting/decrypting utf8 strings in Perl's more recent than 5.8.8. 2.28 Mon Mar 31 10:46:25 EDT 2008 - Fixed bug in onesandzeroes test that causes it to fail with Rijndael module is not installed. 2.27 Fri Mar 28 10:13:32 EDT 2008 - When taint mode is turned on and user is using a tainted key, explicitly check tainting of key in order to avoid "cryptic" failure messages from some crypt modules. 2.26 Thu Mar 20 16:41:23 EDT 2008 - Fixed onezeropadding test, which was not reporting its test count properly. 2.25 Fri Jan 11 15:26:27 EST 2008 - Fixed failure of oneandzeroes padding when plaintext size is an even multiple of blocksize. - Added new "rijndael_compat" padding method, which is compatible with the oneandzeroes padding method used by Crypt::Rijndael in CBC mode. 2.24 Fri Sep 28 11:21:07 EDT 2007 - Fixed failure to run under taint checks with Crypt::Rijndael or Crypt::OpenSSL::AES (and maybe other Crypt modules). See http://rt.cpan.org/Public/Bug/Display.html?id=29646. 2.23 Fri Apr 13 14:50:21 EDT 2007 - Added checks for other implementations of CBC which add no standard padding at all when cipher text is an even multiple of the block size. 2.22 Sun Oct 29 16:50:32 EST 2006 - Fixed bug in which plaintext encrypted with the -literal_key option could not be decrypted using a new object created with the same -literal_key. - Added documentation confirming that -literal_key must be accompanied by a -header of 'none' and a manually specificied IV. 2.21 Mon Oct 16 19:26:26 EDT 2006 - Fixed bug in which new() failed to work when first option is -literal_key. 2.20 Sat Aug 12 22:30:53 EDT 2006 - Added ability to pass a preinitialized Crypt::* block cipher object instead of the class name. - Fixed a bug when processing -literal_key. 2.19 Tue Jul 18 18:39:57 EDT 2006 - Renamed Crypt::CBC-2.16-vulnerability.txt so that package installs correctly under Cygwin 2.18 2006/06/06 23:17:04 - added more documentation describing how to achieve compatibility with old encrypted messages 2.17 Mon Jan 9 18:22:51 EST 2006 -IMPORTANT NOTE: Versions of this module prior to 2.17 were incorrectly using 8 byte IVs when generating the old-style RandomIV style header (as opposed to the new-style random salt header). This affects data encrypted using the Rijndael algorithm, which has a 16 byte blocksize, and is a significant security issue. The bug has been corrected in versions 2.17 and higher by making it impossible to use 16-byte block ciphers with RandomIV headers. You may still read legacy encrypted data by explicitly passing the -insecure_legacy_decrypt option to Crypt::CBC->new(). -The salt, iv and key are now reset before each complete encryption cycle. This avoids inadvertent reuse of the same salt. -A new -header option has been added that allows you to select among the various types of headers, and avoids the ambiguity of having multiple interacting options. -A new random_bytes() method provides access to /dev/urandom on suitably-equipped hardware. 2.16 Tue Dec 6 14:17:45 EST 2005 - Added two new options to new(): -keysize => Force the keysize -- useful for Blowfish -blocksize => Force the blocksize -- not known to be useful ("-keysize=>16" is necessary to decrypt OpenSSL messages encrypted with Blowfish) 2.15 Thu Nov 17 17:34:28 EST 2005 - -add_header=>0 now explicitly turns off any attempt of parsing the header in decrypt routines. 2.14 Thu May 5 16:08:15 EDT 2005 - RandomIV in message header overrides manually-supplied -salt, as one would expect it should. 2.13 Fri Apr 22 13:01:32 EDT 200 - Added OpenSSL compatibility - Salt and IV generators take advantage of /dev/urandom device, if available - Reorganized internal structure for coding clarity - Added regression test for PCBC mode 2.12 Thu Jun 17 11:52:04 EDT 2004 - quenched (again) uninitialized variable warnings 2.11 Thu Jun 3 12:07:33 EDT 2004 -Fixed bug reported by Joshua Brown that caused certain length strings to not encrypt properly if ending in a "0" character. 2.10 Sat May 29 13:10:05 EDT 2004 -Fixed Rijndael compat problems 2.09 Thu May 27 11:18:06 EDT 2004 -Quenched uninitialized variable warnings 2.08 Wed Sep 11 08:12:49 EDT 2002 -Bug fix from Chris Laas to fix custom padding 2.07 Thu Aug 8 14:44:52 EDT 2002 -Bug fixes from Stephen Waters to fix space padding -Lots of regression tests from Stephen Waters 2.05 Tue Jun 11 22:18:04 EDT 2002 -Makes zero-and-one padding compatible with Crypt::Rijndael::MODE_CBC. -Lots of improvements to padding mechanisms from Stephen Waters 2.04 Tue Jun 11 22:18:04 EDT 2002 WITHDRAWN VERSION DO NOT USE 2.03 Mon Feb 4 15:41:51 EST 2002 -Patch from Andy Turner to allow backward compatibility with old versions when key length exceeded max. 2.02 Thu Jan 24 00:15:52 EST 2002 - Default to pre-2.00 style padding, because Jody's default padding method was not binary safe. 2.01 Mon Dec 10 12:11:35 EST 2001 - Removed debugging code. 2.00 Tue Oct 31, 2000 - Patches for foreign program compatibility, initialization vectors and padding methods from Jody Biggs 1.25 Thu Jun 8 11:56:28 EDT 2000 - Bug fix didn't get into version 1.24. Is in version 1.25 1.24 Tue Jun 6 17:35:18 EDT 2000 - Fixed a bug that prevented a DES and an IDEA object from being used simultaneously. 1.22 Wed Jan 26 19:07:30 EST 2000 - Added support for Crypt::Blowfish (available from www.cryptix.org) - Fixed failure to encrypt data files < 8 bytes - Fixed -w warning when decrypting data files < 8 bytes 1.21 Mon Nov 29 17:11:17 EST 1999 - Generate random initialization vector. - Use same encryption format as Ben Laurie's patches to OpenSSL (versions >= 0.9.5) 1.20 Sun Dec 20 3:58:01 1998 MET - Folded in bug fixes from Devin Carraway (chiefly having to do with finish() being called with a zero-length buffer). 1.10 Thu Sep 11 09:15:01 1998 - Changed package name to Crypt::CBC 1.00 Tue Jun 16 07:37:35 1998 - original version; created by h2xs 1.18