File Coverage

lib/Crypt/CBC.pm
Criterion Covered Total %
statement 350 443 79.0
branch 161 242 66.5
condition 74 121 61.1
subroutine 57 71 80.2
pod 22 29 75.8
total 664 906 73.2


line stmt bran cond sub pod time code
1             package Crypt::CBC;
2              
3 9     9   42678 use strict;
  9         18  
  9         287  
4 9     9   42 use Carp 'croak','carp';
  9         13  
  9         437  
5 9     9   3228 use Crypt::CBC::PBKDF;
  9         18  
  9         237  
6 9     9   5189 use bytes;
  9         120  
  9         38  
7 9     9   284 use vars qw($VERSION);
  9         25  
  9         488  
8 9     9   49 no warnings 'uninitialized';
  9         14  
  9         405  
9             $VERSION = '3.03';
10              
11 9     9   41 use constant RANDOM_DEVICE => '/dev/urandom';
  9         13  
  9         776  
12 9     9   53 use constant DEFAULT_PBKDF => 'opensslv1';
  9         10  
  9         362  
13 9     9   49 use constant DEFAULT_ITER => 10_000; # same as OpenSSL default
  9         25  
  9         52067  
14              
15             my @valid_options = qw(
16             pass
17             key
18             cipher
19             keysize
20             chain_mode
21             pbkdf
22             nodeprecate
23             iter
24             hasher
25             header
26             iv
27             salt
28             padding
29             literal_key
30             pcbc
31             add_header
32             generate_key
33             prepend_iv
34             );
35              
36             sub new {
37 43     43 1 62451 my $class = shift;
38              
39             # the _get_*() methods move a lot of the ugliness/legacy logic
40             # out of new(). But the ugliness is still there!
41 43         137 my $options = $class->_get_options(@_);
42 43 100       58 eval {$class->_validate_options($options)} or croak $@;
  43         113  
43            
44 42         124 my $cipher = $class->_get_cipher_obj($options);
45 42         105 my $header_mode = $class->_get_header_mode($options);
46 41         117 my ($ks,$bs) = $class->_get_key_and_block_sizes($cipher,$options);
47 41         104 my ($pass,$iv,$salt,$key,
48             $random_salt,$random_iv) = $class->_get_key_materials($options);
49 39         123 my $padding = $class->_get_padding_mode($bs,$options);
50 39         93 my ($pbkdf,$iter,
51             $hc,$nodeprecate) = $class->_get_key_derivation_options($options,$header_mode);
52 39         142 my $chain_mode = $class->_get_chain_mode($options);
53              
54             ### CONSISTENCY CHECKS ####
55              
56             # set literal key flag if a key was passed in or the key derivation algorithm is none
57 39 100 66     96 $key ||= $pass if $pbkdf eq 'none'; # just in case
58 39         76 my $literal_key = defined $key;
59              
60             # check length of initialization vector
61 39 100 100     456 croak "Initialization vector must be exactly $bs bytes long when using the $cipher cipher"
62             if defined $iv and length($iv) != $bs;
63              
64             # chaining mode check
65 37 50       266 croak "invalid cipher block chain mode: $chain_mode"
66             unless $class->can("_${chain_mode}_encrypt");
67              
68             # KEYSIZE consistency
69 37 100 100     108 if (defined $key && length($key) != $ks) {
70 2         238 croak "If specified by -literal_key, then the key length must be equal to the chosen cipher's key length of $ks bytes";
71             }
72              
73             # HEADER consistency
74 35 100       93 if ($header_mode eq 'salt') {
    100          
75 25 50       56 croak "Cannot use salt-based key generation if literal key is specified"
76             if $literal_key;
77             }
78             elsif ($header_mode eq 'randomiv') {
79 3 100       108 croak "Cannot encrypt using a non-8 byte blocksize cipher when using randomiv header mode"
80             unless $bs == 8
81             }
82              
83 34 50 33     114 croak "If a key derivation function (-pbkdf) of 'none' is provided, a literal key and iv must be provided"
      66        
84             if $pbkdf eq 'none' && (!defined $key || !defined $iv);
85              
86 34 100 100     286 croak "If a -header mode of 'randomiv' is provided, then the -pbkdf key derivation function must be 'randomiv' or undefined"
87             if $header_mode eq 'randomiv' and $pbkdf ne 'randomiv';
88              
89 33         518 return bless {
90             'cipher' => $cipher,
91             'passphrase' => $pass,
92             'key' => $key,
93             'iv' => $iv,
94             'salt' => $salt,
95             'padding' => $padding,
96             'blocksize' => $bs,
97             'keysize' => $ks,
98             'header_mode' => $header_mode,
99             'literal_key' => $literal_key,
100             'chain_mode' => $chain_mode,
101             'make_random_salt' => $random_salt,
102             'make_random_iv' => $random_iv,
103             'pbkdf' => $pbkdf,
104             'iter' => $iter,
105             'hasher' => $hc,
106             'nodeprecate' => $nodeprecate,
107             },$class;
108             }
109              
110             sub filehandle {
111 0     0 1 0 my $self = shift;
112 0 0       0 $self->_load_module('Crypt::FileHandle')
113             or croak "Optional Crypt::FileHandle module must be installed to use the filehandle() method";
114              
115 0 0       0 if (ref $self) { # already initialized
116 0         0 return Crypt::FileHandle->new($self);
117             }
118             else { # create object
119 0         0 return Crypt::FileHandle->new($self->new(@_));
120             }
121             }
122              
123             sub encrypt (\$$) {
124 881     881 1 5986 my ($self,$data) = @_;
125 881         1568 $self->start('encrypting');
126 881         1475 my $result = $self->crypt($data);
127 881         1583 $result .= $self->finish;
128 881         3146 $result;
129             }
130              
131             sub decrypt (\$$){
132 880     880 1 1227 my ($self,$data) = @_;
133 880         1562 $self->start('decrypting');
134 880         1350 my $result = $self->crypt($data);
135 880         1812 $result .= $self->finish;
136 880         2877 $result;
137             }
138              
139             sub encrypt_hex (\$$) {
140 512     512 1 7968 my ($self,$data) = @_;
141 512         843 return join('',unpack 'H*',$self->encrypt($data));
142             }
143              
144             sub decrypt_hex (\$$) {
145 512     512 1 1475 my ($self,$data) = @_;
146 512         1910 return $self->decrypt(pack'H*',$data);
147             }
148              
149             # call to start a series of encryption/decryption operations
150             sub start (\$$) {
151 1761     1761 1 1861 my $self = shift;
152 1761         1663 my $operation = shift;
153 1761 50       4283 croak "Specify ncryption or ecryption" unless $operation=~/^[ed]/i;
154              
155 1761         2005 delete $self->{'civ'};
156 1761         2349 $self->{'buffer'} = '';
157 1761         3068 $self->{'decrypt'} = $operation=~/^d/i;
158 1761         2746 $self->_deprecation_warning;
159             }
160              
161 5338 50   5338 1 20480 sub chain_mode { shift->{chain_mode} || 'cbc' }
162              
163             sub chaining_method {
164 3262     3262 0 3178 my $self = shift;
165 3262         3326 my $decrypt = shift;
166              
167             # memoize this result
168             return $self->{chaining_method}{$decrypt}
169 3262 100       6453 if exists $self->{chaining_method}{$decrypt};
170            
171 39         74 my $cm = $self->chain_mode;
172 39 100       208 my $code = $self->can($decrypt ? "_${cm}_decrypt" : "_${cm}_encrypt");
173 39 50       89 croak "Chain mode $cm not supported" unless $code;
174 39         112 return $self->{chaining_method}{$decrypt} = $code;
175             }
176              
177             # call to encrypt/decrypt a bit of data
178             sub crypt (\$$){
179 1761     1761 1 1887 my $self = shift;
180 1761         1985 my $data = shift;
181              
182 1761         1616 my $result;
183              
184             croak "crypt() called without a preceding start()"
185 1761 50       2503 unless exists $self->{'buffer'};
186              
187 1761         2251 my $d = $self->{'decrypt'};
188              
189 1761 50       2445 unless ($self->{civ}) { # block cipher has not yet been initialized
190 1761 100       3410 $result = $self->_generate_iv_and_cipher_from_datastream(\$data) if $d;
191 1761 100       3465 $result = $self->_generate_iv_and_cipher_from_options() unless $d;
192             }
193              
194 1761         2219 my $iv = $self->{'civ'};
195 1761         2932 $self->{'buffer'} .= $data;
196              
197 1761         2067 my $bs = $self->{'blocksize'};
198              
199             croak "When using no padding, plaintext size must be a multiple of $bs"
200             if $self->_needs_padding
201 1761 50 66     3197 and $self->{'padding'} eq \&_no_padding
      33        
202             and length($data) % $bs;
203              
204             croak "When using rijndael_compat padding, plaintext size must be a multiple of $bs"
205             if $self->_needs_padding
206 1761 50 66     2809 and $self->{'padding'} eq \&_rijndael_compat
      33        
207             and length($data) % $bs;
208              
209 1761 100       3646 return $result unless (length($self->{'buffer'}) >= $bs);
210              
211 1501         6647 my @blocks = unpack("(a$bs)*",$self->{buffer});
212 1501         2070 $self->{buffer} = '';
213            
214             # if decrypting, leave the last block in the buffer for padding
215 1501 100       2052 if ($d) {
216 864         1189 $self->{buffer} = pop @blocks;
217             } else {
218 637 100       1406 $self->{buffer} = pop @blocks if length $blocks[-1] < $bs;
219             }
220              
221 1501         2638 my $code = $self->chaining_method($d);
222             # $self->$code($self->{crypt},\$iv,\$result,\@blocks);
223             # calling the code sub directly is slightly faster for some reason
224 1501         3214 $code->($self,$self->{crypt},\$iv,\$result,\@blocks);
225              
226 1501         1903 $self->{'civ'} = $iv; # remember the iv
227 1501         3019 return $result;
228             }
229              
230             # this is called at the end to flush whatever's left
231             sub finish (\$) {
232 1761     1761 1 1758 my $self = shift;
233 1761         1856 my $bs = $self->{'blocksize'};
234              
235 1761         2182 my $block = $self->{buffer}; # what's left
236              
237             # Special case hack for backward compatibility with Crypt::Rijndael's CBC_MODE.
238 1761 50 66     3531 if (length $block == 0 && $self->{padding} eq \&_rijndael_compat) {
239 0         0 delete $self->{'civ'};
240 0         0 delete $self->{'buffer'};
241 0         0 return '';
242             }
243            
244 1761   50     2557 $self->{civ} ||= '';
245 1761         1887 my $iv = $self->{civ};
246 1761         2446 my $code = $self->chaining_method($self->{decrypt});
247            
248 1761         2218 my $result = '';
249 1761 100       2479 if ($self->{decrypt}) {
250 880         2181 $self->$code($self->{crypt},\$iv,\$result,[$block]);
251 880 100       1542 $result = $self->{padding}->($result,$bs,'d') if $self->_needs_padding;
252             } else {
253 881 100       1122 $block = $self->{padding}->($block,$bs,'e') if $self->_needs_padding;
254 881 100 100     3216 $self->$code($self->{crypt},\$iv,\$result,[$block]) unless length $block==0 && !$self->_needs_padding
255             }
256            
257 1761         2984 delete $self->{'civ'};
258 1761         1909 delete $self->{'buffer'};
259 1761         2865 return $result;
260             }
261              
262             ############# Move the boring new() argument processing here #######
263             sub _get_options {
264 43     43   63 my $class = shift;
265            
266 43         67 my $options = {};
267            
268             # hashref arguments
269 43 100       262 if (ref $_[0] eq 'HASH') {
    50          
270 1         2 $options = shift;
271             }
272              
273             # CGI style arguments
274             elsif ($_[0] =~ /^-[a-zA-Z_]{1,20}$/) {
275 42         194 my %tmp = @_;
276 42         167 while ( my($key,$value) = each %tmp) {
277 178         427 $key =~ s/^-//;
278 178         633 $options->{lc $key} = $value;
279             }
280             }
281              
282             else {
283 0         0 $options->{key} = shift;
284 0         0 $options->{cipher} = shift;
285             }
286 43         84 return $options;
287             }
288              
289             sub _get_cipher_obj {
290 42     42   62 my $class = shift;
291 42         50 my $options = shift;
292              
293 42         63 my $cipher = $options->{cipher};
294 42 50       126 $cipher = 'Crypt::Cipher::AES' unless $cipher;
295              
296 42 100       93 unless (ref $cipher) { # munge the class name if no object passed
297 40 100       140 $cipher = $cipher=~/^Crypt::/ ? $cipher : "Crypt::$cipher";
298 40 50 33     359 $cipher->can('encrypt') or eval "require $cipher; 1" or croak "Couldn't load $cipher: $@";
299             # some crypt modules use the class Crypt::, and others don't
300 40 50       145 $cipher =~ s/^Crypt::// unless $cipher->can('keysize');
301             }
302              
303 42         78 return $cipher;
304             }
305              
306             sub _validate_options {
307 43     43   61 my $self = shift;
308 43         56 my $options = shift;
309 43         87 my %valid_options = map {$_=>1} @valid_options;
  774         1115  
310 43         173 for my $o (keys %$options) {
311 185 100       578 die "'$o' is not a recognized argument" unless $valid_options{$o};
312             }
313 42         171 return 1;
314             }
315              
316             sub _get_header_mode {
317 42     42   57 my $class = shift;
318 42         53 my $options = shift;
319              
320             # header mode checking
321 42         73 my %valid_modes = map {$_=>1} qw(none salt randomiv);
  126         243  
322 42         75 my $header_mode = $options->{header};
323 42 50 0     114 $header_mode ||= 'none' if exists $options->{prepend_iv} && !$options->{prepend_iv};
      33        
324 42 50 0     102 $header_mode ||= 'none' if exists $options->{add_header} && !$options->{add_header};
      33        
325 42 100 100     240 $header_mode ||= 'none' if $options->{literal_key} || (exists $options->{pbkdf} && $options->{pbkdf} eq 'none');
      100        
      100        
326 42   100     116 $header_mode ||= 'salt'; # default
327 42 100       191 croak "Invalid -header mode '$header_mode'" unless $valid_modes{$header_mode};
328              
329 41         105 return $header_mode;
330             }
331              
332             sub _get_padding_mode {
333 39     39   53 my $class = shift;
334 39         59 my ($bs,$options) = @_;
335              
336 39   100     117 my $padding = $options->{padding} || 'standard';
337              
338 39 50 33     150 if ($padding && ref($padding) eq 'CODE') {
339             # check to see that this code does its padding correctly
340 0         0 for my $i (1..$bs-1) {
341 0         0 my $rbs = length($padding->(" "x$i,$bs,'e'));
342 0 0       0 croak "padding method callback does not behave properly: expected $bs bytes back, got $rbs bytes back."
343             unless ($rbs == $bs);
344             }
345             } else {
346 39 50       220 $padding = $padding eq 'none' ? \&_no_padding
    50          
    100          
    100          
    100          
    100          
347             :$padding eq 'null' ? \&_null_padding
348             :$padding eq 'space' ? \&_space_padding
349             :$padding eq 'oneandzeroes' ? \&_oneandzeroes_padding
350             :$padding eq 'rijndael_compat'? \&_rijndael_compat
351             :$padding eq 'standard' ? \&_standard_padding
352             :croak "'$padding' padding not supported. See perldoc Crypt::CBC for instructions on creating your own.";
353             }
354 39         73 return $padding;
355             }
356              
357             sub _get_key_and_block_sizes {
358 41     41   57 my $class = shift;
359 41         53 my $cipher = shift;
360 41         60 my $options = shift;
361            
362             # allow user to override the keysize value
363 41 50 33     103 my $ks = $options->{keysize} || eval {$cipher->keysize} || eval {$cipher->max_keysize}
364             or croak "Cannot derive keysize from $cipher";
365              
366 41 50       413 my $bs = eval {$cipher->blocksize}
  41         118  
367             or croak "$cipher did not provide a blocksize";
368              
369 41         190 return ($ks,$bs);
370             }
371              
372             sub _get_key_materials {
373 41     41   65 my $self = shift;
374 41         51 my $options = shift;
375              
376             # "key" is a misnomer here, because it is actually usually a passphrase that is used
377             # to derive the true key
378 41   100     139 my $pass = $options->{pass} || $options->{key};
379              
380 41   66     152 my $cipher_object_provided = $options->{cipher} && ref $options->{cipher};
381 41 100       87 if ($cipher_object_provided) {
382 2 50       6 carp "Both a key and a pre-initialized Crypt::* object were passed. The key will be ignored"
383             if defined $pass;
384 2   50     19 $pass ||= '';
385             }
386              
387 41 100       187 croak "Please provide an encryption/decryption passphrase using -pass or -key"
388             unless defined $pass;
389              
390             # Default behavior is to treat -key as a passphrase.
391             # But if the literal_key option is true, then use key as is
392             croak "The options -literal_key and -regenerate_key are incompatible with each other"
393 40 50 66     98 if exists $options->{literal_key} && exists $options->{regenerate_key};
394              
395 40 100       79 my $key = $pass if $options->{literal_key};
396 40 50 33     106 $key = $pass if exists $options->{regenerate_key} && !$options->{regenerate_key};
397              
398             # Get the salt.
399 40         70 my $salt = $options->{salt};
400 40 100 100     128 my $random_salt = 1 unless defined $salt && $salt ne '1';
401 40 100 100     234 croak "Argument to -salt must be exactly 8 bytes long" if defined $salt && length $salt != 8 && $salt ne '1';
      100        
402              
403             # note: iv will be autogenerated by start() if not specified in options
404 39         51 my $iv = $options->{iv};
405 39 100       85 my $random_iv = 1 unless defined $iv;
406              
407 39   66     148 my $literal_key = $options->{literal_key} || (exists $options->{regenerate_key} && !$options->{regenerate_key});
408 39 100       81 undef $pass if $literal_key;
409              
410 39         129 return ($pass,$iv,$salt,$key,$random_salt,$random_iv);
411             }
412              
413             sub _get_key_derivation_options {
414 39     39   64 my $self = shift;
415 39         79 my ($options,$header_mode) = @_;
416            
417             # KEY DERIVATION PARAMETERS
418             # Some special cases here
419             # 1. literal key has been requested - use algorithm 'none'
420             # 2. headerless mode - use algorithm 'none'
421             # 3. randomiv header - use algorithm 'nosalt'
422 39   66     134 my $pbkdf = $options->{pbkdf} || ($options->{literal_key} ? 'none'
423             :$header_mode eq 'randomiv' ? 'randomiv'
424             :DEFAULT_PBKDF);
425             # iterations
426 39   100     126 my $iter = $options->{iter} || DEFAULT_ITER;
427 39 50 33     250 $iter =~ /[\d_]+/ && $iter >= 1 or croak "-iterations argument must be greater than or equal to 1";
428 39 50 33     230 $iter =~ /[\d_]+/ && $iter >= 1 or croak "-iterations argument must be greater than or equal to 1";
429              
430             # hasher
431 39         71 my $hc = $options->{hasher};
432 39         48 my $nodeprecate = $options->{nodeprecate};
433            
434 39         125 return ($pbkdf,$iter,$hc,$nodeprecate);
435             }
436              
437             sub _get_chain_mode {
438 39     39   64 my $self = shift;
439 39         54 my $options = shift;
440             return $options->{chain_mode} ? $options->{chain_mode}
441 39 50       122 :$options->{pcbc} ? 'pcbc'
    100          
442             :'cbc';
443             }
444              
445             sub _load_module {
446 0     0   0 my $self = shift;
447 0         0 my ($module,$args) = @_;
448 0         0 my $result = eval "use $module $args; 1;";
449 0 0       0 warn $@ if $@;
450 0         0 return $result;
451             }
452              
453             sub _deprecation_warning {
454 1761     1761   1856 my $self = shift;
455 1761 100       2509 return if $self->nodeprecate;
456 1748 100       3096 return if $self->{decrypt};
457 874         1313 my $pbkdf = $self->pbkdf;
458 874 50       2407 carp <
459             WARNING: The key derivation method "$pbkdf" is deprecated. Using -pbkdf=>'pbkdf2' would be better.
460             Pass -nodeprecate=>1 to inhibit this message.
461             END
462              
463              
464             }
465              
466             ######################################### chaining mode methods ################################3
467             sub _needs_padding {
468 5299     5299   5111 my $self = shift;
469 5299 100       6239 $self->chain_mode =~ /^p?cbc$/ && $self->padding ne \&_no_padding;
470             }
471              
472             sub _cbc_encrypt {
473 1433     1433   1506 my $self = shift;
474 1433         1748 my ($crypt,$iv,$result,$blocks) = @_;
475             # the copying looks silly, but it is slightly faster than dereferencing the
476             # variables each time
477 1433         1951 my ($i,$r) = ($$iv,$$result);
478 1433         1981 foreach (@$blocks) {
479 3158         10507 $r .= $i = $crypt->encrypt($i ^ $_);
480             }
481 1433         3099 ($$iv,$$result) = ($i,$r);
482             }
483              
484             sub _cbc_decrypt {
485 1644     1644   1488 my $self = shift;
486 1644         2094 my ($crypt,$iv,$result,$blocks) = @_;
487             # the copying looks silly, but it is slightly faster than dereferencing the
488             # variables each time
489 1644         2041 my ($i,$r) = ($$iv,$$result);
490 1644         2246 foreach (@$blocks) {
491 3157         7789 $r .= $i ^ $crypt->decrypt($_);
492 3157         4390 $i = $_;
493             }
494 1644         2692 ($$iv,$$result) = ($i,$r);
495             }
496              
497             sub _pcbc_encrypt {
498 42     42   88 my $self = shift;
499 42         105 my ($crypt,$iv,$result,$blocks) = @_;
500 42         93 foreach my $plaintext (@$blocks) {
501 82         476 $$result .= $$iv = $crypt->encrypt($$iv ^ $plaintext);
502 82         183 $$iv ^= $plaintext;
503             }
504             }
505              
506             sub _pcbc_decrypt {
507 58     58   72 my $self = shift;
508 58         112 my ($crypt,$iv,$result,$blocks) = @_;
509 58         124 foreach my $ciphertext (@$blocks) {
510 82         441 $$result .= $$iv = $$iv ^ $crypt->decrypt($ciphertext);
511 82         164 $$iv ^= $ciphertext;
512             }
513             }
514              
515             sub _cfb_encrypt {
516 0     0   0 my $self = shift;
517 0         0 my ($crypt,$iv,$result,$blocks) = @_;
518 0         0 my ($i,$r) = ($$iv,$$result);
519 0         0 foreach my $plaintext (@$blocks) {
520 0         0 $r .= $i = $plaintext ^ $crypt->encrypt($i)
521             }
522 0         0 ($$iv,$$result) = ($i,$r);
523             }
524              
525             sub _cfb_decrypt {
526 0     0   0 my $self = shift;
527 0         0 my ($crypt,$iv,$result,$blocks) = @_;
528 0         0 my ($i,$r) = ($$iv,$$result);
529 0         0 foreach my $ciphertext (@$blocks) {
530 0         0 $r .= $ciphertext ^ $crypt->encrypt($i);
531 0         0 $i = $ciphertext;
532             }
533 0         0 ($$iv,$$result) = ($i,$r);
534             }
535              
536             sub _ofb_encrypt {
537 82     82   80 my $self = shift;
538 82         93 my ($crypt,$iv,$result,$blocks) = @_;
539 82         105 my ($i,$r) = ($$iv,$$result);
540 82         105 foreach my $plaintext (@$blocks) {
541 165         414 my $ciphertext = $plaintext ^ ($i = $crypt->encrypt($i));
542 165         197 substr($ciphertext,length $plaintext) = ''; # truncate
543 165         205 $r .= $ciphertext;
544             }
545 82         136 ($$iv,$$result) = ($i,$r);
546             }
547              
548             *_ofb_decrypt = \&_ofb_encrypt; # same code
549              
550             # According to RFC3686, the counter is 128 bits (16 bytes)
551             # The first 32 bits (4 bytes) is the nonce
552             # The next 64 bits (8 bytes) is the IV
553             # The final 32 bits (4 bytes) is the counter, starting at 1
554             # BUT, the way that openssl v1.1.1 does it is to generate a random
555             # IV, treat the whole thing as a blocksize-sized integer, and then
556             # increment.
557             sub _ctr_encrypt {
558 0     0   0 my $self = shift;
559 0         0 my ($crypt,$iv,$result,$blocks) = @_;
560 0         0 my $bs = $self->blocksize;
561            
562 0         0 $self->_upgrade_iv_to_ctr($iv);
563 0         0 my ($i,$r) = ($$iv,$$result);
564              
565 0         0 foreach my $plaintext (@$blocks) {
566 0         0 my $bytes = int128_to_net($i++);
567              
568             # pad with leading nulls if there are insufficient bytes
569             # (there's gotta be a better way to do this)
570 0 0       0 if ($bs > length $bytes) {
571 0         0 substr($bytes,0,0) = "\000"x($bs-length $bytes) ;
572             }
573              
574 0         0 my $ciphertext = $plaintext ^ ($crypt->encrypt($bytes));
575 0         0 substr($ciphertext,length $plaintext) = ''; # truncate
576 0         0 $r .= $ciphertext;
577             }
578 0         0 ($$iv,$$result) = ($i,$r);
579             }
580              
581             *_ctr_decrypt = \&_ctr_encrypt; # same code
582              
583             # upgrades instance vector to a CTR counter
584             # returns 1 if upgrade performed
585             sub _upgrade_iv_to_ctr {
586 0     0   0 my $self = shift;
587 0         0 my $iv = shift; # this is a scalar reference
588 0 0       0 return if ref $$iv; # already upgraded to an object
589              
590 0 0       0 $self->_load_module("Math::Int128" => "'net_to_int128','int128_to_net'")
591             or croak "Optional Math::Int128 module must be installed to use the CTR chaining method";
592              
593 0         0 $$iv = net_to_int128($$iv);
594 0         0 return 1;
595             }
596              
597             ######################################### chaining mode methods ################################3
598              
599 2643     2643 1 3540 sub pbkdf { shift->{pbkdf} }
600              
601             # get the initialized PBKDF object
602             sub pbkdf_obj {
603 1762     1762 0 1963 my $self = shift;
604 1762         2457 my $pbkdf = $self->pbkdf;
605 1762         2328 my $iter = $self->{iter};
606 1762         1773 my $hc = $self->{hasher};
607 1762 100       2935 my @hash_args = $hc ? ref ($hc) ? (hasher => $hc) : (hash_class => $hc)
    100          
608             : ();
609             return Crypt::CBC::PBKDF->new($pbkdf =>
610             {
611             key_len => $self->{keysize},
612             iv_len => $self->{blocksize},
613 1762         7878 iterations => $iter,
614             @hash_args,
615             }
616             );
617             }
618              
619             ############################# generating key, iv and salt ########################
620             # hopefully a replacement for mess below
621             sub set_key_and_iv {
622 888     888 0 1079 my $self = shift;
623              
624 888 100       1596 if (!$self->{literal_key}) {
625 885         1474 my ($key,$iv) = $self->pbkdf_obj->key_and_iv($self->{salt},$self->{passphrase});
626 885         4726 $self->{key} = $key;
627 885 100       2095 $self->{iv} = $iv if $self->{make_random_iv};
628             } else {
629 3 50       9 $self->{iv} = $self->_get_random_bytes($self->blocksize) if $self->{make_random_iv};
630             }
631              
632 888 50       1608 length $self->{salt} == 8 or croak "Salt must be exactly 8 bytes long";
633 888 50       1819 length $self->{iv} == $self->{blocksize} or croak "IV must be exactly $self->{blocksize} bytes long";
634             }
635              
636             # derive the salt, iv and key from the datastream header + passphrase
637             sub _read_key_and_iv {
638 880     880   816 my $self = shift;
639 880         830 my $input_stream = shift;
640 880         1127 my $bs = $self->blocksize;
641              
642             # use our header mode to figure out what to do with the data stream
643 880         1131 my $header_mode = $self->header_mode;
644              
645 880 100       1910 if ($header_mode eq 'none') {
    100          
    50          
646 4   66     10 $self->{salt} ||= $self->_get_random_bytes(8);
647 4         7 return $self->set_key_and_iv;
648             }
649              
650             elsif ($header_mode eq 'salt') {
651 875         3114 ($self->{salt}) = $$input_stream =~ /^Salted__(.{8})/s;
652 875 50       1607 croak "Ciphertext does not begin with a valid header for 'salt' header mode" unless defined $self->{salt};
653 875         1642 substr($$input_stream,0,16) = '';
654 875         1462 ($self->{key},$self->{iv}) = $self->pbkdf_obj->key_and_iv($self->{salt},$self->{passphrase});
655             }
656              
657             elsif ($header_mode eq 'randomiv') {
658 1         4 ($self->{iv}) = $$input_stream =~ /^RandomIV(.{8})/s;
659 1 50       3 croak "Ciphertext does not begin with a valid header for 'randomiv' header mode" unless defined $self->{iv};
660 1 50       3 croak "randomiv header mode cannot be used securely when decrypting with a >8 byte block cipher.\n"
661             unless $self->blocksize == 8;
662 1         2 (undef,$self->{key}) = $self->pbkdf_obj->key_and_iv(undef,$self->{passphrase});
663 1         10 substr($$input_stream,0,16) = ''; # truncate
664             }
665              
666             else {
667 0         0 croak "Invalid header mode '$header_mode'";
668             }
669             }
670              
671             # this subroutine will generate the actual {en,de}cryption key, the iv
672             # and the block cipher object. This is called when reading from a datastream
673             # and so it uses previous values of salt or iv if they are encoded in datastream
674             # header
675             sub _generate_iv_and_cipher_from_datastream {
676 880     880   981 my $self = shift;
677 880         842 my $input_stream = shift;
678              
679 880         1576 $self->_read_key_and_iv($input_stream);
680 880         4996 $self->{civ} = $self->{iv};
681            
682             # we should have the key and iv now, or we are dead in the water
683             croak "Could not derive key or iv from cipher stream, and you did not specify these values in new()"
684 880 50 33     3027 unless $self->{key} && $self->{civ};
685              
686             # now we can generate the crypt object itself
687             $self->{crypt} = ref $self->{cipher} ? $self->{cipher}
688             : $self->{cipher}->new($self->{key})
689 880 100       9099 or croak "Could not create $self->{cipher} object: $@";
    50          
690 880         1808 return '';
691             }
692              
693             sub _generate_iv_and_cipher_from_options {
694 881     881   970 my $self = shift;
695              
696 881 50       1904 $self->{salt} = $self->_get_random_bytes(8) if $self->{make_random_salt};
697 881         2677 $self->set_key_and_iv;
698 881         1339 $self->{civ} = $self->{iv};
699              
700 881         979 my $result = '';
701 881         1668 my $header_mode = $self->header_mode;
702            
703 881 100       1672 if ($header_mode eq 'salt') {
    100          
704 876         1507 $result = "Salted__$self->{salt}";
705             }
706              
707             elsif ($header_mode eq 'randomiv') {
708 2         4 $result = "RandomIV$self->{iv}";
709 2         4 undef $self->{salt}; # shouldn't be there!
710             }
711              
712 881 50 33     2787 croak "key and/or iv are missing" unless defined $self->{key} && defined $self->{civ};
713              
714 881         1792 $self->_taintcheck($self->{key});
715             $self->{crypt} = ref $self->{cipher} ? $self->{cipher}
716             : $self->{cipher}->new($self->{key})
717 881 100       9056 or croak "Could not create $self->{cipher} object: $@";
    50          
718 881         1926 return $result;
719             }
720              
721             sub _taintcheck {
722 881     881   916 my $self = shift;
723 881         928 my $key = shift;
724 881 50       2425 return unless ${^TAINT};
725              
726 0         0 my $has_scalar_util = eval "require Scalar::Util; 1";
727 0         0 my $tainted;
728              
729              
730 0 0       0 if ($has_scalar_util) {
731 0         0 $tainted = Scalar::Util::tainted($key);
732             } else {
733 0         0 local($@, $SIG{__DIE__}, $SIG{__WARN__});
734 0         0 local $^W = 0;
735 0         0 eval { kill 0 * $key };
  0         0  
736 0         0 $tainted = $@ =~ /^Insecure/;
737             }
738              
739 0 0       0 croak "Taint checks are turned on and your key is tainted. Please untaint the key and try again"
740             if $tainted;
741             }
742              
743             sub _digest_obj {
744 0     0   0 my $self = shift;
745              
746 0 0       0 if ($self->{digest_obj}) {
747 0         0 $self->{digest_obj}->reset();
748 0         0 return $self->{digest_obj};
749             }
750              
751 0         0 my $alg = $self->{digest_alg};
752 0 0 0     0 return $alg if ref $alg && $alg->can('digest');
753 0         0 my $obj = eval {Digest->new($alg)};
  0         0  
754 0 0       0 croak "Unable to instantiate '$alg' digest object: $@" if $@;
755              
756 0         0 return $self->{digest_obj} = $obj;
757             }
758              
759             sub random_bytes {
760 2     2 1 3 my $self = shift;
761 2 50       4 my $bytes = shift or croak "usage: random_bytes(\$byte_length)";
762 2         4 $self->_get_random_bytes($bytes);
763             }
764              
765             sub _get_random_bytes {
766 888     888   974 my $self = shift;
767 888         885 my $length = shift;
768 888         811 my $result;
769              
770 888 50 33     35418 if (-r RANDOM_DEVICE && open(F,RANDOM_DEVICE)) {
771 888         495279 read(F,$result,$length);
772 888         10732 close F;
773             } else {
774 0         0 $result = pack("C*",map {rand(256)} 1..$length);
  0         0  
775             }
776             # Clear taint and check length
777 888         4222 $result =~ /^(.+)$/s;
778 888 50       2909 length($1) == $length or croak "Invalid length while gathering $length random bytes";
779 888         2976 return $1;
780             }
781              
782             sub _standard_padding ($$$) {
783 566     566   1075 my ($b,$bs,$decrypt) = @_;
784              
785 566 100       972 if ($decrypt eq 'd') {
786 283         622 my $pad_length = unpack("C",substr($b,-1));
787 283         802 return substr($b,0,$bs-$pad_length);
788             }
789 283         400 my $pad = $bs - length($b);
790 283         1348 return $b . pack("C*",($pad)x$pad);
791             }
792              
793             sub _space_padding ($$$) {
794 378     378   595 my ($b,$bs,$decrypt) = @_;
795              
796 378 100       537 if ($decrypt eq 'd') {
797 189         805 $b=~ s/ *\z//s;
798             } else {
799 189         688 $b .= pack("C*", (32) x ($bs-length($b)));
800             }
801 378         607 return $b;
802             }
803              
804             sub _no_padding ($$$) {
805 0     0   0 my ($b,$bs,$decrypt) = @_;
806 0         0 return $b;
807             }
808              
809             sub _null_padding ($$$) {
810 378     378   672 my ($b,$bs,$decrypt) = @_;
811 378 100       860 return unless length $b;
812 365 50       520 $b = length $b ? $b : '';
813 365 100       509 if ($decrypt eq 'd') {
814 189         774 $b=~ s/\0*\z//s;
815 189         421 return $b;
816             }
817 176         765 return $b . pack("C*", (0) x ($bs - length($b) % $bs));
818             }
819              
820             sub _oneandzeroes_padding ($$$) {
821 380     380   605 my ($b,$bs,$decrypt) = @_;
822 380 100       571 if ($decrypt eq 'd') {
823 190         669 $b=~ s/\x80\0*\z//s;
824 190         400 return $b;
825             }
826 190         654 return $b . pack("C*", 128, (0) x ($bs - length($b) - 1) );
827             }
828              
829             sub _rijndael_compat ($$$) {
830 0     0   0 my ($b,$bs,$decrypt) = @_;
831              
832 0 0       0 return unless length $b;
833 0 0       0 if ($decrypt eq 'd') {
834 0         0 $b=~ s/\x80\0*\z//s;
835 0         0 return $b;
836             }
837 0         0 return $b . pack("C*", 128, (0) x ($bs - length($b) % $bs - 1) );
838             }
839              
840             sub get_initialization_vector (\$) {
841 0     0 1 0 my $self = shift;
842 0         0 $self->iv();
843             }
844              
845             sub set_initialization_vector (\$$) {
846 0     0 1 0 my $self = shift;
847 0         0 my $iv = shift;
848 0         0 my $bs = $self->blocksize;
849 0 0       0 croak "Initialization vector must be $bs bytes in length" unless length($iv) == $bs;
850 0         0 $self->iv($iv);
851             }
852              
853             sub salt {
854 11     11 1 23 my $self = shift;
855 11         16 my $d = $self->{salt};
856 11 50       21 $self->{salt} = shift if @_;
857 11         35 $d;
858             }
859              
860             sub iv {
861 15     15 1 105 my $self = shift;
862 15         22 my $d = $self->{iv};
863 15 50       29 $self->{iv} = shift if @_;
864 15         48 $d;
865             }
866              
867             sub key {
868 15     15 1 36 my $self = shift;
869 15         22 my $d = $self->{key};
870 15 50       29 $self->{key} = shift if @_;
871 15         52 $d;
872             }
873              
874             sub passphrase {
875 4     4 1 6 my $self = shift;
876 4         5 my $d = $self->{passphrase};
877 4 100       9 if (@_) {
878 1         3 undef $self->{key};
879 1         1 undef $self->{iv};
880 1         2 $self->{passphrase} = shift;
881             }
882 4         26 $d;
883             }
884              
885             sub keysize {
886 0     0 1 0 my $self = shift;
887 0 0       0 $self->{keysize} = shift if @_;
888 0         0 $self->{keysize};
889             }
890              
891 0     0 1 0 sub cipher { shift->{cipher} }
892 5123     5123 1 27293 sub padding { shift->{padding} }
893 881     881 1 1090 sub blocksize { shift->{blocksize} }
894 0     0 0 0 sub pcbc { shift->{pcbc} }
895 1765     1765 0 2553 sub header_mode {shift->{header_mode} }
896 1     1 0 22 sub literal_key {shift->{literal_key}}
897 1761     1761 0 2902 sub nodeprecate {shift->{nodeprecate}}
898            
899             1;
900             __END__