File Coverage

lib/Crypt/CBC.pm
Criterion Covered Total %
statement 347 442 78.5
branch 155 238 65.1
condition 71 118 60.1
subroutine 56 71 78.8
pod 22 29 75.8
total 651 898 72.4


line stmt bran cond sub pod time code
1             package Crypt::CBC;
2              
3 8     8   42499 use strict;
  8         17  
  8         303  
4 8     8   42 use Carp 'croak','carp';
  8         14  
  8         497  
5 8     8   3319 use Crypt::CBC::PBKDF;
  8         20  
  8         240  
6 8     8   5386 use bytes;
  8         124  
  8         43  
7 8     8   305 use vars qw($VERSION);
  8         13  
  8         537  
8 8     8   50 no warnings 'uninitialized';
  8         15  
  8         481  
9             $VERSION = '3.02';
10              
11 8     8   45 use constant RANDOM_DEVICE => '/dev/urandom';
  8         14  
  8         916  
12 8     8   49 use constant DEFAULT_PBKDF => 'opensslv1';
  8         13  
  8         379  
13 8     8   41 use constant DEFAULT_ITER => 10_000; # same as OpenSSL default
  8         27  
  8         51350  
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 42     42 1 71940 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 42         151 my $options = $class->_get_options(@_);
42 42 100       77 eval {$class->_validate_options($options)} or croak $@;
  42         120  
