File Coverage

lib/Crypt/CBC.pm
Criterion Covered Total %
statement 346 437 79.1
branch 162 244 66.3
condition 76 121 62.8
subroutine 56 70 80.0
pod 22 29 75.8
total 662 901 73.4


line stmt bran cond sub pod time code
1             package Crypt::CBC;
2              
3 11     11   2525869 use strict;
  11         24  
  11         505  
4 11     11   57 use Carp 'croak','carp';
  11         16  
  11         735  
5 11     11   5518 use Crypt::CBC::PBKDF;
  11         30  
  11         357  
6 11     11   6033 use Crypt::URandom ();
  11         52782  
  11         319  
7 11     11   407 use bytes;
  11         355  
  11         102  
8 11     11   399 no warnings 'uninitialized';
  11         19  
  11         690  
9             our $VERSION = '3.07';
10              
11 11     11   58 use constant DEFAULT_PBKDF => 'opensslv1';
  11         19  
  11         636  
12 11     11   49 use constant DEFAULT_ITER => 10_000; # same as OpenSSL default
  11         14  
  11         82920  
13              
14             my @valid_options = qw(
15             pass
16             key
17             cipher
18             keysize
19             chain_mode
20             pbkdf
21             nodeprecate
22             iter
23             hasher
24             header
25             iv
26             salt
27             padding
28             literal_key
29             pcbc
30             add_header
31             generate_key
32             prepend_iv
33             );
34              
35             sub new {
36 53     53 1 345888 my $class = shift;
37              
38             # the _get_*() methods move a lot of the ugliness/legacy logic
39             # out of new(). But the ugliness is still there!
40 53         189 my $options = $class->_get_options(@_);
41 53 100       162 eval {$class->_validate_options($options)} or croak $@;
  53         176  
42            
43 52         159 my $cipher = $class->_get_cipher_obj($options);
44 52         173 my $header_mode = $class->_get_header_mode($options);
45 51         164 my ($ks,$bs) = $class->_get_key_and_block_sizes($cipher,$options);
46 51         226 my ($pass,$iv,$salt,$key,
47             $random_salt,$random_iv) = $class->_get_key_materials($options);
48 49         172 my $padding = $class->_get_padding_mode($bs,$options);
49 49         157 my ($pbkdf,$iter,
50             $hc,$nodeprecate) = $class->_get_key_derivation_options($options,$header_mode);
51 49         184 my $chain_mode = $class->_get_chain_mode($options);
52              
53             ### CONSISTENCY CHECKS ####
54              
55             # set literal key flag if a key was passed in or the key derivation algorithm is none
56 49 100 66     192 $key ||= $pass if $pbkdf eq 'none'; # just in case
57 49         121 my $literal_key = defined $key;
58              
59             # check length of initialization vector
60 49 100 100     568 croak "Initialization vector must be exactly $bs bytes long when using the $cipher cipher"
61             if defined $iv and length($iv) != $bs;
62              
63             # chaining mode check
64 47 50       381 croak "invalid cipher block chain mode: $chain_mode"
65             unless $class->can("_${chain_mode}_encrypt");
66              
67             # KEYSIZE consistency
68 47 100 100     252 if (defined $key && length($key) != $ks) {
69 2         309 croak "If specified by -literal_key, then the key length must be equal to the chosen cipher's key length of $ks bytes";
70             }
71              
72             # HEADER consistency
73 45 100       175 if ($header_mode eq 'salt') {
    100          
74 34 50       102 croak "Cannot use -header mode of 'salt' if a literal key is specified or key derivation function is none"
75             if $literal_key;
76             }
77             elsif ($header_mode eq 'randomiv') {
78 4 100       184 croak "Cannot use -header mode of 'randomiv' in conjunction with a cipher whose blocksize greater than 8"
79             unless $bs == 8
80             }
81              
82 44 50 33     162 croak "If a key derivation function (-pbkdf) of 'none' is provided, a literal key and iv must be provided"
      66        
83             if $pbkdf eq 'none' && (!defined $key || !defined $iv);
84              
85 44 100 100     363 croak "If a -header mode of 'randomiv' is provided, then the -pbkdf key derivation function must be 'randomiv' or undefined"
86             if $header_mode eq 'randomiv' and $pbkdf ne 'randomiv';
87              
88 43         919 return bless {
89             'cipher' => $cipher,
90             'passphrase' => $pass,
91             'key' => $key,
92             'iv' => $iv,
93             'salt' => $salt,
94             'padding' => $padding,
95             'blocksize' => $bs,
96             'keysize' => $ks,
97             'header_mode' => $header_mode,
98             'literal_key' => $literal_key,
99             'literal_iv' => defined $iv,
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 1667     1667 1 13946 my ($self,$data) = @_;
125 1667         3856 $self->start('encrypting');
126 1667         13471 my $result = $self->crypt($data);
127 1667         4163 $result .= $self->finish;
128 1667         8862 $result;
129             }
130              
131             sub decrypt (\$$){
132 1666     1666 1 3072 my ($self,$data) = @_;
133 1666         4010 $self->start('decrypting');
134 1666         3638 my $result = $self->crypt($data);
135 1666         3981 $result .= $self->finish;
136 1666         20419 $result;
137             }
138              
139             sub encrypt_hex (\$$) {
140 1025     1025 1 23239 my ($self,$data) = @_;
141 1025         2061 return join('',unpack 'H*',$self->encrypt($data));
142             }
143              
144             sub decrypt_hex (\$$) {
145 1025     1025 1 3833 my ($self,$data) = @_;
146 1025         5139 return $self->decrypt(pack 'H*',$data);
147             }
148              
149             # call to start a series of encryption/decryption operations
150             sub start (\$$) {
151 3333     3333 1 4489 my $self = shift;
152 3333         4262 my $operation = shift;
153 3333 50       10026 croak "Specify <e>ncryption or <d>ecryption" unless $operation=~/^[ed]/i;
154              
155 3333         4951 delete $self->{'civ'};
156 3333         6107 $self->{'buffer'} = '';
157 3333         7171 $self->{'decrypt'} = $operation=~/^d/i;
158 3333         7105 $self->_deprecation_warning;
159             }
160              
161 10098 50   10098 1 51586 sub chain_mode { shift->{chain_mode} || 'cbc' }
162              
163             sub chaining_method {
164 6314     6314 0 7514 my $self = shift;
165 6314         8499 my $decrypt = shift;
166              
167             # memoize this result
168             return $self->{chaining_method}{$decrypt}
169 6314 100       18489 if exists $self->{chaining_method}{$decrypt};
170            
171 59         134 my $cm = $self->chain_mode;
172 59 100       349 my $code = $self->can($decrypt ? "_${cm}_decrypt" : "_${cm}_encrypt");
173 59 50       157 croak "Chain mode $cm not supported" unless $code;
174 59         213 return $self->{chaining_method}{$decrypt} = $code;
175             }
176              
177             # call to encrypt/decrypt a bit of data
178             sub crypt (\$$){
179 3333     3333 1 4167 my $self = shift;
180 3333         4836 my $data = shift;
181              
182 3333         4204 my $result;
183              
184             croak "crypt() called without a preceding start()"
185 3333 50       7038 unless exists $self->{'buffer'};
186              
187 3333         4746 my $d = $self->{'decrypt'};
188              
189 3333 50       6910 unless ($self->{civ}) { # block cipher has not yet been initialized
190 3333 100       7749 $result = $self->_generate_iv_and_cipher_from_datastream(\$data) if $d;
191 3333 100       9111 $result = $self->_generate_iv_and_cipher_from_options() unless $d;
192             }
193              
194 3333         5930 my $iv = $self->{'civ'};
195 3333         9314 $self->{'buffer'} .= $data;
196              
197 3333         5219 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 3333 50 66     7948 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 3333 50 66     6653 and $self->{'padding'} eq \&_rijndael_compat
      33        
207             and length($data) % $bs;
208              
209 3333 100       10185 return $result unless (length($self->{'buffer'}) >= $bs);
210              
211 2981         17323 my @blocks = unpack("(a$bs)*",$self->{buffer});
212 2981         5388 $self->{buffer} = '';
213            
214             # if decrypting, leave the last block in the buffer for padding
215 2981 100       5440 if ($d) {
216 1650         3109 $self->{buffer} = pop @blocks;
217             } else {
218 1331 100       3751 $self->{buffer} = pop @blocks if length $blocks[-1] < $bs;
219             }
220              
221 2981         6388 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 2981         9418 $code->($self,$self->{crypt},\$iv,\$result,\@blocks);
225              
226 2981         6342 $self->{'civ'} = $iv; # remember the iv
227 2981         9135 return $result;
228             }
229              
230             # this is called at the end to flush whatever's left
231             sub finish (\$) {
232 3333     3333 1 4397 my $self = shift;
233 3333         5070 my $bs = $self->{'blocksize'};
234              
235 3333         5097 my $block = $self->{buffer}; # what's left
236              
237             # Special case hack for backward compatibility with Crypt::Rijndael's CBC_MODE.
238 3333 50 66     8841 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 3333   50     6905 $self->{civ} ||= '';
245 3333         5226 my $iv = $self->{civ};
246 3333         7014 my $code = $self->chaining_method($self->{decrypt});
247            
248 3333         5594 my $result = '';
249 3333 100       6005 if ($self->{decrypt}) {
250 1666         5387 $self->$code($self->{crypt},\$iv,\$result,[$block]);
251 1666 100       4053 $result = $self->{padding}->($result,$bs,'d') if $self->_needs_padding;
252             } else {
253 1667 100       2842 $block = $self->{padding}->($block,$bs,'e') if $self->_needs_padding;
254 1667 100 100     7844 $self->$code($self->{crypt},\$iv,\$result,[$block]) unless length $block==0 && !$self->_needs_padding
255             }
256            
257 3333         7826 delete $self->{'civ'};
258 3333         5486 delete $self->{'buffer'};
259 3333         7634 return $result;
260             }
261              
262             ############# Move the boring new() argument processing here #######
263             sub _get_options {
264 53     53   159 my $class = shift;
265            
266 53         118 my $options = {};
267            
268             # hashref arguments
269 53 100       344 if (ref $_[0] eq 'HASH') {
    50          
270 2         13 $options = shift;
271             }
272              
273             # CGI style arguments
274             elsif ($_[0] =~ /^-[a-zA-Z_]{1,20}$/) {
275 51         303 my %tmp = @_;
276 51         268 while ( my($key,$value) = each %tmp) {
277 213         410 $key =~ s/^-//;
278 213         2424 $options->{lc $key} = $value;
279             }
280             }
281              
282             else {
283 0         0 $options->{key} = shift;
284 0         0 $options->{cipher} = shift;
285             }
286 53         118 return $options;
287             }
288              
289             sub _get_cipher_obj {
290 52     52   117 my $class = shift;
291 52         79 my $options = shift;
292              
293 52         97 my $cipher = $options->{cipher};
294 52 50       125 $cipher = 'Crypt::Cipher::AES' unless $cipher;
295              
296 52 100       130 unless (ref $cipher) { # munge the class name if no object passed
297 50 100       162 $cipher = $cipher=~/^Crypt::/ ? $cipher : "Crypt::$cipher";
298 50 50 33     651 $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 50 50       238 $cipher =~ s/^Crypt::// unless $cipher->can('keysize');
301             }
302              
303 52         118 return $cipher;
304             }
305              
306             sub _validate_options {
307 53     53   87 my $self = shift;
308 53         80 my $options = shift;
309 53         119 my %valid_options = map {$_=>1} @valid_options;
  954         1937  
310 53         266 for my $o (keys %$options) {
311 224 100       704 die "'$o' is not a recognized argument" unless $valid_options{$o};
312             }
313 52         287 return 1;
314             }
315              
316             sub _get_header_mode {
317 52     52   95 my $class = shift;
318 52         74 my $options = shift;
319              
320             # header mode checking
321 52         95 my %valid_modes = map {$_=>1} qw(none salt randomiv);
  156         382  
322 52         115 my $header_mode = $options->{header};
323 52 50 0     159 $header_mode ||= 'none' if exists $options->{prepend_iv} && !$options->{prepend_iv};
      33        
324 52 50 0     142 $header_mode ||= 'none' if exists $options->{add_header} && !$options->{add_header};
      33        
325 52 100 100     372 $header_mode ||= 'none' if $options->{literal_key} || (exists $options->{pbkdf} && $options->{pbkdf} eq 'none');
      100        
      100        
326 52   100     190 $header_mode ||= 'salt'; # default
327 52 100       273 croak "Invalid -header mode '$header_mode'" unless $valid_modes{$header_mode};
328              
329 51         175 return $header_mode;
330             }
331              
332             sub _get_padding_mode {
333 49     49   81 my $class = shift;
334 49         97 my ($bs,$options) = @_;
335              
336 49   100     141 my $padding = $options->{padding} || 'standard';
337              
338 49 50 33     217 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 49 50       346 $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 49         118 return $padding;
355             }
356              
357             sub _get_key_and_block_sizes {
358 51     51   84 my $class = shift;
359 51         75 my $cipher = shift;
360 51         77 my $options = shift;
361            
362             # allow user to override the keysize value
363 51 50 66     1500 my $ks = $options->{keysize} || eval {$cipher->keysize} || eval {$cipher->max_keysize}
364             or croak "Cannot derive keysize from $cipher";
365              
366 51 50       679 my $bs = eval {$cipher->blocksize}
  51         166  
367             or croak "$cipher did not provide a blocksize";
368              
369 51         311 return ($ks,$bs);
370             }
371              
372             sub _get_key_materials {
373 51     51   100 my $self = shift;
374 51         69 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 51   100     237 my $pass = $options->{pass} || $options->{key};
379              
380 51   66     267 my $cipher_object_provided = $options->{cipher} && ref $options->{cipher};
381 51 100       132 if ($cipher_object_provided) {
382 2 50       17 carp "Both a key and a pre-initialized Crypt::* object were passed. The key will be ignored"
383             if defined $pass;
384 2   50     11 $pass ||= '';
385             }
386              
387 51 100       223 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 50 50 66     137 if exists $options->{literal_key} && exists $options->{regenerate_key};
394              
395 50 100       142 my $key = $pass if $options->{literal_key};
396 50 50 33     153 $key = $pass if exists $options->{regenerate_key} && !$options->{regenerate_key};
397              
398             # Get the salt.
399 50         90 my $salt = $options->{salt};
400 50 100 100     166 my $random_salt = 1 unless defined $salt && $salt ne '1';
401 50 100 100     274 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 49         86 my $iv = $options->{iv};
405 49 100       116 my $random_iv = 1 unless defined $iv;
406              
407 49   66     226 my $literal_key = $options->{literal_key} || (exists $options->{regenerate_key} && !$options->{regenerate_key});
408 49 100       113 undef $pass if $literal_key;
409              
410 49         195 return ($pass,$iv,$salt,$key,$random_salt,$random_iv);
411             }
412              
413             sub _get_key_derivation_options {
414 49     49   145 my $self = shift;
415 49         95 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 49   66     180 my $pbkdf = $options->{pbkdf} || ($options->{literal_key} ? 'none'
423             :$header_mode eq 'randomiv' ? 'randomiv'
424             :DEFAULT_PBKDF);
425             # iterations
426 49   100     178 my $iter = $options->{iter} || DEFAULT_ITER;
427 49 50 33     391 $iter =~ /[\d_]+/ && $iter >= 1 or croak "-iterations argument must be greater than or equal to 1";
428 49 50 33     265 $iter =~ /[\d_]+/ && $iter >= 1 or croak "-iterations argument must be greater than or equal to 1";
429              
430             # hasher
431 49         84 my $hc = $options->{hasher};
432 49         80 my $nodeprecate = $options->{nodeprecate};
433            
434 49         194 return ($pbkdf,$iter,$hc,$nodeprecate);
435             }
436              
437             sub _get_chain_mode {
438 49     49   84 my $self = shift;
439 49         89 my $options = shift;
440             return $options->{chain_mode} ? $options->{chain_mode}
441 49 50       181 :$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 3333     3333   4416 my $self = shift;
455 3333 100       6417 return if $self->nodeprecate;
456 3260 100       7898 return if $self->{decrypt};
457 1630         3526 my $pbkdf = $self->pbkdf;
458 1630 50       6192 carp <<END if $pbkdf =~ /^(opensslv1|randomiv)$/;
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 10039     10039   12584 my $self = shift;
469 10039 100       16862 $self->chain_mode =~ /^p?cbc$/ && $self->padding ne \&_no_padding;
470             }
471              
472             sub _cbc_encrypt {
473 2913     2913   4032 my $self = shift;
474 2913         5427 my ($crypt,$iv,$result,$blocks) = @_;
475             # the copying looks silly, but it is slightly faster than dereferencing the
476             # variables each time
477 2913         5670 my ($i,$r) = ($$iv,$$result);
478 2913         5661 foreach (@$blocks) {
479 8716         59534 $r .= $i = $crypt->encrypt($i ^ $_);
480             }
481 2913         19098 ($$iv,$$result) = ($i,$r);
482             }
483              
484             sub _cbc_decrypt {
485 3216     3216   3770 my $self = shift;
486 3216         5793 my ($crypt,$iv,$result,$blocks) = @_;
487             # the copying looks silly, but it is slightly faster than dereferencing the
488             # variables each time
489 3216         6422 my ($i,$r) = ($$iv,$$result);
490 3216         5906 foreach (@$blocks) {
491 8715         20717 $r .= $i ^ $crypt->decrypt($_);
492 8715         54780 $i = $_;
493             }
494 3216         7532 ($$iv,$$result) = ($i,$r);
495             }
496              
497             sub _pcbc_encrypt {
498 42     42   87 my $self = shift;
499 42         116 my ($crypt,$iv,$result,$blocks) = @_;
500 42         105 foreach my $plaintext (@$blocks) {
501 82         482 $$result .= $$iv = $crypt->encrypt($$iv ^ $plaintext);
502 82         192 $$iv ^= $plaintext;
503             }
504             }
505              
506             sub _pcbc_decrypt {
507 58     58   94 my $self = shift;
508 58         132 my ($crypt,$iv,$result,$blocks) = @_;
509 58         125 foreach my $ciphertext (@$blocks) {
510 82         410 $$result .= $$iv = $$iv ^ $crypt->decrypt($ciphertext);
511 82         186 $$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   116 my $self = shift;
538 82         180 my ($crypt,$iv,$result,$blocks) = @_;
539 82         159 my ($i,$r) = ($$iv,$$result);
540 82         173 foreach my $plaintext (@$blocks) {
541 165         546 my $ciphertext = $plaintext ^ ($i = $crypt->encrypt($i));
542 165         257 substr($ciphertext,length $plaintext) = ''; # truncate
543 165         322 $r .= $ciphertext;
544             }
545 82         210 ($$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 6645     6645 1 16069 sub pbkdf { shift->{pbkdf} }
600              
601             # get the initialized PBKDF object
602             sub pbkdf_obj {
603 3334     3334 0 4196 my $self = shift;
604 3334         5782 my $pbkdf = $self->pbkdf;
605 3334         6202 my $iter = $self->{iter};
606 3334         5259 my $hc = $self->{hasher};
607 3334 100       6437 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 3334         23244 iterations => $iter,
614             @hash_args,
615             }
616             );
617             }
618              
619             ############################# generating key, iv and salt ########################
620             sub set_key_and_iv {
621 1674     1674 0 2114 my $self = shift;
622              
623 1674 100 66     2933 if ($self->pbkdf eq 'none' || $self->{literal_key}) {
624 3 50       9 $self->{iv} = $self->_get_random_bytes($self->blocksize) if $self->{make_random_iv};
625             } else {
626 1671         3142 my ($key,$iv) = $self->pbkdf_obj->key_and_iv($self->{salt},$self->{passphrase});
627 1671         13274 $self->{key} = $key;
628 1671 100       7067 $self->{iv} = $iv if $self->{make_random_iv};
629             }
630              
631 1674 50       3976 length $self->{salt} == 8 or croak "Salt must be exactly 8 bytes long";
632 1674 50       8905 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 1666     1666   2130 my $self = shift;
638 1666         2005 my $input_stream = shift;
639 1666         3270 my $bs = $self->blocksize;
640              
641             # use our header mode to figure out what to do with the data stream
642 1666         3248 my $header_mode = $self->header_mode;
643              
644 1666 100       5274 if ($header_mode eq 'none') {
    100          
    50          
645 4   66     13 $self->{salt} ||= $self->_get_random_bytes(8);
646 4         6 return $self->set_key_and_iv;
647             }
648              
649             elsif ($header_mode eq 'salt') {
650 1660         7899 ($self->{salt}) = $$input_stream =~ /^Salted__(.{8})/s;
651 1660 50       3742 croak "Ciphertext does not begin with a valid header for 'salt' header mode" unless defined $self->{salt};
652 1660         3998 substr($$input_stream,0,16) = '';
653 1660         3490 my ($k,$i) = $self->pbkdf_obj->key_and_iv($self->{salt},$self->{passphrase});
654 1660 50       15155 $self->{key} = $k unless $self->{literal_key};
655 1660 50       5826 $self->{iv} = $i unless $self->{literal_iv};
656             }
657              
658             elsif ($header_mode eq 'randomiv') {
659 2         12 ($self->{iv}) = $$input_stream =~ /^RandomIV(.{8})/s;
660 2 50       8 croak "Ciphertext does not begin with a valid header for 'randomiv' header mode" unless defined $self->{iv};
661 2 50       5 croak "randomiv header mode cannot be used securely when decrypting with a >8 byte block cipher.\n"
662             unless $self->blocksize == 8;
663 2         7 ($self->{key},undef) = $self->pbkdf_obj->key_and_iv(undef,$self->{passphrase});
664 2         23 substr($$input_stream,0,16) = ''; # truncate
665             }
666              
667             else {
668 0         0 croak "Invalid header mode '$header_mode'";
669             }
670             }
671              
672             # this subroutine will generate the actual {en,de}cryption key, the iv
673             # and the block cipher object. This is called when reading from a datastream
674             # and so it uses previous values of salt or iv if they are encoded in datastream
675             # header
676             sub _generate_iv_and_cipher_from_datastream {
677 1666     1666   2435 my $self = shift;
678 1666         2190 my $input_stream = shift;
679              
680 1666         3969 $self->_read_key_and_iv($input_stream);
681 1666         3963 $self->{civ} = $self->{iv};
682            
683             # we should have the key and iv now, or we are dead in the water
684             croak "Could not derive key or iv from cipher stream, and you did not specify these values in new()"
685 1666 50 33     6826 unless $self->{key} && $self->{civ};
686              
687             # now we can generate the crypt object itself
688             $self->{crypt} = ref $self->{cipher} ? $self->{cipher}
689             : $self->{cipher}->new($self->{key})
690 1666 100       14875 or croak "Could not create $self->{cipher} object: $@";
    50          
691 1666         78893 return '';
692             }
693              
694             sub _generate_iv_and_cipher_from_options {
695 1667     1667   5178 my $self = shift;
696              
697 1667 50       4733 $self->{salt} = $self->_get_random_bytes(8) if $self->{make_random_salt};
698 1667         4370 $self->set_key_and_iv;
699 1667         4107 $self->{civ} = $self->{iv};
700              
701 1667         2335 my $result = '';
702 1667         4188 my $header_mode = $self->header_mode;
703            
704 1667 100       3863 if ($header_mode eq 'salt') {
    100          
705 1661         3100 $result = "Salted__$self->{salt}";
706             }
707              
708             elsif ($header_mode eq 'randomiv') {
709 3         6 $result = "RandomIV$self->{iv}";
710 3         7 undef $self->{salt}; # shouldn't be there!
711             }
712              
713 1667 50 33     6624 croak "key and/or iv are missing" unless defined $self->{key} && defined $self->{civ};
714              
715 1667         5096 $self->_taintcheck($self->{key});
716             $self->{crypt} = ref $self->{cipher} ? $self->{cipher}
717             : $self->{cipher}->new($self->{key})
718 1667 100       16039 or croak "Could not create $self->{cipher} object: $@";
    50          
719 1667         79327 return $result;
720             }
721              
722             sub _taintcheck {
723 1667     1667   2378 my $self = shift;
724 1667         2481 my $key = shift;
725 1667 50       5906 return unless ${^TAINT};
726              
727 0         0 my $has_scalar_util = eval "require Scalar::Util; 1";
728 0         0 my $tainted;
729              
730              
731 0 0       0 if ($has_scalar_util) {
732 0         0 $tainted = Scalar::Util::tainted($key);
733             } else {
734 0         0 local($@, $SIG{__DIE__}, $SIG{__WARN__});
735 0         0 local $^W = 0;
736 0         0 eval { kill 0 * $key };
  0         0  
737 0         0 $tainted = $@ =~ /^Insecure/;
738             }
739              
740 0 0       0 croak "Taint checks are turned on and your key is tainted. Please untaint the key and try again"
741             if $tainted;
742             }
743              
744             sub _digest_obj {
745 0     0   0 my $self = shift;
746              
747 0 0       0 if ($self->{digest_obj}) {
748 0         0 $self->{digest_obj}->reset();
749 0         0 return $self->{digest_obj};
750             }
751              
752 0         0 my $alg = $self->{digest_alg};
753 0 0 0     0 return $alg if ref $alg && $alg->can('digest');
754 0         0 my $obj = eval {Digest->new($alg)};
  0         0  
755 0 0       0 croak "Unable to instantiate '$alg' digest object: $@" if $@;
756              
757 0         0 return $self->{digest_obj} = $obj;
758             }
759              
760             sub random_bytes {
761 2     2 1 3 my $self = shift;
762 2 50       6 my $bytes = shift or croak "usage: random_bytes(\$byte_length)";
763 2         4 $self->_get_random_bytes($bytes);
764             }
765              
766             sub _get_random_bytes {
767 1676     1676   2325 my $self = shift;
768 1676         2124 my $length = shift;
769 1676         4694 my $result = Crypt::URandom::urandom($length);
770             # Clear taint and check length
771 1676         53340 $result =~ /^(.+)$/s;
772 1676 50       5822 length($1) == $length or croak "Invalid length while gathering $length random bytes";
773 1676         9687 return $1;
774             }
775              
776             sub _standard_padding ($$$) {
777 1004     1004   2986 my ($b,$bs,$decrypt) = @_;
778              
779 1004 100       2176 if ($decrypt eq 'd') {
780 502         1508 my $pad_length = unpack("C",substr($b,-1));
781 502         1693 return substr($b,0,$bs-$pad_length);
782             }
783 502         930 my $pad = $bs - length($b);
784 502         2695 return $b . pack("C*",($pad)x$pad);
785             }
786              
787             sub _space_padding ($$$) {
788 756     756   1674 my ($b,$bs,$decrypt) = @_;
789              
790 756 100       1563 if ($decrypt eq 'd') {
791 378         2199 $b=~ s/ *\z//s;
792             } else {
793 378         1536 $b .= pack("C*", (32) x ($bs-length($b)));
794             }
795 756         1504 return $b;
796             }
797              
798             sub _no_padding ($$$) {
799 0     0   0 my ($b,$bs,$decrypt) = @_;
800 0         0 return $b;
801             }
802              
803             sub _null_padding ($$$) {
804 756     756   1708 my ($b,$bs,$decrypt) = @_;
805 756 100       1537 return unless length $b;
806 719 50       1226 $b = length $b ? $b : '';
807 719 100       5442 if ($decrypt eq 'd') {
808 378         5353 $b=~ s/\0*\z//s;
809 378         986 return $b;
810             }
811 341         1844 return $b . pack("C*", (0) x ($bs - length($b) % $bs));
812             }
813              
814             sub _oneandzeroes_padding ($$$) {
815 758     758   1801 my ($b,$bs,$decrypt) = @_;
816 758 100       1792 if ($decrypt eq 'd') {
817 379         2209 $b=~ s/\x80\0*\z//s;
818 379         1023 return $b;
819             }
820 379         1952 return $b . pack("C*", 128, (0) x ($bs - length($b) - 1) );
821             }
822              
823             sub _rijndael_compat ($$$) {
824 0     0   0 my ($b,$bs,$decrypt) = @_;
825              
826 0 0       0 return unless length $b;
827 0 0       0 if ($decrypt eq 'd') {
828 0         0 $b=~ s/\x80\0*\z//s;
829 0         0 return $b;
830             }
831 0         0 return $b . pack("C*", 128, (0) x ($bs - length($b) % $bs - 1) );
832             }
833              
834             sub get_initialization_vector (\$) {
835 0     0 1 0 my $self = shift;
836 0         0 $self->iv();
837             }
838              
839             sub set_initialization_vector (\$$) {
840 0     0 1 0 my $self = shift;
841 0         0 my $iv = shift;
842 0         0 my $bs = $self->blocksize;
843 0 0       0 croak "Initialization vector must be $bs bytes in length" unless length($iv) == $bs;
844 0         0 $self->iv($iv);
845             }
846              
847             sub salt {
848 11     11 1 18 my $self = shift;
849 11         17 my $d = $self->{salt};
850 11 50       21 $self->{salt} = shift if @_;
851 11         35 $d;
852             }
853              
854             sub iv {
855 15     15 1 109 my $self = shift;
856 15         23 my $d = $self->{iv};
857 15 50       30 $self->{iv} = shift if @_;
858 15         49 $d;
859             }
860              
861             sub key {
862 15     15 1 40 my $self = shift;
863 15         28 my $d = $self->{key};
864 15 50       29 $self->{key} = shift if @_;
865 15         59 $d;
866             }
867              
868             sub passphrase {
869 4     4 1 5 my $self = shift;
870 4         6 my $d = $self->{passphrase};
871 4 100       21 if (@_) {
872 1         2 undef $self->{key};
873 1         2 undef $self->{iv};
874 1         2 $self->{passphrase} = shift;
875             }
876 4         17 $d;
877             }
878              
879             sub keysize {
880 0     0 1 0 my $self = shift;
881 0 0       0 $self->{keysize} = shift if @_;
882 0         0 $self->{keysize};
883             }
884              
885 0     0 1 0 sub cipher { shift->{cipher} }
886 9863     9863 1 67196 sub padding { shift->{padding} }
887 1668     1668 1 2896 sub blocksize { shift->{blocksize} }
888 0     0 0 0 sub pcbc { shift->{pcbc} }
889 3337     3337 0 6189 sub header_mode {shift->{header_mode} }
890 1     1 0 22 sub literal_key {shift->{literal_key}}
891 3333     3333 0 7544 sub nodeprecate {shift->{nodeprecate}}
892            
893             1;
894             __END__
895              
896             =head1 NAME
897              
898             Crypt::CBC - Encrypt Data with Cipher Block Chaining Mode
899              
900             =head1 SYNOPSIS
901              
902             use Crypt::CBC;
903             $cipher = Crypt::CBC->new( -pass => 'my secret password',
904             -cipher => 'Cipher::AES'
905             );
906              
907             # one shot mode
908             $ciphertext = $cipher->encrypt("This data is hush hush");
909             $plaintext = $cipher->decrypt($ciphertext);
910              
911             # stream mode
912             $cipher->start('encrypting');
913             open(F,"./BIG_FILE");
914             while (read(F,$buffer,1024)) {
915             print $cipher->crypt($buffer);
916             }
917             print $cipher->finish;
918              
919             # do-it-yourself mode -- specify key && initialization vector yourself
920             $key = Crypt::CBC->random_bytes(8); # assuming a 8-byte block cipher
921             $iv = Crypt::CBC->random_bytes(8);
922             $cipher = Crypt::CBC->new(-pbkdf => 'none',
923             -header => 'none',
924             -key => $key,
925             -iv => $iv);
926              
927             $ciphertext = $cipher->encrypt("This data is hush hush");
928             $plaintext = $cipher->decrypt($ciphertext);
929              
930             # encrypting via a filehandle (requires Crypt::FileHandle>
931             $fh = Crypt::CBC->filehandle(-pass => 'secret');
932             open $fh,'>','encrypted.txt" or die $!
933             print $fh "This will be encrypted\n";
934             close $fh;
935              
936             =head1 DESCRIPTION
937              
938             This module is a Perl-only implementation of the cryptographic cipher
939             block chaining mode (CBC). In combination with a block cipher such as
940             AES or Blowfish, you can encrypt and decrypt messages of arbitrarily
941             long length. The encrypted messages are compatible with the
942             encryption format used by the B<OpenSSL> package.
943              
944             To use this module, you will first create a Crypt::CBC cipher object
945             with new(). At the time of cipher creation, you specify an encryption
946             key to use and, optionally, a block encryption algorithm. You will
947             then call the start() method to initialize the encryption or
948             decryption process, crypt() to encrypt or decrypt one or more blocks
949             of data, and lastly finish(), to pad and encrypt the final block. For
950             your convenience, you can call the encrypt() and decrypt() methods to
951             operate on a whole data value at once.
952              
953             =head2 new()
954              
955             $cipher = Crypt::CBC->new( -pass => 'my secret key',
956             -cipher => 'Cipher::AES',
957             );
958              
959             # or (for compatibility with versions prior to 2.0)
960             $cipher = new Crypt::CBC('my secret key' => 'Cipher::AES');
961              
962             The new() method creates a new Crypt::CBC object. It accepts a list of
963             -argument => value pairs selected from the following list:
964              
965             Argument Description
966             -------- -----------
967              
968             -pass,-key The encryption/decryption passphrase. These arguments
969             are interchangeable, but -pass is preferred
970             ("key" is a misnomer, as it is not the literal
971             encryption key).
972              
973             -cipher The cipher algorithm (defaults to Crypt::Cipher:AES), or
974             a previously created cipher object reference. For
975             convenience, you may omit the initial "Crypt::" part
976             of the classname and use the basename, e.g. "Blowfish"
977             instead of "Crypt::Blowfish".
978              
979             -keysize Force the cipher keysize to the indicated number of bytes. This can be used
980             to set the keysize for variable keylength ciphers such as AES.
981              
982             -chain_mode The block chaining mode to use. Current options are:
983             'cbc' -- cipher-block chaining mode [default]
984             'pcbc' -- plaintext cipher-block chaining mode
985             'cfb' -- cipher feedback mode
986             'ofb' -- output feedback mode
987             'ctr' -- counter mode
988              
989             -pbkdf The passphrase-based key derivation function used to derive
990             the encryption key and initialization vector from the
991             provided passphrase. For backward compatibility, Crypt::CBC
992             will default to "opensslv1", but it is recommended to use
993             the standard "pbkdf2"algorithm instead. If you wish to interoperate
994             with OpenSSL, be aware that different versions of the software
995             support a series of derivation functions.
996              
997             'none' -- The value provided in -pass/-key is used directly.
998             This is the same as passing true to -literal_key.
999             You must also manually specify the IV with -iv.
1000             The key and the IV must match the keylength
1001             and blocklength of the chosen cipher.
1002             'randomiv' -- Use insecure key derivation method found
1003             in prehistoric versions of OpenSSL (dangerous)
1004             'opensslv1' -- [default] Use the salted MD5 method that was default
1005             in versions of OpenSSL through v1.0.2.
1006             'opensslv2' -- [better] Use the salted SHA-256 method that was
1007             the default in versions of OpenSSL through v1.1.0.
1008             'pbkdf2' -- [best] Use the PBKDF2 method that was first
1009             introduced in OpenSSL v1.1.1.
1010              
1011             More derivation functions may be added in the future. To see the
1012             supported list, use the command
1013             perl -MCrypt::CBC::PBKDF -e 'print join "\n",Crypt::CBC::PBKDF->list'
1014              
1015             -iter If the 'pbkdf2' key derivation algorithm is used, this specifies the number of
1016             hashing cycles to be applied to the passphrase+salt (longer is more secure).
1017             [default 10,000]
1018              
1019             -hasher If the 'pbkdf2' key derivation algorithm is chosen, you can use this to provide
1020             an initialized Crypt::PBKDF2::Hash object.
1021             [default HMACSHA2 for OpenSSL compatability]
1022              
1023             -header What type of header to prepend to the ciphertext. One of
1024             'salt' -- use OpenSSL-compatible salted header (default)
1025             'randomiv' -- Randomiv-compatible "RandomIV" header
1026             'none' -- prepend no header at all
1027             (compatible with prehistoric versions
1028             of OpenSSL)
1029              
1030             -iv The initialization vector (IV). If not provided, it will be generated
1031             by the key derivation function.
1032              
1033             -salt The salt passed to the key derivation function. If not provided, will be
1034             generated randomly (recommended).
1035              
1036             -padding The padding method, one of "standard" (default),
1037             "space", "oneandzeroes", "rijndael_compat",
1038             "null", or "none" (default "standard").
1039              
1040             -literal_key [deprected, use -pbkdf=>'none']
1041             If true, the key provided by "-key" or "-pass" is used
1042             directly for encryption/decryption without salting or
1043             hashing. The key must be the right length for the chosen
1044             cipher.
1045             [default false)
1046              
1047             -pcbc [deprecated, use -chaining_mode=>'pcbc']
1048             Whether to use the PCBC chaining algorithm rather than
1049             the standard CBC algorithm (default false).
1050              
1051             -add_header [deprecated; use -header instead]
1052             Whether to add the salt and IV to the header of the output
1053             cipher text.
1054              
1055             -regenerate_key [deprecated; use -literal_key instead]
1056             Whether to use a hash of the provided key to generate
1057             the actual encryption key (default true)
1058              
1059             -prepend_iv [deprecated; use -header instead]
1060             Whether to prepend the IV to the beginning of the
1061             encrypted stream (default true)
1062              
1063             Crypt::CBC requires three pieces of information to do its job. First
1064             it needs the name of the block cipher algorithm that will encrypt or
1065             decrypt the data in blocks of fixed length known as the cipher's
1066             "blocksize." Second, it needs an encryption/decryption key to pass to
1067             the block cipher. Third, it needs an initialization vector (IV) that
1068             will be used to propagate information from one encrypted block to the
1069             next. Both the key and the IV must be exactly the same length as the
1070             chosen cipher's blocksize.
1071              
1072             Crypt::CBC can derive the key and the IV from a passphrase that you
1073             provide, or can let you specify the true key and IV manually. In
1074             addition, you have the option of embedding enough information to
1075             regenerate the IV in a short header that is emitted at the start of
1076             the encrypted stream, or outputting a headerless encryption stream. In
1077             the first case, Crypt::CBC will be able to decrypt the stream given
1078             just the original key or passphrase. In the second case, you will have
1079             to provide the original IV as well as the key/passphrase.
1080              
1081             The B<-cipher> option specifies which block cipher algorithm to use to
1082             encode each section of the message. This argument is optional and
1083             will default to the secure Crypt::Cipher::AES algorithm.
1084             You may use any compatible block encryption
1085             algorithm that you have installed. Currently, this includes
1086             Crypt::Cipher::AES, Crypt::DES, Crypt::DES_EDE3, Crypt::IDEA, Crypt::Blowfish,
1087             Crypt::CAST5 and Crypt::Rijndael. You may refer to them using their
1088             full names ("Crypt::IDEA") or in abbreviated form ("IDEA").
1089              
1090             Instead of passing the name of a cipher class, you may pass an
1091             already-created block cipher object. This allows you to take advantage
1092             of cipher algorithms that have parameterized new() methods, such as
1093             Crypt::Eksblowfish:
1094              
1095             my $eksblowfish = Crypt::Eksblowfish->new(8,$salt,$key);
1096             my $cbc = Crypt::CBC->new(-cipher=>$eksblowfish);
1097              
1098             The B<-pass> argument provides a passphrase to use to generate the
1099             encryption key or the literal value of the block cipher key. If used
1100             in passphrase mode (which is the default), B<-pass> can be any number
1101             of characters; the actual key will be derived by passing the
1102             passphrase through a series of hashing operations. To take full
1103             advantage of a given block cipher, the length of the passphrase should
1104             be at least equal to the cipher's blocksize. For backward
1105             compatibility, you may also refer to this argument using B<-key>.
1106              
1107             To skip this hashing operation and specify the key directly, provide
1108             the actual key as a string to B<-key> and specify a key derivation
1109             function of "none" to the B<-pbkdf> argument. Alternatively, you may
1110             pass a true value to the B<-literal_key> argument. When you manually
1111             specify the key in this way, should choose a key of length exactly
1112             equal to the cipher's key length. You will also have to specify an IV
1113             equal in length to the cipher's blocksize. These choices imply a
1114             header mode of "none."
1115              
1116             If you pass an existing Crypt::* object to new(), then the
1117             B<-pass>/B<-key> argument is ignored and the module will generate a
1118             warning.
1119              
1120             The B<-pbkdf> argument specifies the algorithm used to derive the true
1121             key and IV from the provided passphrase (PBKDF stands for
1122             "passphrase-based key derivation function"). Valid values are:
1123              
1124             "opensslv1" -- [default] A fast algorithm that derives the key by
1125             combining a random salt values with the passphrase via
1126             a series of MD5 hashes.
1127              
1128             "opensslv2" -- an improved version that uses SHA-256 rather
1129             than MD5, and has been OpenSSL's default since v1.1.0.
1130             However, it has been deprecated in favor of pbkdf2
1131             since OpenSSL v1.1.1.
1132              
1133             "pbkdf2" -- a better algorithm implemented in OpenSSL v1.1.1,
1134             described in RFC 2898 L<https://tools.ietf.org/html/rfc2898>
1135              
1136             "none" -- don't use a derivation function, but treat the passphrase
1137             as the literal key. This is the same as B<-literal_key> true.
1138              
1139             "nosalt" -- an insecure key derivation method used by prehistoric versions
1140             of OpenSSL, provided for backward compatibility. Don't use.
1141              
1142             "opensslv1" was OpenSSL's default key derivation algorithm through
1143             version 1.0.2, but is susceptible to dictionary attacks and is no
1144             longer supported. It remains the default for Crypt::CBC in order to
1145             avoid breaking compatibility with previously-encrypted messages. Using
1146             this option will issue a deprecation warning when initiating
1147             encryption. You can suppress the warning by passing a true value to
1148             the B<-nodeprecate> option.
1149              
1150             It is recommended to specify the "pbkdf2" key derivation algorithm
1151             when compatibility with older versions of Crypt::CBC is not
1152             needed. This algorithm is deliberately computationally expensive in
1153             order to make dictionary-based attacks harder. As a result, it
1154             introduces a slight delay before an encryption or decryption
1155             operation starts.
1156              
1157             The B<-iter> argument is used in conjunction with the "pbkdf2" key
1158             derivation option. Its value indicates the number of hashing cycles
1159             used to derive the key. Larger values are more secure, but impose a
1160             longer delay before encryption/decryption starts. The default is
1161             10,000 for compatibility with OpenSSL's default.
1162              
1163             The B<-hasher> argument is used in conjunction with the "pbkdf2" key
1164             derivation option to pass the reference to an initialized
1165             Crypt::PBKDF2::Hash object. If not provided, it defaults to the
1166             OpenSSL-compatible hash function HMACSHA2 initialized with its default
1167             options (SHA-256 hash).
1168              
1169             The B<-header> argument specifies what type of header, if any, to
1170             prepend to the beginning of the encrypted data stream. The header
1171             allows Crypt::CBC to regenerate the original IV and correctly decrypt
1172             the data without your having to provide the same IV used to encrypt
1173             the data. Valid values for the B<-header> are:
1174              
1175             "salt" -- Combine the passphrase with an 8-byte random value to
1176             generate both the block cipher key and the IV from the
1177             provided passphrase. The salt will be appended to the
1178             beginning of the data stream allowing decryption to
1179             regenerate both the key and IV given the correct passphrase.
1180             This method is compatible with current versions of OpenSSL.
1181              
1182             "randomiv" -- Generate the block cipher key from the passphrase, and
1183             choose a random 8-byte value to use as the IV. The IV will
1184             be prepended to the data stream. This method is compatible
1185             with ciphertext produced by versions of the library prior to
1186             2.17, but is incompatible with block ciphers that have non
1187             8-byte block sizes, such as Rijndael. Crypt::CBC will exit
1188             with a fatal error if you try to use this header mode with a
1189             non 8-byte cipher. This header type is NOT secure and NOT
1190             recommended.
1191              
1192             "none" -- Do not generate a header. To decrypt a stream encrypted
1193             in this way, you will have to provide the true key and IV
1194             manually.
1195              
1196             B<The "salt" header is now the default as of Crypt::CBC version 2.17. In
1197             all earlier versions "randomiv" was the default.>
1198              
1199             When using a "salt" header, you may specify your own value of the
1200             salt, by passing the desired 8-byte character string to the B<-salt>
1201             argument. Otherwise, the module will generate a random salt for
1202             you. Crypt::CBC will generate a fatal error if you specify a salt
1203             value that isn't exactly 8 bytes long. For backward compatibility
1204             reasons, passing a value of "1" will generate a random salt, the same
1205             as if no B<-salt> argument was provided.
1206              
1207             The B<-padding> argument controls how the last few bytes of the
1208             encrypted stream are dealt with when they not an exact multiple of the
1209             cipher block length. The default is "standard", the method specified
1210             in PKCS#5.
1211              
1212             The B<-chaining_mode> argument will select among several different
1213             block chaining modes. Values are:
1214              
1215             'cbc' -- [default] traditional Cipher-Block Chaining mode. It has
1216             the property that if one block in the ciphertext message
1217             is damaged, only that block and the next one will be
1218             rendered un-decryptable.
1219              
1220             'pcbc' -- Plaintext Cipher-Block Chaining mode. This has the property
1221             that one damaged ciphertext block will render the
1222             remainder of the message unreadable
1223              
1224             'cfb' -- Cipher Feedback Mode. In this mode, both encryption and decryption
1225             are performed using the block cipher's "encrypt" algorithm.
1226             The error propagation behaviour is similar to CBC's.
1227              
1228             'ofb' -- Output Feedback Mode. Similar to CFB, the block cipher's encrypt
1229             algorithm is used for both encryption and decryption. If one bit
1230             of the plaintext or ciphertext message is damaged, the damage is
1231             confined to a single block of the corresponding ciphertext or
1232             plaintext, and error correction algorithms can be used to reconstruct
1233             the damaged part.
1234              
1235             'ctr' -- Counter Mode. This mode uses a one-time "nonce" instead of
1236             an IV. The nonce is incremented by one for each block of
1237             plain or ciphertext, encrypted using the chosen
1238             algorithm, and then applied to the block of text. If one
1239             bit of the input text is damaged, it only affects 1 bit
1240             of the output text. To use CTR mode you will need to
1241             install the Perl Math::Int128 module. This chaining method
1242             is roughly half the speed of the others due to integer
1243             arithmetic.
1244              
1245             Passing a B<-pcbc> argument of true will have the same effect as
1246             -chaining_mode=>'pcbc', and is included for backward
1247             compatibility. [deprecated].
1248              
1249             For more information on chaining modes, see
1250             L<http://www.crypto-it.net/eng/theory/modes-of-block-ciphers.html>.
1251              
1252             The B<-keysize> argument can be used to force the cipher's
1253             keysize. This is useful for several of the newer algorithms, including
1254             AES, ARIA, Blowfish, and CAMELLIA. If -keysize is not specified, then
1255             Crypt::CBC will use the value returned by the cipher's max_keylength()
1256             method. Note that versions of CBC::Crypt prior to 2.36 could also
1257             allow you to set the blocksize, but this was never supported by any
1258             ciphers and has been removed.
1259              
1260             For compatibility with earlier versions of this module, you can
1261             provide new() with a hashref containing key/value pairs. The key names
1262             are the same as the arguments described earlier, but without the
1263             initial hyphen. You may also call new() with one or two positional
1264             arguments, in which case the first argument is taken to be the key and
1265             the second to be the optional block cipher algorithm.
1266              
1267              
1268             =head2 start()
1269              
1270             $cipher->start('encrypting');
1271             $cipher->start('decrypting');
1272              
1273             The start() method prepares the cipher for a series of encryption or
1274             decryption steps, resetting the internal state of the cipher if
1275             necessary. You must provide a string indicating whether you wish to
1276             encrypt or decrypt. "E" or any word that begins with an "e" indicates
1277             encryption. "D" or any word that begins with a "d" indicates
1278             decryption.
1279              
1280             =head2 crypt()
1281              
1282             $ciphertext = $cipher->crypt($plaintext);
1283              
1284             After calling start(), you should call crypt() as many times as
1285             necessary to encrypt the desired data.
1286              
1287             =head2 finish()
1288              
1289             $ciphertext = $cipher->finish();
1290              
1291             The CBC algorithm must buffer data blocks internally until they are
1292             even multiples of the encryption algorithm's blocksize (typically 8
1293             bytes). After the last call to crypt() you should call finish().
1294             This flushes the internal buffer and returns any leftover ciphertext.
1295              
1296             In a typical application you will read the plaintext from a file or
1297             input stream and write the result to standard output in a loop that
1298             might look like this:
1299              
1300             $cipher = new Crypt::CBC('hey jude!');
1301             $cipher->start('encrypting');
1302             print $cipher->crypt($_) while <>;
1303             print $cipher->finish();
1304              
1305             =head2 encrypt()
1306              
1307             $ciphertext = $cipher->encrypt($plaintext)
1308              
1309             This convenience function runs the entire sequence of start(), crypt()
1310             and finish() for you, processing the provided plaintext and returning
1311             the corresponding ciphertext.
1312              
1313             =head2 decrypt()
1314              
1315             $plaintext = $cipher->decrypt($ciphertext)
1316              
1317             This convenience function runs the entire sequence of start(), crypt()
1318             and finish() for you, processing the provided ciphertext and returning
1319             the corresponding plaintext.
1320              
1321             =head2 encrypt_hex(), decrypt_hex()
1322              
1323             $ciphertext = $cipher->encrypt_hex($plaintext)
1324             $plaintext = $cipher->decrypt_hex($ciphertext)
1325              
1326             These are convenience functions that operate on ciphertext in a
1327             hexadecimal representation. B<encrypt_hex($plaintext)> is exactly
1328             equivalent to B<unpack('H*',encrypt($plaintext))>. These functions
1329             can be useful if, for example, you wish to place the encrypted in an
1330             email message.
1331              
1332             =head2 filehandle()
1333              
1334             This method returns a filehandle for transparent encryption or
1335             decryption using Christopher Dunkle's excellent L<Crypt::FileHandle>
1336             module. This module must be installed in order to use this method.
1337              
1338             filehandle() can be called as a class method using the same arguments
1339             as new():
1340              
1341             $fh = Crypt::CBC->filehandle(-cipher=> 'Blowfish',
1342             -pass => "You'll never guess");
1343              
1344             or on a previously-created Crypt::CBC object:
1345              
1346             $cbc = Crypt::CBC->new(-cipher=> 'Blowfish',
1347             -pass => "You'll never guess");
1348             $fh = $cbc->filehandle;
1349              
1350             The filehandle can then be opened using the familiar open() syntax.
1351             Printing to a filehandle opened for writing will encrypt the
1352             data. Filehandles opened for input will be decrypted.
1353              
1354             Here is an example:
1355              
1356             # transparent encryption
1357             open $fh,'>','encrypted.out' or die $!;
1358             print $fh "You won't be able to read me!\n";
1359             close $fh;
1360              
1361             # transparent decryption
1362             open $fh,'<','encrypted.out' or die $!;
1363             while (<$fh>) { print $_ }
1364             close $fh;
1365              
1366             =head2 get_initialization_vector()
1367              
1368             $iv = $cipher->get_initialization_vector()
1369              
1370             This function will return the IV used in encryption and or decryption.
1371             The IV is not guaranteed to be set when encrypting until start() is
1372             called, and when decrypting until crypt() is called the first
1373             time. Unless the IV was manually specified in the new() call, the IV
1374             will change with every complete encryption operation.
1375              
1376             =head2 set_initialization_vector()
1377              
1378             $cipher->set_initialization_vector('76543210')
1379              
1380             This function sets the IV used in encryption and/or decryption. This
1381             function may be useful if the IV is not contained within the
1382             ciphertext string being decrypted, or if a particular IV is desired
1383             for encryption. Note that the IV must match the chosen cipher's
1384             blocksize bytes in length.
1385              
1386             =head2 iv()
1387              
1388             $iv = $cipher->iv();
1389             $cipher->iv($new_iv);
1390              
1391             As above, but using a single method call.
1392              
1393             =head2 key()
1394              
1395             $key = $cipher->key();
1396             $cipher->key($new_key);
1397              
1398             Get or set the block cipher key used for encryption/decryption. When
1399             encrypting, the key is not guaranteed to exist until start() is
1400             called, and when decrypting, the key is not guaranteed to exist until
1401             after the first call to crypt(). The key must match the length
1402             required by the underlying block cipher.
1403              
1404             When salted headers are used, the block cipher key will change after
1405             each complete sequence of encryption operations.
1406              
1407             =head2 salt()
1408              
1409             $salt = $cipher->salt();
1410             $cipher->salt($new_salt);
1411              
1412             Get or set the salt used for deriving the encryption key and IV when
1413             in OpenSSL compatibility mode.
1414              
1415             =head2 passphrase()
1416              
1417             $passphrase = $cipher->passphrase();
1418             $cipher->passphrase($new_passphrase);
1419              
1420             This gets or sets the value of the B<passphrase> passed to new() when
1421             B<literal_key> is false.
1422              
1423             =head2 $data = random_bytes($numbytes)
1424              
1425             Return $numbytes worth of random data, using L<Crypt::URandom>, which
1426             will read data from the system's source of random bytes, such as
1427             F</dev/urandom>.
1428              
1429             =head2 cipher(), pbkdf(), padding(), keysize(), blocksize(), chain_mode()
1430              
1431             These read-only methods return the identity of the chosen block cipher
1432             algorithm, the key derivation function (e.g. "opensslv1"), padding
1433             method, key and block size of the chosen block cipher, and what
1434             chaining mode ("cbc", "ofb" ,etc) is being used.
1435              
1436             =head2 Padding methods
1437              
1438             Use the 'padding' option to change the padding method.
1439              
1440             When the last block of plaintext is shorter than the block size,
1441             it must be padded. Padding methods include: "standard" (i.e., PKCS#5),
1442             "oneandzeroes", "space", "rijndael_compat", "null", and "none".
1443              
1444             standard: (default) Binary safe
1445             pads with the number of bytes that should be truncated. So, if
1446             blocksize is 8, then "0A0B0C" will be padded with "05", resulting
1447             in "0A0B0C0505050505". If the final block is a full block of 8
1448             bytes, then a whole block of "0808080808080808" is appended.
1449              
1450             oneandzeroes: Binary safe
1451             pads with "80" followed by as many "00" necessary to fill the
1452             block. If the last block is a full block and blocksize is 8, a
1453             block of "8000000000000000" will be appended.
1454              
1455             rijndael_compat: Binary safe, with caveats
1456             similar to oneandzeroes, except that no padding is performed if
1457             the last block is a full block. This is provided for
1458             compatibility with Crypt::Rijndael's buit-in MODE_CBC.
1459             Note that Crypt::Rijndael's implementation of CBC only
1460             works with messages that are even multiples of 16 bytes.
1461              
1462             null: text only
1463             pads with as many "00" necessary to fill the block. If the last
1464             block is a full block and blocksize is 8, a block of
1465             "0000000000000000" will be appended.
1466              
1467             space: text only
1468             same as "null", but with "20".
1469              
1470             none:
1471             no padding added. Useful for special-purpose applications where
1472             you wish to add custom padding to the message.
1473              
1474             Both the standard and oneandzeroes paddings are binary safe. The
1475             space and null paddings are recommended only for text data. Which
1476             type of padding you use depends on whether you wish to communicate
1477             with an external (non Crypt::CBC library). If this is the case, use
1478             whatever padding method is compatible.
1479              
1480             You can also pass in a custom padding function. To do this, create a
1481             function that takes the arguments:
1482              
1483             $padded_block = function($block,$blocksize,$direction);
1484              
1485             where $block is the current block of data, $blocksize is the size to
1486             pad it to, $direction is "e" for encrypting and "d" for decrypting,
1487             and $padded_block is the result after padding or depadding.
1488              
1489             When encrypting, the function should always return a string of
1490             <blocksize> length, and when decrypting, can expect the string coming
1491             in to always be that length. See _standard_padding(), _space_padding(),
1492             _null_padding(), or _oneandzeroes_padding() in the source for examples.
1493              
1494             Standard and oneandzeroes padding are recommended, as both space and
1495             null padding can potentially truncate more characters than they should.
1496              
1497             =head1 Comparison to Crypt::Mode::CBC
1498              
1499             The L<CryptX> modules L<Crypt::Mode::CBC>, L<Crypt::Mode::OFB>,
1500             L<Crypt::Mode::CFB>, and L<Crypt::Mode::CTR> provide fast
1501             implementations of the respective cipherblock chaining modes (roughly
1502             5x the speed of Crypt::CBC). Crypt::CBC was designed to encrypt and
1503             decrypt messages in a manner compatible with OpenSSL's "enc"
1504             function. Hence it handles the derivation of the key and IV from a
1505             passphrase using the same conventions as OpenSSL, and it writes out an
1506             OpenSSL-compatible header in the encrypted message in a manner that
1507             allows the key and IV to be regenerated during decryption.
1508              
1509             In contrast, the CryptX modules do not automatically derive the key
1510             and IV from a passphrase or write out an encrypted header. You will
1511             need to derive and store the key and IV by other means (e.g. with
1512             CryptX's Crypt::KeyDerivation module, or with Crypt::PBKDF2).
1513              
1514             =head1 EXAMPLES
1515              
1516             Three examples, aes.pl, des.pl and idea.pl can be found in the eg/
1517             subdirectory of the Crypt-CBC distribution. These implement
1518             command-line DES and IDEA encryption algorithms using default
1519             parameters, and should be compatible with recent versions of
1520             OpenSSL. Note that aes.pl uses the "pbkdf2" key derivation function to
1521             generate its keys. The other two were distributed with pre-PBKDF2
1522             versions of Crypt::CBC, and use the older "opensslv1" algorithm.
1523              
1524             =head1 LIMITATIONS
1525              
1526             The encryption and decryption process is about a tenth the speed of
1527             the equivalent OpenSSL tool and about a fifth of the Crypt::Mode::CBC
1528             module (both which use compiled C).
1529              
1530             =head1 BUGS
1531              
1532             Please report them.
1533              
1534             =head1 AUTHOR
1535              
1536             Lincoln Stein, lstein@cshl.org
1537              
1538             =head1 LICENSE
1539              
1540             This module is distributed under the ARTISTIC LICENSE v2 using the
1541             same terms as Perl itself.
1542              
1543             =head1 SEE ALSO
1544              
1545             perl(1), CryptX, Crypt::FileHandle, Crypt::Cipher::AES,
1546             Crypt::Blowfish, Crypt::CAST5, Crypt::DES, Crypt::IDEA,
1547             Crypt::Rijndael
1548              
1549             =cut