File Coverage

lib/Crypt/CBC.pm
Criterion Covered Total %
statement 352 445 79.1
branch 163 246 66.2
condition 74 121 61.1
subroutine 57 71 80.2
pod 22 29 75.8
total 668 912 73.2


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