43            
44 41         114 my $cipher = $class->_get_cipher_obj($options);
45 41         109 my $header_mode = $class->_get_header_mode($options);
46 40         139 my ($ks,$bs) = $class->_get_key_and_block_sizes($cipher,$options);
47 40         113 my ($pass,$iv,$salt,$key,
48             $random_salt,$random_iv) = $class->_get_key_materials($options);
49 38         117 my $padding = $class->_get_padding_mode($bs,$options);
50 38         109 my ($pbkdf,$iter,
51             $hc,$nodeprecate) = $class->_get_key_derivation_options($options,$header_mode);
52 38         125 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 38 100 66     109 $key ||= $pass if $pbkdf eq 'none'; # just in case
58 38         62 my $literal_key = defined $key;
59              
60             # check length of initialization vector
61 38 100 100     461 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 36 50       263 croak "invalid cipher block chain mode: $chain_mode"
66             unless $class->can("_${chain_mode}_encrypt");
67              
68             # KEYSIZE consistency
69 36 100 100     120 if (defined $key && length($key) != $ks) {
70 2         323 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 34 100       95 if ($header_mode eq 'salt') {
    100          
75 25 50       75 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       116 croak "Cannot encrypt using a non-8 byte blocksize cipher when using randomiv header mode"
80             unless $bs == 8
81             }
82              
83 33 50 33     117 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 33 100 100     433 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 32         613 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 880     880 1 7261 my ($self,$data) = @_;
125 880         1947 $self->start('encrypting');
126 880         1835 my $result = $self->crypt($data);
127 880         2003 $result .= $self->finish;
128 880         4057 $result;
129             }
130              
131             sub decrypt (\$$){
132 880     880 1 1615 my ($self,$data) = @_;
133 880         1975 $self->start('decrypting');
134 880         1684 my $result = $self->crypt($data);
135 880         1948 $result .= $self->finish;
136 880         3303 $result;
137             }
138              
139             sub encrypt_hex (\$$) {
140 512     512 1 10874 my ($self,$data) = @_;
141 512         1062 return join('',unpack 'H*',$self->encrypt($data));
142             }
143              
144             sub decrypt_hex (\$$) {
145 512     512 1 1841 my ($self,$data) = @_;
146 512         2427 return $self->decrypt(pack'H*',$data);
147             }
148              
149             # call to start a series of encryption/decryption operations
150             sub start (\$$) {
151 1760     1760 1 2126 my $self = shift;
152 1760         2064 my $operation = shift;
153 1760 50       5073 croak "Specify ncryption or ecryption" unless $operation=~/^[ed]/i;
154              
155 1760         2397 delete $self->{'civ'};
156 1760         2993 $self->{'buffer'} = '';
157 1760         3834 $self->{'decrypt'} = $operation=~/^d/i;
158 1760         3243 $self->_deprecation_warning;
159             }
160              
161 5318 50   5318 1 36341 sub chain_mode { shift->{chain_mode} || 'cbc' }
162              
163             sub chaining_method {
164 3260     3260 0 3874 my $self = shift;
165 3260         3845 my $decrypt = shift;
166              
167             # memoize this result
168             return $self->{chaining_method}{$decrypt}
169 3260 100       7703 if exists $self->{chaining_method}{$decrypt};
170            
171 38         111 my $cm = $self->chain_mode;
172 38 100       348 my $code = $self->can($decrypt ? "_${cm}_decrypt" : "_${cm}_encrypt");
173 38 50       102 croak "Chain mode $cm not supported" unless $code;
174 38         141 return $self->{chaining_method}{$decrypt} = $code;
175             }
176              
177             # call to encrypt/decrypt a bit of data
178             sub crypt (\$$){
179 1760     1760 1 2138 my $self = shift;
180 1760         2206 my $data = shift;
181              
182 1760         1862 my $result;
183              
184             croak "crypt() called without a preceding start()"
185 1760 50       3037 unless exists $self->{'buffer'};
186              
187 1760         2438 my $d = $self->{'decrypt'};
188              
189 1760 50       3316 unless ($self->{civ}) { # block cipher has not yet been initialized
190 1760 100       4454 $result = $self->_generate_iv_and_cipher_from_datastream(\$data) if $d;
191 1760 100       4273 $result = $self->_generate_iv_and_cipher_from_options() unless $d;
192             }
193              
194 1760         2933 my $iv = $self->{'civ'};
195 1760         3959 $self->{'buffer'} .= $data;
196              
197 1760         2442 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 1760 50 66     3857 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 1760 50 66     3825 and $self->{'padding'} eq \&_rijndael_compat
      33        
207             and length($data) % $bs;
208              
209 1760 100       4956 return $result unless (length($self->{'buffer'}) >= $bs);
210              
211 1500         8256 my @blocks = unpack("(a$bs)*",$self->{buffer});
212 1500         2576 $self->{buffer} = '';
213            
214             # if decrypting, leave the last block in the buffer for padding
215 1500 100       2621 if ($d) {
216 864         1448 $self->{buffer} = pop @blocks;
217             } else {
218 636 100       1732 $self->{buffer} = pop @blocks if length $blocks[-1] < $bs;
219             }
220              
221 1500         3112 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 1500         3950 $code->($self,$self->{crypt},\$iv,\$result,\@blocks);
225              
226 1500         2335 $self->{'civ'} = $iv; # remember the iv
227 1500         3761 return $result;
228             }
229              
230             # this is called at the end to flush whatever's left
231             sub finish (\$) {
232 1760     1760 1 2017 my $self = shift;
233 1760         2287 my $bs = $self->{'blocksize'};
234              
235 1760         2536 my $block = $self->{buffer}; # what's left
236              
237             # Special case hack for backward compatibility with Crypt::Rijndael's CBC_MODE.
238 1760 50 66     4063 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 1760   50     3043 $self->{civ} ||= '';
245 1760         2407 my $iv = $self->{civ};
246 1760         2899 my $code = $self->chaining_method($self->{decrypt});
247            
248 1760         2412 my $result = '';
249 1760 100       2957 if ($self->{decrypt}) {
250 880         2717 $self->$code($self->{crypt},\$iv,\$result,[$block]);
251 880 100       1775 $result = $self->{padding}->($result,$bs,'d') if $self->_needs_padding;
252             } else {
253 880 100       1300 $block = $self->{padding}->($block,$bs,'e') if $self->_needs_padding;
254 880         3008 $self->$code($self->{crypt},\$iv,\$result,[$block]);
255             }
256            
257 1760         3476 delete $self->{'civ'};
258 1760         2384 delete $self->{'buffer'};
259 1760         3411 return $result;
260             }
261              
262             ############# Move the boring new() argument processing here #######
263             sub _get_options {
264 42     42   80 my $class = shift;
265            
266 42         80 my $options = {};
267            
268             # hashref arguments
269 42 50       309 if (ref $_[0] eq 'HASH') {
    50          
270 0         0 $options = shift;
271             }
272              
273             # CGI style arguments
274             elsif ($_[0] =~ /^-[a-zA-Z_]{1,20}$/) {
275 42         203 my %tmp = @_;
276 42         217 while ( my($key,$value) = each %tmp) {
277 178         503 $key =~ s/^-//;
278 178         683 $options->{lc $key} = $value;
279             }
280             }
281              
282             else {
283 0         0 $options->{key} = shift;
284 0         0 $options->{cipher} = shift;
285             }
286 42         90 return $options;
287             }
288              
289             sub _get_cipher_obj {
290 41     41   87 my $class = shift;
291 41         63 my $options = shift;
292              
293 41         68 my $cipher = $options->{cipher};
294 41 50       102 $cipher = 'Crypt::Cipher::AES' unless $cipher;
295              
296 41 100       92 unless (ref $cipher) { # munge the class name if no object passed
297 39 100       142 $cipher = $cipher=~/^Crypt::/ ? $cipher : "Crypt::$cipher";
298 39 50 33     323 $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 39 50       249 $cipher =~ s/^Crypt::// unless $cipher->can('keysize');
301             }
302              
303 41         90 return $cipher;
304             }
305              
306             sub _validate_options {
307 42     42   72 my $self = shift;
308 42         52 my $options = shift;
309 42         103 my %valid_options = map {$_=>1} @valid_options;
  756         1287  
310 42         185 for my $o (keys %$options) {
311 177 100       564 die "'$o' is not a recognized argument" unless $valid_options{$o};
312             }
313 41         176 return 1;
314             }
315              
316             sub _get_header_mode {
317 41     41   68 my $class = shift;
318 41         61 my $options = shift;
319              
320             # header mode checking
321 41         71 my %valid_modes = map {$_=>1} qw(none salt randomiv);
  123         247  
322 41         146 my $header_mode = $options->{header};
323 41 50 0     124 $header_mode ||= 'none' if exists $options->{prepend_iv} && !$options->{prepend_iv};
      33        
324 41 50 0     111 $header_mode ||= 'none' if exists $options->{add_header} && !$options->{add_header};
      33        
325 41 100 100     254 $header_mode ||= 'none' if $options->{literal_key} || (exists $options->{pbkdf} && $options->{pbkdf} eq 'none');
      100        
      100        
326 41   100     130 $header_mode ||= 'salt'; # default
327 41 100       220 croak "Invalid -header mode '$header_mode'" unless $valid_modes{$header_mode};
328              
329 40         99 return $header_mode;
330             }
331              
332             sub _get_padding_mode {
333 38     38   60 my $class = shift;
334 38         68 my ($bs,$options) = @_;
335              
336 38   100     158 my $padding = $options->{padding} || 'standard';
337              
338 38 50 33     176 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 38 50       241 $padding = $padding eq 'none' ? \&_no_padding
    50          
    100          
    100          
    100          
    50          
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 38         101 return $padding;
355             }
356              
357             sub _get_key_and_block_sizes {
358 40     40   62 my $class = shift;
359 40         56 my $cipher = shift;
360 40         72 my $options = shift;
361            
362             # allow user to override the keysize value
363 40 50 33     134 my $ks = $options->{keysize} || eval {$cipher->keysize} || eval {$cipher->max_keysize}
364             or croak "Cannot derive keysize from $cipher";
365              
366 40 50       492 my $bs = eval {$cipher->blocksize}
  40         123  
367             or croak "$cipher did not provide a blocksize";
368              
369 40         220 return ($ks,$bs);
370             }
371              
372             sub _get_key_materials {
373 40     40   60 my $self = shift;
374 40         62 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 40   100     146 my $pass = $options->{pass} || $options->{key};
379              
380 40   66     170 my $cipher_object_provided = $options->{cipher} && ref $options->{cipher};
381 40 100       102 if ($cipher_object_provided) {
382 2 50       9 carp "Both a key and a pre-initialized Crypt::* object were passed. The key will be ignored"
383             if defined $pass;
384 2   50     10 $pass ||= '';
385             }
386              
387 40 100       209 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 39 50 66     92 if exists $options->{literal_key} && exists $options->{regenerate_key};
394              
395 39 100       95 my $key = $pass if $options->{literal_key};
396 39 50 33     98 $key = $pass if exists $options->{regenerate_key} && !$options->{regenerate_key};
397              
398             # Get the salt.
399 39         57 my $salt = $options->{salt};
400 39 100 100     166 my $random_salt = 1 unless defined $salt && $salt ne '1';
401 39 100 100     239 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 38         70 my $iv = $options->{iv};
405 38 100       91 my $random_iv = 1 unless defined $iv;
406              
407 38   66     167 my $literal_key = $options->{literal_key} || (exists $options->{regenerate_key} && !$options->{regenerate_key});
408 38 100       102 undef $pass if $literal_key;
409              
410 38         133 return ($pass,$iv,$salt,$key,$random_salt,$random_iv);
411             }
412              
413             sub _get_key_derivation_options {
414 38     38   63 my $self = shift;
415 38         67 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 38   66     136 my $pbkdf = $options->{pbkdf} || ($options->{literal_key} ? 'none'
423             :$header_mode eq 'randomiv' ? 'randomiv'
424             :DEFAULT_PBKDF);
425             # iterations
426 38   100     143 my $iter = $options->{iter} || DEFAULT_ITER;
427 38 50 33     350 $iter =~ /[\d_]+/ && $iter >= 1 or croak "-iterations argument must be greater than or equal to 1";
428 38 50 33     190 $iter =~ /[\d_]+/ && $iter >= 1 or croak "-iterations argument must be greater than or equal to 1";
429              
430             # hasher
431 38         104 my $hc = $options->{hasher};
432 38         62 my $nodeprecate = $options->{nodeprecate};
433            
434 38         136 return ($pbkdf,$iter,$hc,$nodeprecate);
435             }
436              
437             sub _get_chain_mode {
438 38     38   74 my $self = shift;
439 38         70 my $options = shift;
440             return $options->{chain_mode} ? $options->{chain_mode}
441 38 50       129 :$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 1760     1760   2102 my $self = shift;
455 1760 100       2998 return if $self->nodeprecate;
456 1748 100       3793 return if $self->{decrypt};
457 874         1730 my $pbkdf = $self->pbkdf;
458 874 50       3073 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 5280     5280   7423 shift->chain_mode =~ /^p?cbc$/;
469             }
470              
471             sub _cbc_encrypt {
472 1432     1432   1688 my $self = shift;
473 1432         2138 my ($crypt,$iv,$result,$blocks) = @_;
474             # the copying looks silly, but it is slightly faster than dereferencing the
475             # variables each time
476 1432         2292 my ($i,$r) = ($$iv,$$result);
477 1432         2418 foreach (@$blocks) {
478 3157         13211 $r .= $i = $crypt->encrypt($i ^ $_);
479             }
480 1432         3603 ($$iv,$$result) = ($i,$r);
481             }
482              
483             sub _cbc_decrypt {
484 1644     1644   1748 my $self = shift;
485 1644         2519 my ($crypt,$iv,$result,$blocks) = @_;
486             # the copying looks silly, but it is slightly faster than dereferencing the
487             # variables each time
488 1644         2571 my ($i,$r) = ($$iv,$$result);
489 1644         2631 foreach (@$blocks) {
490 3157         9900 $r .= $i ^ $crypt->decrypt($_);
491 3157         5217 $i = $_;
492             }
493 1644         3648 ($$iv,$$result) = ($i,$r);
494             }
495              
496             sub _pcbc_encrypt {
497 42     42   67 my $self = shift;
498 42         95 my ($crypt,$iv,$result,$blocks) = @_;
499 42         97 foreach my $plaintext (@$blocks) {
500 82         559 $$result .= $$iv = $crypt->encrypt($$iv ^ $plaintext);
501 82         198 $$iv ^= $plaintext;
502             }
503             }
504              
505             sub _pcbc_decrypt {
506 58     58   98 my $self = shift;
507 58         114 my ($crypt,$iv,$result,$blocks) = @_;
508 58         139 foreach my $ciphertext (@$blocks) {
509 82         490 $$result .= $$iv = $$iv ^ $crypt->decrypt($ciphertext);
510 82         156 $$iv ^= $ciphertext;
511             }
512             }
513              
514             sub _cfb_encrypt {
515 0     0   0 my $self = shift;
516 0         0 my ($crypt,$iv,$result,$blocks) = @_;
517 0         0 my ($i,$r) = ($$iv,$$result);
518 0         0 foreach my $plaintext (@$blocks) {
519 0         0 $r .= $i = $plaintext ^ $crypt->encrypt($i)
520             }
521 0         0 ($$iv,$$result) = ($i,$r);
522             }
523              
524             sub _cfb_decrypt {
525 0     0   0 my $self = shift;
526 0         0 my ($crypt,$iv,$result,$blocks) = @_;
527 0         0 my ($i,$r) = ($$iv,$$result);
528 0         0 foreach my $ciphertext (@$blocks) {
529 0         0 $r .= $ciphertext ^ $crypt->encrypt($i);
530 0         0 $i = $ciphertext;
531             }
532 0         0 ($$iv,$$result) = ($i,$r);
533             }
534              
535             sub _ofb_encrypt {
536 84     84   94 my $self = shift;
537 84         118 my ($crypt,$iv,$result,$blocks) = @_;
538 84         134 my ($i,$r) = ($$iv,$$result);
539 84         129 foreach my $plaintext (@$blocks) {
540 167         487 my $ciphertext = $plaintext ^ ($i = $crypt->encrypt($i));
541 167         236 substr($ciphertext,length $plaintext) = ''; # truncate
542 167         264 $r .= $ciphertext;
543             }
544 84         183 ($$iv,$$result) = ($i,$r);
545             }
546              
547             *_ofb_decrypt = \&_ofb_encrypt; # same code
548              
549             # According to RFC3686, the counter is 128 bits (16 bytes)
550             # The first 32 bits (4 bytes) is the nonce
551             # The next 64 bits (8 bytes) is the IV
552             # The final 32 bits (4 bytes) is the counter, starting at 1
553             # BUT, the way that openssl v1.1.1 does it is to generate a random
554             # IV, treat the whole thing as a blocksize-sized integer, and then
555             # increment.
556             sub _ctr_encrypt {
557 0     0   0 my $self = shift;
558 0         0 my ($crypt,$iv,$result,$blocks) = @_;
559 0         0 my $bs = $self->blocksize;
560            
561 0         0 $self->_upgrade_iv_to_ctr($iv);
562 0         0 my ($i,$r) = ($$iv,$$result);
563              
564 0         0 foreach my $plaintext (@$blocks) {
565 0         0 my $bytes = int128_to_net($i++);
566              
567             # pad with leading nulls if there are insufficient bytes
568             # (there's gotta be a better way to do this)
569 0 0       0 if ($bs > length $bytes) {
570 0         0 substr($bytes,0,0) = "\000"x($bs-length $bytes) ;
571             }
572              
573 0         0 my $ciphertext = $plaintext ^ ($crypt->encrypt($bytes));
574 0         0 substr($ciphertext,length $plaintext) = ''; # truncate
575 0         0 $r .= $ciphertext;
576             }
577 0         0 ($$iv,$$result) = ($i,$r);
578             }
579              
580             *_ctr_decrypt = \&_ctr_encrypt; # same code
581              
582             # upgrades instance vector to a CTR counter
583             # returns 1 if upgrade performed
584             sub _upgrade_iv_to_ctr {
585 0     0   0 my $self = shift;
586 0         0 my $iv = shift; # this is a scalar reference
587 0 0       0 return if ref $$iv; # already upgraded to an object
588              
589 0 0       0 $self->_load_module("Math::Int128" => "'net_to_int128','int128_to_net'")
590             or croak "Optional Math::Int128 module must be installed to use the CTR chaining method";
591              
592 0         0 $$iv = net_to_int128($$iv);
593 0         0 return 1;
594             }
595              
596             ######################################### chaining mode methods ################################3
597              
598 2643     2643 1 4152 sub pbkdf { shift->{pbkdf} }
599              
600             # get the initialized PBKDF object
601             sub pbkdf_obj {
602 1762     1762 0 2269 my $self = shift;
603 1762         3097 my $pbkdf = $self->pbkdf;
604 1762         2856 my $iter = $self->{iter};
605 1762         2196 my $hc = $self->{hasher};
606 1762 100       3276 my @hash_args = $hc ? ref ($hc) ? (hasher => $hc) : (hash_class => $hc)
    100          
607             : ();
608             return Crypt::CBC::PBKDF->new($pbkdf =>
609             {
610             key_len => $self->{keysize},
611             iv_len => $self->{blocksize},
612 1762         10067 iterations => $iter,
613             @hash_args,
614             }
615             );
616             }
617              
618             ############################# generating key, iv and salt ########################
619             # hopefully a replacement for mess below
620             sub set_key_and_iv {
621 887     887 0 1283 my $self = shift;
622              
623 887 100       1933 if (!$self->{literal_key}) {
624 885         1840 my ($key,$iv) = $self->pbkdf_obj->key_and_iv($self->{salt},$self->{passphrase});
625 885         5689 $self->{key} = $key;
626 885 100       2756 $self->{iv} = $iv if $self->{make_random_iv};
627             } else {
628 2 50       6 $self->{iv} = $self->_get_random_bytes($self->blocksize) if $self->{make_random_iv};
629             }
630              
631 887 50       1847 length $self->{salt} == 8 or croak "Salt must be exactly 8 bytes long";
632 887 50       2245 length $self->{iv} == $self->{blocksize} or croak "IV must be exactly $self->{blocksize} bytes long";
633             }
634              
635             # derive the salt, iv and key from the datastream header + passphrase
636             sub _read_key_and_iv {
637 880     880   979 my $self = shift;
638 880         1078 my $input_stream = shift;
639 880         1763 my $bs = $self->blocksize;
640              
641             # use our header mode to figure out what to do with the data stream
642 880         1455 my $header_mode = $self->header_mode;
643              
644 880 100       2186 if ($header_mode eq 'none') {
    100          
    50          
645 4   66     16 $self->{salt} ||= $self->_get_random_bytes(8);
646 4         11 return $self->set_key_and_iv;
647             }
648              
649             elsif ($header_mode eq 'salt') {
650 875         3842 ($self->{salt}) = $$input_stream =~ /^Salted__(.{8})/s;
651 875 50       2129 croak "Ciphertext does not begin with a valid header for 'salt' header mode" unless defined $self->{salt};
652 875         2083 substr($$input_stream,0,16) = '';
653 875         1732 ($self->{key},$self->{iv}) = $self->pbkdf_obj->key_and_iv($self->{salt},$self->{passphrase});
654             }
655              
656             elsif ($header_mode eq 'randomiv') {
657 1         9 ($self->{iv}) = $$input_stream =~ /^RandomIV(.{8})/s;
658 1 50       4 croak "Ciphertext does not begin with a valid header for 'randomiv' header mode" unless defined $self->{iv};
659 1 50       3 croak "randomiv header mode cannot be used securely when decrypting with a >8 byte block cipher.\n"
660             unless $self->blocksize == 8;
661 1         3 (undef,$self->{key}) = $self->pbkdf_obj->key_and_iv(undef,$self->{passphrase});
662 1         14 substr($$input_stream,0,16) = ''; # truncate
663             }
664              
665             else {
666 0         0 croak "Invalid header mode '$header_mode'";
667             }
668             }
669              
670             # this subroutine will generate the actual {en,de}cryption key, the iv
671             # and the block cipher object. This is called when reading from a datastream
672             # and so it uses previous values of salt or iv if they are encoded in datastream
673             # header
674             sub _generate_iv_and_cipher_from_datastream {
675 880     880   1069 my $self = shift;
676 880         935 my $input_stream = shift;
677              
678 880         1799 $self->_read_key_and_iv($input_stream);
679 880         5514 $self->{civ} = $self->{iv};
680            
681             # we should have the key and iv now, or we are dead in the water
682             croak "Could not derive key or iv from cipher stream, and you did not specify these values in new()"
683 880 50 33     3723 unless $self->{key} && $self->{civ};
684              
685             # now we can generate the crypt object itself
686             $self->{crypt} = ref $self->{cipher} ? $self->{cipher}
687             : $self->{cipher}->new($self->{key})
688 880 100       10492 or croak "Could not create $self->{cipher} object: $@";
    50          
689 880         2034 return '';
690             }
691              
692             sub _generate_iv_and_cipher_from_options {
693 880     880   1131 my $self = shift;
694              
695 880 50       2497 $self->{salt} = $self->_get_random_bytes(8) if $self->{make_random_salt};
696 880         2775 $self->set_key_and_iv;
697 880         1621 $self->{civ} = $self->{iv};
698              
699 880         1119 my $result = '';
700 880         2099 my $header_mode = $self->header_mode;
701            
702 880 100       1946 if ($header_mode eq 'salt') {
    100          
703 876         1813 $result = "Salted__$self->{salt}";
704             }
705              
706             elsif ($header_mode eq 'randomiv') {
707 2         7 $result = "RandomIV$self->{iv}";
708 2         5 undef $self->{salt}; # shouldn't be there!
709             }
710              
711 880 50 33     3307 croak "key and/or iv are missing" unless defined $self->{key} && defined $self->{civ};
712              
713 880         2235 $self->_taintcheck($self->{key});
714             $self->{crypt} = ref $self->{cipher} ? $self->{cipher}
715             : $self->{cipher}->new($self->{key})
716 880 100       10583 or croak "Could not create $self->{cipher} object: $@";
    50          
717 880         2303 return $result;
718             }
719              
720             sub _taintcheck {
721 880     880   1151 my $self = shift;
722 880         1144 my $key = shift;
723 880 50       3095 return unless ${^TAINT};
724              
725 0         0 my $has_scalar_util = eval "require Scalar::Util; 1";
726 0         0 my $tainted;
727              
728              
729 0 0       0 if ($has_scalar_util) {
730 0         0 $tainted = Scalar::Util::tainted($key);
731             } else {
732 0         0 local($@, $SIG{__DIE__}, $SIG{__WARN__});
733 0         0 local $^W = 0;
734 0         0 eval { kill 0 * $key };
  0         0  
735 0         0 $tainted = $@ =~ /^Insecure/;
736             }
737              
738 0 0       0 croak "Taint checks are turned on and your key is tainted. Please untaint the key and try again"
739             if $tainted;
740             }
741              
742             sub _digest_obj {
743 0     0   0 my $self = shift;
744              
745 0 0       0 if ($self->{digest_obj}) {
746 0         0 $self->{digest_obj}->reset();
747 0         0 return $self->{digest_obj};
748             }
749              
750 0         0 my $alg = $self->{digest_alg};
751 0 0 0     0 return $alg if ref $alg && $alg->can('digest');
752 0         0 my $obj = eval {Digest->new($alg)};
  0         0  
753 0 0       0 croak "Unable to instantiate '$alg' digest object: $@" if $@;
754              
755 0         0 return $self->{digest_obj} = $obj;
756             }
757              
758             sub random_bytes {
759 2     2 1 5 my $self = shift;
760 2 50       22 my $bytes = shift or croak "usage: random_bytes(\$byte_length)";
761 2         8 $self->_get_random_bytes($bytes);
762             }
763              
764             sub _get_random_bytes {
765 887     887   1131 my $self = shift;
766 887         976 my $length = shift;
767 887         1390 my $result;
768              
769 887 50 33     46387 if (-r RANDOM_DEVICE && open(F,RANDOM_DEVICE)) {
770 887         591411 read(F,$result,$length);
771 887         13900 close F;
772             } else {
773 0         0 $result = pack("C*",map {rand(256)} 1..$length);
  0         0  
774             }
775             # Clear taint and check length
776 887         5262 $result =~ /^(.+)$/s;
777 887 50       3506 length($1) == $length or croak "Invalid length while gathering $length random bytes";
778 887         3797 return $1;
779             }
780              
781             sub _standard_padding ($$$) {
782 566     566   1428 my ($b,$bs,$decrypt) = @_;
783              
784 566 100       1204 if ($decrypt eq 'd') {
785 283         708 my $pad_length = unpack("C",substr($b,-1));
786 283         986 return substr($b,0,$bs-$pad_length);
787             }
788 283         487 my $pad = $bs - length($b);
789 283         1669 return $b . pack("C*",($pad)x$pad);
790             }
791              
792             sub _space_padding ($$$) {
793 378     378   1031 my ($b,$bs,$decrypt) = @_;
794              
795 378 100       661 if ($decrypt eq 'd') {
796 189         910 $b=~ s/ *\z//s;
797             } else {
798 189         762 $b .= pack("C*", (32) x ($bs-length($b)));
799             }
800 378         727 return $b;
801             }
802              
803             sub _no_padding ($$$) {
804 0     0   0 my ($b,$bs,$decrypt) = @_;
805 0         0 return $b;
806             }
807              
808             sub _null_padding ($$$) {
809 378     378   728 my ($b,$bs,$decrypt) = @_;
810 378 100       619 return unless length $b;
811 365 50       569 $b = length $b ? $b : '';
812 365 100       646 if ($decrypt eq 'd') {
813 189         920 $b=~ s/\0*\z//s;
814 189         595 return $b;
815             }
816 176         938 return $b . pack("C*", (0) x ($bs - length($b) % $bs));
817             }
818              
819             sub _oneandzeroes_padding ($$$) {
820 380     380   765 my ($b,$bs,$decrypt) = @_;
821 380 100       712 if ($decrypt eq 'd') {
822 190         889 $b=~ s/\x80\0*\z//s;
823 190         512 return $b;
824             }
825 190         872 return $b . pack("C*", 128, (0) x ($bs - length($b) - 1) );
826             }
827              
828             sub _rijndael_compat ($$$) {
829 0     0   0 my ($b,$bs,$decrypt) = @_;
830              
831 0 0       0 return unless length $b;
832 0 0       0 if ($decrypt eq 'd') {
833 0         0 $b=~ s/\x80\0*\z//s;
834 0         0 return $b;
835             }
836 0         0 return $b . pack("C*", 128, (0) x ($bs - length($b) % $bs - 1) );
837             }
838              
839             sub get_initialization_vector (\$) {
840 0     0 1 0 my $self = shift;
841 0         0 $self->iv();
842             }
843              
844             sub set_initialization_vector (\$$) {
845 0     0 1 0 my $self = shift;
846 0         0 my $iv = shift;
847 0         0 my $bs = $self->blocksize;
848 0 0       0 croak "Initialization vector must be $bs bytes in length" unless length($iv) == $bs;
849 0         0 $self->iv($iv);
850             }
851              
852             sub salt {
853 11     11 1 26 my $self = shift;
854 11         18 my $d = $self->{salt};
855 11 50       22 $self->{salt} = shift if @_;
856 11         65 $d;
857             }
858              
859             sub iv {
860 15     15 1 125 my $self = shift;
861 15         23 my $d = $self->{iv};
862 15 50       34 $self->{iv} = shift if @_;
863 15         68 $d;
864             }
865              
866             sub key {
867 15     15 1 36 my $self = shift;
868 15         30 my $d = $self->{key};
869 15 50       31 $self->{key} = shift if @_;
870 15         65 $d;
871             }
872              
873             sub passphrase {
874 4     4 1 9 my $self = shift;
875 4         7 my $d = $self->{passphrase};
876 4 100       10 if (@_) {
877 1         3 undef $self->{key};
878 1         2 undef $self->{iv};
879 1         2 $self->{passphrase} = shift;
880             }
881 4         13 $d;
882             }
883              
884             sub keysize {
885 0     0 1 0 my $self = shift;
886 0 0       0 $self->{keysize} = shift if @_;
887 0         0 $self->{keysize};
888             }
889              
890 0     0 1 0 sub cipher { shift->{cipher} }
891 0     0 1 0 sub padding { shift->{padding} }
892 881     881 1 1542 sub blocksize { shift->{blocksize} }
893 0     0 0 0 sub pcbc { shift->{pcbc} }
894 1764     1764 0 2761 sub header_mode {shift->{header_mode} }
895 1     1 0 25 sub literal_key {shift->{literal_key}}
896 1760     1760 0 3828 sub nodeprecate {shift->{nodeprecate}}
897            
898             1;
899             __END__