File Coverage

blib/lib/Crypt/CBC.pm
Criterion Covered Total %
statement 208 287 72.5
branch 97 194 50.0
condition 32 97 33.0
subroutine 21 36 58.3
pod 19 22 86.4
total 377 636 59.3


line stmt bran cond sub pod time code
1             package Crypt::CBC;
2              
3 4     4   59 use Digest::MD5 'md5';
  4         55  
  4         78  
4 4     4   62 use Carp;
  4         37  
  4         75  
5 4     4   59 use strict;
  4         37  
  4         57  
6 4     4   117 use vars qw($VERSION);
  4         38  
  4         106  
7             $VERSION = '2.22';
8              
9 4     4   61 use constant RANDOM_DEVICE => '/dev/urandom';
  4         37  
  4         73  
10              
11             sub new {
12 15     15 1 416     my $class = shift;
13              
14 15         215     my $options = {};
15              
16             # hashref arguments
17 15 50       333     if (ref $_[0] eq 'HASH') {
    100          
18 0         0       $options = shift;
19                 }
20              
21             # CGI style arguments
22                 elsif ($_[0] =~ /^-[a-zA-Z_]{1,20}$/) {
23 13         192       my %tmp = @_;
24 13         171       while ( my($key,$value) = each %tmp) {
25 38         398 $key =~ s/^-//;
26 38         2835 $options->{lc $key} = $value;
27                   }
28                 }
29              
30                 else {
31 2         24 $options->{key}    = shift;
32 2         22 $options->{cipher} = shift;
33                 }
34              
35 15   33     214     my $cipher_object_provided = $options->{cipher} && ref $options->{cipher};
36              
37             # "key" is a misnomer here, because it is actually usually a passphrase that is used
38             # to derive the true key
39 15         138     my $pass = $options->{key};
40              
41 15 50       184     if ($cipher_object_provided) {
    50          
42 0 0       0       carp "Both a key and a pre-initialized Crypt::* object were passed. The key will be ignored"
43             if defined $pass;
44 0   0     0       $pass ||= '';
45                 }
46                 elsif (!defined $pass) {
47 0         0       croak "Please provide an encryption/decryption passphrase or key using -key"
48                 }
49              
50             # header mode
51 15         169     my %valid_modes = map {$_=>1} qw(none salt randomiv);
  45         484  
52 15         174     my $header_mode = $options->{header};
53 15 50 0     189     $header_mode ||= 'none' if exists $options->{prepend_iv} && !$options->{prepend_iv};
      33        
54 15 50 0     172     $header_mode ||= 'none' if exists $options->{add_header} && !$options->{add_header};
      33        
55 15   50     181     $header_mode ||= 'salt'; # default
56 15 50       151     croak "Invalid -header mode '$header_mode'" unless $valid_modes{$header_mode};
57              
58 15 50 33     212     croak "The -salt argument is incompatible with a -header mode of $header_mode"
59                   if exists $options->{salt} && $header_mode ne 'salt';
60              
61 15         132     my $cipher = $options->{cipher};
62 15 50       176     $cipher = 'Crypt::DES' unless $cipher;
63 15   33     185     my $cipherclass = ref $cipher || $cipher;
64              
65 15 50       182     unless (ref $cipher) { # munge the class name if no object passed
66 15 50       942       $cipher = $cipher=~/^Crypt::/ ? $cipher : "Crypt::$cipher";
67 15 50 66     776       $cipher->can('encrypt') or eval "require $cipher; 1" or croak "Couldn't load $cipher: $@";
68             # some crypt modules use the class Crypt::, and others don't
69 15 100       263       $cipher =~ s/^Crypt::// unless $cipher->can('keysize');
70                 }
71              
72             # allow user to override these values
73 15         137     my $ks = $options->{keysize};
74 15         134     my $bs = $options->{blocksize};
75              
76             # otherwise we get the values from the cipher
77 15   50     192     $ks ||= eval {$cipher->keysize};
  15         181  
78 15   50     251     $bs ||= eval {$cipher->blocksize};
  15         168  
79              
80             # Some of the cipher modules are busted and don't report the
81             # keysize (well, Crypt::Blowfish in any case). If we detect
82             # this, and find the blowfish module in use, then assume 56.
83             # Otherwise assume the least common denominator of 8.
84 15 50 100     169     $ks ||= $cipherclass =~ /blowfish/i ? 56 : 8;
85 15   50     190     $bs ||= $ks;
86              
87 15         132     my $pcbc = $options->{'pcbc'};
88              
89             # Default behavior is to treat -key as a passphrase.
90             # But if the literal_key option is true, then use key as is
91 15 50 33     163     croak "The options -literal_key and -regenerate_key are incompatible with each other"
92                   if exists $options->{literal_key} && exists $options->{regenerate_key};
93 15         119     my $key;
94 15 50       151     $key = $pass if $options->{literal_key};
95 15 50 33     206     $key = $pass if exists $options->{regenerate_key} && !$options->{regenerate_key};
96              
97             # Get the salt.
98 15         130     my $salt = $options->{salt};
99 15 50 33     768     my $random_salt = 1 unless defined $salt && $salt ne '1';
100 15 50 33     182     croak "Argument to -salt must be exactly 8 bytes long" if defined $salt && length $salt != 8 && $salt ne '1';
      33        
101              
102             # note: iv will be autogenerated by start() if not specified in options
103 15         161     my $iv = $options->{iv};
104 15 50       152     my $random_iv = 1 unless defined $iv;
105 15 50 33     185     croak "Initialization vector must be exactly $bs bytes long when using the $cipherclass cipher" if defined $iv and length($iv) != $bs;
106              
107 15   33     340     my $literal_key = $options->{literal_key} || (exists $options->{regenerate_key} && !$options->{regenerate_key});
      33        
108 15         170     my $legacy_hack = $options->{insecure_legacy_decrypt};
109 15   100     202     my $padding = $options->{padding} || 'standard';
110              
111 15 50 33     216     if ($padding && ref($padding) eq 'CODE') {
112             # check to see that this code does its padding correctly
113 0         0       for my $i (1..$bs-1) {
114 0         0 my $rbs = length($padding->(" "x$i,$bs,'e'));
115 0 0       0 croak "padding method callback does not behave properly: expected $bs bytes back, got $rbs bytes back."
116             unless ($rbs == $bs);
117                   }
118                 } else {
119 15 50       268       $padding = $padding eq 'null' ? \&_null_padding
    100          
    100          
    100          
120             :$padding eq 'space' ? \&_space_padding
121             :$padding eq 'oneandzeroes' ? \&_oneandzeroes_padding
122                             :$padding eq 'standard' ? \&_standard_padding
123             :croak "'$padding' padding not supported. See perldoc Crypt::CBC for instructions on creating your own.";
124                 }
125              
126             # CONSISTENCY CHECKS
127             # HEADER consistency
128 15 50       152     if ($header_mode eq 'salt') {
    0          
    0          
129 15 50       154       croak "Cannot use salt-based key generation if literal key is specified" if $options->{literal_key};
130 15 50       535       croak "Cannot use salt-based IV generation if literal IV is specified" if exists $options->{iv};
131                 }
132                 elsif ($header_mode eq 'randomiv') {
133 0 0 0     0       croak "Cannot encrypt using a non-8 byte blocksize cipher when using randomiv header mode" unless $bs == 8 || $legacy_hack;
134                 }
135                 elsif ($header_mode eq 'none') {
136 0 0       0       croak "You must provide an initialization vector using -iv when using -header=>'none'" unless exists $options->{iv};
137                 }
138              
139             # KEYSIZE consistency
140 15 50 33     179     if (defined $key && length($key) != $ks) {
141 0         0       croak "If specified by -literal_key, then the key length must be equal to the chosen cipher's key length of $ks bytes";
142                 }
143              
144             # IV consistency
145 15 50 33     190     if (defined $iv && length($iv) != $bs) {
146 0         0       croak "If specified by -iv, then the initialization vector length must be equal to the chosen cipher's blocksize of $bs bytes";
147                 }
148              
149              
150 15         539     return bless {'cipher' => $cipher,
151             'passphrase'  => $pass,
152             'key'         => $key,
153             'iv'          => $iv,
154             'salt'        => $salt,
155             'padding'     => $padding,
156             'blocksize'   => $bs,
157             'keysize'     => $ks,
158                               'header_mode' => $header_mode,
159             'legacy_hack' => $legacy_hack,
160                               'literal_key' => $literal_key,
161                               'pcbc' => $pcbc,
162             'make_random_salt' => $random_salt,
163             'make_random_iv'   => $random_iv,
164             },$class;
165             }
166              
167             sub encrypt (\$$) {
168 435     435 1 5162     my ($self,$data) = @_;
169 435         6949     $self->start('encrypting');
170 435         6641     my $result = $self->crypt($data);
171 435         4920     $result .= $self->finish;
172 435         17064     $result;
173             }
174              
175             sub decrypt (\$$){
176 435     435 1 6641     my ($self,$data) = @_;
177 435         5488     $self->start('decrypting');
178 435         13324     my $result = $self->crypt($data);
179 435         8906     $result .= $self->finish;
180 435         7460     $result;
181             }
182              
183             sub encrypt_hex (\$$) {
184 0     0 1 0     my ($self,$data) = @_;
185 0         0     return join('',unpack 'H*',$self->encrypt($data));
186             }
187              
188             sub decrypt_hex (\$$) {
189 0     0 1 0     my ($self,$data) = @_;
190 0         0     return $self->decrypt(pack'H*',$data);
191             }
192            
193             # call to start a series of encryption/decryption operations
194             sub start (\$$) {
195 870     870 1 7910 my $self = shift;
196 870         10008 my $operation = shift;
197 870 50       10944 croak "Specify <e>ncryption or <d>ecryption" unless $operation=~/^[ed]/i;
198            
199 870         8799 $self->{'buffer'} = '';
200 870         9831 $self->{'decrypt'} = $operation=~/^d/i;
201             }
202            
203             # call to encrypt/decrypt a bit of data
204             sub crypt (\$$){
205 870     870 1 10327 my $self = shift;
206 870         9259 my $data = shift;
207            
208 870         8219 my $result;
209            
210 870 50       9543 croak "crypt() called without a preceding start()"
211             unless exists $self->{'buffer'};
212            
213 870         10823 my $d = $self->{'decrypt'};
214            
215 870 50       11220 unless ($self->{civ}) { # block cipher has not yet been initialized
216 870 100       9938 $result = $self->_generate_iv_and_cipher_from_datastream(\$data) if $d;
217 870 100       15341 $result = $self->_generate_iv_and_cipher_from_options() unless $d;
218             }
219            
220 870         11200 my $iv = $self->{'civ'};
221 870         13941 $self->{'buffer'} .= $data;
222            
223 870         8254 my $bs = $self->{'blocksize'};
224            
225 870 100       15652 return $result unless (length($self->{'buffer'}) >= $bs);
226            
227 741         16552 my @blocks = unpack("a$bs "x(int(length($self->{'buffer'})/$bs)) . "a*", $self->{'buffer'});
228 741         13118 $self->{'buffer'} = '';
229            
230 741 100       9434 if ($d) { # when decrypting, always leave a free block at the end
231 426 50       8203 $self->{'buffer'} = length($blocks[-1]) < $bs ? join '',splice(@blocks,-2) : pop(@blocks);
232             } else {
233 315 50       3929 $self->{'buffer'} = pop @blocks if length($blocks[-1]) < $bs; # what's left over
234             }
235            
236 741         7557 foreach my $block (@blocks) {
237 3543 100       34078       if ($d) { # decrypting
238 1758         23418 $result .= $iv = $iv ^ $self->{'crypt'}->decrypt($block);
239 1758 50       34777 $iv = $block unless $self->{pcbc};
240                   } else { # encrypting
241 1785         24060 $result .= $iv = $self->{'crypt'}->encrypt($iv ^ $block);
242                   }
243 3543 50       42755       $iv = $iv ^ $block if $self->{pcbc};
244                 }
245 741         10496     $self->{'civ'} = $iv; # remember the iv
246 741         10660     return $result;
247             }
248              
249             # this is called at the end to flush whatever's left
250             sub finish (\$) {
251 870     870 1 11148     my $self = shift;
252 870         9487     my $bs = $self->{'blocksize'};
253 870 50       9199     my $block = defined $self->{'buffer'} ? $self->{'buffer'} : '';
254              
255 870   50     13317     $self->{civ} ||= '';
256              
257 870         6982     my $result;
258 870 100       8755     if ($self->{'decrypt'}) { #decrypting
259 435 100       6823 $block = length $block ? pack("a$bs",$block) : ''; # pad and truncate to block size
260            
261 435 100       7108 if (length($block)) {
262 426         5316 $result = $self->{'civ'} ^ $self->{'crypt'}->decrypt($block);
263 426         4875 $result = $self->{'padding'}->($result, $bs, 'd');
264             } else {
265 9         77 $result = '';
266             }
267              
268                 } else { # encrypting
269 435   100     4784       $block = $self->{'padding'}->($block,$bs,'e') || '';
270 435 100       6686       $result = length $block ? $self->{'crypt'}->encrypt($self->{'civ'} ^ $block) : '';
271                 }
272 870         9597     delete $self->{'civ'};
273 870         8780     delete $self->{'buffer'};
274 870         9060     return $result;
275             }
276              
277             # this subroutine will generate the actual {en,de}cryption key, the iv
278             # and the block cipher object. This is called when reading from a datastream
279             # and so it uses previous values of salt or iv if they are encoded in datastream
280             # header
281             sub _generate_iv_and_cipher_from_datastream {
282 435     435   4060   my $self = shift;
283 435         6132   my $input_stream = shift;
284 435         4365   my $bs = $self->blocksize;
285              
286             # use our header mode to figure out what to do with the data stream
287 435         5267   my $header_mode = $self->header_mode;
288              
289 435 50       5002   if ($header_mode eq 'none') {
    50          
    0          
290 0 0       0     croak "You must specify a $bs byte initialization vector by passing the -iv option to new() when using -header_mode=>'none'"
291                   unless exists $self->{iv};
292 0         0     $self->{civ} = $self->{iv}; # current IV equals saved IV
293 0   0     0     $self->{key} ||= $self->_key_from_key($self->{passphrase});
294               }
295              
296               elsif ($header_mode eq 'salt') {
297 435         8821     my ($salt) = $$input_stream =~ /^Salted__(.{8})/s;
298 435 50       7124     croak "Ciphertext does not begin with a valid header for 'salt' header mode" unless defined $salt;
299 435         5230     $self->{salt} = $salt; # new salt
300 435         8836     substr($$input_stream,0,16) = '';
301 435         5005     my ($key,$iv) = $self->_salted_key_and_iv($self->{passphrase},$salt);
302 435         5044     $self->{iv} = $self->{civ} = $iv;
303 435         4287     $self->{key} = $key;
304               }
305              
306               elsif ($header_mode eq 'randomiv') {
307 0         0     my ($iv) = $$input_stream =~ /^RandomIV(.{8})/s;
308 0 0       0     croak "Ciphertext does not begin with a valid header for 'randomiv' header mode" unless defined $iv;
309 0 0 0     0     croak "randomiv header mode cannot be used securely when decrypting with a >8 byte block cipher.\nUse the -insecure_legacy_decrypt flag if you are sure you want to do this" unless $self->blocksize == 8 || $self->legacy_hack;
310 0         0     $self->{iv} = $self->{civ} = $iv;
311 0         0     $self->{key} = $self->_key_from_key($self->{passphrase});
312 0         0     undef $self->{salt}; # paranoia
313 0         0     substr($$input_stream,0,16) = ''; # truncate
314               }
315              
316               else {
317 0         0     croak "Invalid header mode '$header_mode'";
318               }
319              
320             # we should have the key and iv now, or we are dead in the water
321 435 50 33     8685   croak "Cipher stream did not contain IV or salt, and you did not specify these values in new()"
322                 unless $self->{key} && $self->{civ};
323              
324             # now we can generate the crypt object itself
325 435 50       9703   $self->{crypt} = ref $self->{cipher} ? $self->{cipher}
    50          
326                                                    : $self->{cipher}->new($self->{key})
327             or croak "Could not create $self->{cipher} object: $@";
328 435         5355   return '';
329             }
330              
331             sub _generate_iv_and_cipher_from_options {
332 435     435   4442   my $self = shift;
333 435         10662   my $blocksize = $self->blocksize;
334              
335 435         9754   my $result = '';
336              
337 435         4601   my $header_mode = $self->header_mode;
338 435 50       10177   if ($header_mode eq 'none') {
    50          
    0          
339 0 0       0     croak "You must specify a $blocksize byte initialization vector by passing the -iv option to new() when using -header_mode=>'none'"
340                   unless exists $self->{iv};
341 0         0     $self->{civ} = $self->{iv};
342 0   0     0     $self->{key} ||= $self->_key_from_key($self->{passphrase});
343               }
344              
345               elsif ($header_mode eq 'salt') {
346 435 50       6756     $self->{salt} = $self->_get_random_bytes(8) if $self->{make_random_salt};
347 435 50       9229     defined (my $salt = $self->{salt}) or croak "No header_mode of 'salt' specified, but no salt value provided"; # shouldn't happen
348 435 50       9976     length($salt) == 8 or croak "Salt must be exactly 8 bytes long";
349 435         6420     my ($key,$iv) = $self->_salted_key_and_iv($self->{passphrase},$salt);
350 435         13646     $self->{key} = $key;
351 435         7749     $self->{civ} = $self->{iv} = $iv;
352 435         5983     $result = "Salted__${salt}";
353               }
354              
355               elsif ($header_mode eq 'randomiv') {
356 0 0       0     croak "randomiv header mode cannot be used when encrypting with a >8 byte block cipher. There is no option to allow this"
357                   unless $blocksize == 8;
358 0   0     0     $self->{key} ||= $self->_key_from_key($self->{passphrase});
359 0 0       0     $self->{iv} = $self->_get_random_bytes(8) if $self->{make_random_iv};
360 0 0       0     length($self->{iv}) == 8 or croak "IV must be exactly 8 bytes long when used with header mode of 'randomiv'";
361 0         0     $self->{civ} = $self->{iv};
362 0         0     $result = "RandomIV$self->{iv}";
363               }
364              
365 435 50 33     9539   croak "key and/or iv are missing" unless defined $self->{key} && defined $self->{civ};
366              
367 435 50       7132   $self->{crypt} = ref $self->{cipher} ? $self->{cipher}
    50          
368                                                    : $self->{cipher}->new($self->{key})
369             or croak "Could not create $self->{cipher} object: $@";
370 435         6279   return $result;
371             }
372              
373             sub _key_from_key {
374 0     0   0   my $self = shift;
375 0         0   my $pass = shift;
376 0         0   my $ks = $self->{keysize};
377              
378 0 0       0   return $pass if $self->{literal_key};
379              
380 0         0   my $material = md5($pass);
381 0         0   while (length($material) < $ks) {
382 0         0     $material .= md5($material);
383               }
384 0         0   return substr($material,0,$ks);
385             }
386              
387             sub _salted_key_and_iv {
388 870     870   10599   my $self = shift;
389 870         8705   my ($pass,$salt) = @_;
390              
391 870 50       11540   croak "Salt must be 8 bytes long" unless length $salt == 8;
392              
393 870         12175   my $key_len = $self->{keysize};
394 870         10229   my $iv_len = $self->{blocksize};
395              
396 870         9601   my $desired_len = $key_len+$iv_len;
397              
398 870         9928   my $data = '';
399 870         10318   my $d = '';
400              
401 870         17898   while (length $data < $desired_len) {
402 2030         28916     $d = md5($d . $pass . $salt);
403 2030         29812     $data .= $d;
404               }
405 870         11294   return (substr($data,0,$key_len),substr($data,$key_len,$iv_len));
406             }
407              
408             sub random_bytes {
409 0     0 0 0   my $self = shift;
410 0 0       0   my $bytes = shift or croak "usage: random_bytes(\$byte_length)";
411 0         0   $self->_get_random_bytes($bytes);
412             }
413              
414             sub _get_random_bytes {
415 435     435   4653   my $self = shift;
416 435         6513   my $length = shift;
417 435         3622   my $result;
418              
419 435 50 33     58516   if (-r RANDOM_DEVICE && open(F,RANDOM_DEVICE)) {
420 435         592013     read(F,$result,$length);
421 435         19695     close F;
422               } else {
423 0         0     $result = pack("C*",map {rand(256)} 1..$length);
  0         0  
424               }
425 435         11621   $result;
426             }
427              
428             sub _standard_padding ($$$) {
429 348     348   6831   my ($b,$bs,$decrypt) = @_;
430 348 100       3592   $b = length $b ? $b : '';
431 348 100       3443   if ($decrypt eq 'd') {
432 174         2719      substr($b, -unpack("C",substr($b,-1)))='';
433 174         1969      return $b;
434               }
435 174         1730   my $pad = $bs - length($b) % $bs;
436 174         2765   return $b . pack("C*",($pad)x$pad);
437             }
438              
439             sub _space_padding ($$$) {
440 171     171   1879   my ($b,$bs,$decrypt) = @_;
441 171 100       1749   return unless length $b;
442 159 50       1585   $b = length $b ? $b : '';
443 159 100       1552   if ($decrypt eq 'd') {
444 84         1210      $b=~ s/ *$//s;
445 84         888      return $b;
446               }
447 75         1248   return $b . pack("C*", (32) x ($bs - length($b) % $bs));
448             }
449              
450             sub _null_padding ($$$) {
451 171     171   1742   my ($b,$bs,$decrypt) = @_;
452 171 100       4005   return unless length $b;
453 159 50       1472   $b = length $b ? $b : '';
454 159 100       1641   if ($decrypt eq 'd') {
455 84         1263      $b=~ s/\0*$//s;
456 84         1055      return $b;
457               }
458 75         1263   return $b . pack("C*", (0) x ($bs - length($b) % $bs));
459             }
460              
461             sub _oneandzeroes_padding ($$$) {
462 171     171   1863   my ($b,$bs,$decrypt) = @_;
463 171 100       1650   return unless length $b;
464 159 50       1686   $b = length $b ? $b : '';
465 159 100       1914   if ($decrypt eq 'd') {
466 84         959      my $hex = unpack("H*", $b);
467 84         1265      $hex =~ s/80*$//s;
468 84         1340      return pack("H*", $hex);
469               }
470 75         1312   return $b . pack("C*", 128, (0) x ($bs - length($b) % $bs - 1) );
471             }
472              
473             sub get_initialization_vector (\$) {
474 0     0 1 0   my $self = shift;
475 0         0   $self->iv();
476             }
477              
478             sub set_initialization_vector (\$$) {
479 0     0 1 0   my $self = shift;
480 0         0   my $iv = shift;
481 0         0   my $bs = $self->blocksize;
482 0 0       0   croak "Initialization vector must be $bs bytes in length" unless length($iv) == $bs;
483 0         0   $self->iv($iv);
484             }
485              
486             sub salt {
487 0     0 1 0   my $self = shift;
488 0         0   my $d = $self->{salt};
489 0 0       0   $self->{salt} = shift if @_;
490 0         0   $d;
491             }
492              
493             sub iv {
494 0     0 1 0   my $self = shift;
495 0         0   my $d = $self->{iv};
496 0 0       0   $self->{iv} = shift if @_;
497 0         0   $d;
498             }
499              
500             sub key {
501 0     0 1 0   my $self = shift;
502 0         0   my $d = $self->{key};
503 0 0       0   $self->{key} = shift if @_;
504 0         0   $d;
505             }
506              
507             sub passphrase {
508 0     0 1 0   my $self = shift;
509 0         0   my $d = $self->{passphrase};
510 0 0       0   if (@_) {
511 0         0     undef $self->{key};
512 0         0     undef $self->{iv};
513 0         0     $self->{passphrase} = shift;
514               }
515 0         0   $d;
516             }
517              
518 0     0 1 0 sub cipher { shift->{cipher} }
519 0     0 1 0 sub padding { shift->{padding} }
520 0     0 1 0 sub keysize { shift->{keysize} }
521 870     870 1 10274 sub blocksize { shift->{blocksize} }
522 0     0 1 0 sub pcbc { shift->{pcbc} }
523 870     870 0 9467 sub header_mode {shift->{header_mode} }
524 0     0 0   sub legacy_hack { shift->{legacy_hack} }
525              
526             1;
527             __END__
528            
529             =head1 NAME
530            
531             Crypt::CBC - Encrypt Data with Cipher Block Chaining Mode
532            
533             =head1 SYNOPSIS
534            
535             use Crypt::CBC;
536             $cipher = Crypt::CBC->new( -key => 'my secret key',
537             -cipher => 'Blowfish'
538             );
539            
540             $ciphertext = $cipher->encrypt("This data is hush hush");
541             $plaintext = $cipher->decrypt($ciphertext);
542            
543             $cipher->start('encrypting');
544             open(F,"./BIG_FILE");
545             while (read(F,$buffer,1024)) {
546             print $cipher->crypt($buffer);
547             }
548             print $cipher->finish;
549            
550             # do-it-yourself mode -- specify key, initialization vector yourself
551             $key = Crypt::CBC->random_bytes(8); # assuming a 8-byte block cipher
552             $iv = Crypt::CBC->random_bytes(8);
553             $cipher = Crypt::CBC->new(-literal_key => 1,
554             -key => $key,
555             -iv => $iv,
556             -header => 'none');
557            
558             $ciphertext = $cipher->encrypt("This data is hush hush");
559             $plaintext = $cipher->decrypt($ciphertext);
560            
561             # RANDOMIV-compatible mode
562             $cipher = Crypt::CBC->new(-key => 'Super Secret!'
563             -header => 'randomiv');
564            
565            
566             =head1 DESCRIPTION
567            
568             This module is a Perl-only implementation of the cryptographic cipher
569             block chaining mode (CBC). In combination with a block cipher such as
570             DES or IDEA, you can encrypt and decrypt messages of arbitrarily long
571             length. The encrypted messages are compatible with the encryption
572             format used by the B<OpenSSL> package.
573            
574             To use this module, you will first create a Crypt::CBC cipher object
575             with new(). At the time of cipher creation, you specify an encryption
576             key to use and, optionally, a block encryption algorithm. You will
577             then call the start() method to initialize the encryption or
578             decryption process, crypt() to encrypt or decrypt one or more blocks
579             of data, and lastly finish(), to pad and encrypt the final block. For
580             your convenience, you can call the encrypt() and decrypt() methods to
581             operate on a whole data value at once.
582            
583             =head2 new()
584            
585             $cipher = Crypt::CBC->new( -key => 'my secret key',
586             -cipher => 'Blowfish',
587             );
588            
589             # or (for compatibility with versions prior to 2.13)
590             $cipher = Crypt::CBC->new( {
591             key => 'my secret key',
592             cipher => 'Blowfish'
593             }
594             );
595            
596            
597             # or (for compatibility with versions prior to 2.0)
598             $cipher = new Crypt::CBC('my secret key' => 'Blowfish');
599            
600             The new() method creates a new Crypt::CBC object. It accepts a list of
601             -argument => value pairs selected from the following list:
602            
603             Argument Description
604             -------- -----------
605            
606             -key The encryption/decryption key (required)
607            
608             -cipher The cipher algorithm (defaults to Crypt::DES), or
609             a preexisting cipher object.
610            
611             -salt Enables OpenSSL-compatibility. If equal to a value
612             of "1" then causes a random salt to be generated
613             and used to derive the encryption key and IV. Other
614             true values are taken to be the literal salt.
615            
616             -iv The initialization vector (IV)
617            
618             -header What type of header to prepend to ciphertext. One of
619             'salt' -- use OpenSSL-compatible salted header
620             'randomiv' -- Randomiv-compatible "RandomIV" header
621             'none' -- prepend no header at all
622            
623             -padding The padding method, one of "standard", "space",
624             "onesandzeroes", or "null". (default "standard")
625            
626             -literal_key If true, the key provided by "key" is used directly
627             for encryption/decryption. Otherwise the actual
628             key used will be a hash of the provided key.
629             (default false)
630            
631             -pcbc Whether to use the PCBC chaining algorithm rather than
632             the standard CBC algorithm (default false).
633            
634             -keysize Force the cipher keysize to the indicated number of bytes.
635            
636             -blocksize Force the cipher blocksize to the indicated number of bytes.
637            
638             -insecure_legacy_decrypt
639             Allow decryption of data encrypted using the "RandomIV" header
640             produced by pre-2.17 versions of Crypt::CBC.
641            
642             -add_header [deprecated; use -header instread]
643             Whether to add the salt and IV to the header of the output
644             cipher text.
645            
646             -regenerate_key [deprecated; use literal_key instead]
647             Whether to use a hash of the provided key to generate
648             the actual encryption key (default true)
649            
650             -prepend_iv [deprecated; use add_header instead]
651             Whether to prepend the IV to the beginning of the
652             encrypted stream (default true)
653            
654             Crypt::CBC requires three pieces of information to do its job. First
655             it needs the name of the block cipher algorithm that will encrypt or
656             decrypt the data in blocks of fixed length known as the cipher's
657             "blocksize." Second, it needs an encryption/decryption key to pass to
658             the block cipher. Third, it needs an initialization vector (IV) that
659             will be used to propagate information from one encrypted block to the
660             next. Both the key and the IV must be exactly the same length as the
661             chosen cipher's blocksize.
662            
663             Crypt::CBC can derive the key and the IV from a passphrase that you
664             provide, or can let you specify the true key and IV manually. In
665             addition, you have the option of embedding enough information to
666             regenerate the IV in a short header that is emitted at the start of
667             the encrypted stream, or outputting a headerless encryption stream. In
668             the first case, Crypt::CBC will be able to decrypt the stream given
669             just the original key or passphrase. In the second case, you will have
670             to provide the original IV as well as the key/passphrase.
671            
672             The B<-cipher> option specifies which block cipher algorithm to use to
673             encode each section of the message. This argument is optional and
674             will default to the quick-but-not-very-secure DES algorithm unless
675             specified otherwise. You may use any compatible block encryption
676             algorithm that you have installed. Currently, this includes
677             Crypt::DES, Crypt::DES_EDE3, Crypt::IDEA, Crypt::Blowfish,
678             Crypt::CAST5 and Crypt::Rijndael. You may refer to them using their
679             full names ("Crypt::IDEA") or in abbreviated form ("IDEA").
680            
681             Instead of passing the name of a cipher class, you may pass an
682             already-created block cipher object. This allows you to take advantage
683             of cipher algorithms that have parameterized new() methods, such as
684             Crypt::Eksblowfish:
685            
686             my $eksblowfish = Crypt::Eksblowfish->new(8,$salt,$key);
687             my $cbc = Crypt::CBC->new(-cipher=>$eksblowfish);
688            
689             The B<-key> argument provides either a passphrase to use to generate
690             the encryption key, or the literal value of the block cipher key. If
691             used in passphrase mode (which is the default), B<-key> can be any
692             number of characters; the actual key will be derived by passing the
693             passphrase through a series of MD5 hash operations. To take full
694             advantage of a given block cipher, the length of the passphrase should
695             be at least equal to the cipher's blocksize. To skip this hashing
696             operation and specify the key directly, pass a true value to the
697             B<-literal_key> option. In this case, you should choose a key of
698             length exactly equal to the cipher's key length. You should also
699             specify the IV yourself and a -header mode of 'none'.
700            
701             If you pass an existing Crypt::* object to new(), then the -key
702             argument is ignored and the module will generate a warning.
703            
704             The B<-header> argument specifies what type of header, if any, to
705             prepend to the beginning of the encrypted data stream. The header
706             allows Crypt::CBC to regenerate the original IV and correctly decrypt
707             the data without your having to provide the same IV used to encrypt
708             the data. Valid values for the B<-header> are:
709            
710             "salt" -- Combine the passphrase with an 8-byte random value to
711             generate both the block cipher key and the IV from the
712             provided passphrase. The salt will be appended to the
713             beginning of the data stream allowing decryption to
714             regenerate both the key and IV given the correct passphrase.
715             This method is compatible with current versions of OpenSSL.
716            
717             "randomiv" -- Generate the block cipher key from the passphrase, and
718             choose a random 8-byte value to use as the IV. The IV will
719             be prepended to the data stream. This method is compatible
720             with ciphertext produced by versions of the library prior to
721             2.17, but is incompatible with block ciphers that have non
722             8-byte block sizes, such as Rijndael. Crypt::CBC will exit
723             with a fatal error if you try to use this header mode with a
724             non 8-byte cipher.
725            
726             "none" -- Do not generate a header. To decrypt a stream encrypted
727             in this way, you will have to provide the original IV
728             manually.
729            
730             B<The "salt" header is now the default as of Crypt::CBC version 2.17. In
731             all earlier versions "randomiv" was the default.>
732            
733             When using a "salt" header, you may specify your own value of the
734             salt, by passing the desired 8-byte salt to the B<-salt>
735             argument. Otherwise, the module will generate a random salt for
736             you. Crypt::CBC will generate a fatal error if you specify a salt
737             value that isn't exactly 8 bytes long. For backward compatibility
738             reasons, passing a value of "1" will generate a random salt, the same
739             as if no B<-salt> argument was provided.
740            
741             The B<-padding> argument controls how the last few bytes of the
742             encrypted stream are dealt with when they not an exact multiple of the
743             cipher block length. The default is "standard", the method specified
744             in PKCS#5.
745            
746             The B<-pcbc> argument, if true, activates a modified chaining mode
747             known as PCBC. It provides better error propagation characteristics
748             than the default CBC encryption and is required for authenticating to
749             Kerberos4 systems (see RFC 2222).
750            
751             The B<-keysize> and B<-blocksize> arguments can be used to force the
752             cipher's keysize and/or blocksize. This is only currently useful for
753             the Crypt::Blowfish module, which accepts a variable length
754             keysize. If -keysize is not specified, then Crypt::CBC will use the
755             maximum length Blowfish key size of 56 bytes (448 bits). The Openssl
756             library defaults to 16 byte Blowfish key sizes, so for compatibility
757             with Openssl you may wish to set -keysize=>16. There are currently no
758             Crypt::* modules that have variable block sizes, but an option to
759             change the block size is provided just in case.
760            
761             For compatibility with earlier versions of this module, you can
762             provide new() with a hashref containing key/value pairs. The key names
763             are the same as the arguments described earlier, but without the
764             initial hyphen. You may also call new() with one or two positional
765             arguments, in which case the first argument is taken to be the key and
766             the second to be the optional block cipher algorithm.
767            
768             B<IMPORTANT NOTE:> Versions of this module prior to 2.17 were
769             incorrectly using 8-byte IVs when generating the "randomiv" style of
770             header, even when the chosen cipher's blocksize was greater than 8
771             bytes. This primarily affects the Rijndael algorithm. Such encrypted
772             data streams were B<not secure>. From versions 2.17 onward, Crypt::CBC
773             will refuse to encrypt or decrypt using the "randomiv" header and non-8
774             byte block ciphers. To decrypt legacy data encrypted with earlier
775             versions of the module, you can override the check using the
776             B<-insecure_legacy_decrypt> option. It is not possible to override
777             encryption. Please use the default "salt" header style, or no headers
778             at all.
779            
780             =head2 start()
781            
782             $cipher->start('encrypting');
783             $cipher->start('decrypting');
784            
785             The start() method prepares the cipher for a series of encryption or
786             decryption steps, resetting the internal state of the cipher if
787             necessary. You must provide a string indicating whether you wish to
788             encrypt or decrypt. "E" or any word that begins with an "e" indicates
789             encryption. "D" or any word that begins with a "d" indicates
790             decryption.
791            
792             =head2 crypt()
793            
794             $ciphertext = $cipher->crypt($plaintext);
795            
796             After calling start(), you should call crypt() as many times as
797             necessary to encrypt the desired data.
798            
799             =head2 finish()
800            
801             $ciphertext = $cipher->finish();
802            
803             The CBC algorithm must buffer data blocks inernally until they are
804             even multiples of the encryption algorithm's blocksize (typically 8
805             bytes). After the last call to crypt() you should call finish().
806             This flushes the internal buffer and returns any leftover ciphertext.
807            
808             In a typical application you will read the plaintext from a file or
809             input stream and write the result to standard output in a loop that
810             might look like this:
811            
812             $cipher = new Crypt::CBC('hey jude!');
813             $cipher->start('encrypting');
814             print $cipher->crypt($_) while <>;
815             print $cipher->finish();
816            
817             =head2 encrypt()
818            
819             $ciphertext = $cipher->encrypt($plaintext)
820            
821             This convenience function runs the entire sequence of start(), crypt()
822             and finish() for you, processing the provided plaintext and returning
823             the corresponding ciphertext.
824            
825             =head2 decrypt()
826            
827             $plaintext = $cipher->decrypt($ciphertext)
828            
829             This convenience function runs the entire sequence of start(), crypt()
830             and finish() for you, processing the provided ciphertext and returning
831             the corresponding plaintext.
832            
833             =head2 encrypt_hex(), decrypt_hex()
834            
835             $ciphertext = $cipher->encrypt_hex($plaintext)
836             $plaintext = $cipher->decrypt_hex($ciphertext)
837            
838             These are convenience functions that operate on ciphertext in a
839             hexadecimal representation. B<encrypt_hex($plaintext)> is exactly
840             equivalent to B<unpack('H*',encrypt($plaintext))>. These functions
841             can be useful if, for example, you wish to place the encrypted in an
842             email message.
843            
844             =head2 get_initialization_vector()
845            
846             $iv = $cipher->get_initialization_vector()
847            
848             This function will return the IV used in encryption and or decryption.
849             The IV is not guaranteed to be set when encrypting until start() is
850             called, and when decrypting until crypt() is called the first
851             time. Unless the IV was manually specified in the new() call, the IV
852             will change with every complete encryption operation.
853            
854             =head2 set_initialization_vector()
855            
856             $cipher->set_initialization_vector('76543210')
857            
858             This function sets the IV used in encryption and/or decryption. This
859             function may be useful if the IV is not contained within the
860             ciphertext string being decrypted, or if a particular IV is desired
861             for encryption. Note that the IV must match the chosen cipher's
862             blocksize bytes in length.
863            
864             =head2 iv()
865            
866             $iv = $cipher->iv();
867             $cipher->iv($new_iv);
868            
869             As above, but using a single method call.
870            
871             =head2 key()
872            
873             $key = $cipher->key();
874             $cipher->key($new_key);
875            
876             Get or set the block cipher key used for encryption/decryption. When
877             encrypting, the key is not guaranteed to exist until start() is
878             called, and when decrypting, the key is not guaranteed to exist until
879             after the first call to crypt(). The key must match the length
880             required by the underlying block cipher.
881            
882             When salted headers are used, the block cipher key will change after
883             each complete sequence of encryption operations.
884            
885             =head2 salt()
886            
887             $salt = $cipher->salt();
888             $cipher->salt($new_salt);
889            
890             Get or set the salt used for deriving the encryption key and IV when
891             in OpenSSL compatibility mode.
892            
893             =head2 passphrase()
894            
895             $passphrase = $cipher->passphrase();
896             $cipher->passphrase($new_passphrase);
897            
898             This gets or sets the value of the B<key> passed to new() when
899             B<literal_key> is false.
900            
901             =head2 $data = get_random_bytes($numbytes)
902            
903             Return $numbytes worth of random data. On systems that support the
904             "/dev/urandom" device file, this data will be read from the
905             device. Otherwise, it will be generated by repeated calls to the Perl
906             rand() function.
907            
908             =head2 cipher(), padding(), keysize(), blocksize(), pcbc()
909            
910             These read-only methods return the identity of the chosen block cipher
911             algorithm, padding method, key and block size of the chosen block
912             cipher, and whether PCBC chaining is in effect.
913            
914             =head2 Padding methods
915            
916             Use the 'padding' option to change the padding method.
917            
918             When the last block of plaintext is shorter than the block size,
919             it must be padded. Padding methods include: "standard" (i.e., PKCS#5),
920             "oneandzeroes", "space", and "null".
921            
922             standard: (default) Binary safe
923             pads with the number of bytes that should be truncated. So, if
924             blocksize is 8, then "0A0B0C" will be padded with "05", resulting
925             in "0A0B0C0505050505". If the final block is a full block of 8
926             bytes, then a whole block of "0808080808080808" is appended.
927            
928             oneandzeroes: Binary safe
929             pads with "80" followed by as many "00" necessary to fill the
930             block. If the last block is a full block and blocksize is 8, a
931             block of "8000000000000000" will be appended.
932            
933             null: text only
934             pads with as many "00" necessary to fill the block. If the last
935             block is a full block and blocksize is 8, a block of
936             "0000000000000000" will be appended.
937            
938             space: text only
939             same as "null", but with "20".
940            
941             Both the standard and oneandzeroes paddings are binary safe. The
942             space and null paddings are recommended only for text data. Which
943             type of padding you use depends on whether you wish to communicate
944             with an external (non Crypt::CBC library). If this is the case, use
945             whatever padding method is compatible.
946            
947             You can also pass in a custom padding function. To do this, create a
948             function that takes the arguments:
949            
950             $padded_block = function($block,$blocksize,$direction);
951            
952             where $block is the current block of data, $blocksize is the size to
953             pad it to, $direction is "e" for encrypting and "d" for decrypting,
954             and $padded_block is the result after padding or depadding.
955            
956             When encrypting, the function should always return a string of
957             <blocksize> length, and when decrypting, can expect the string coming
958             in to always be that length. See _standard_padding(), _space_padding(),
959             _null_padding(), or _oneandzeroes_padding() in the source for examples.
960            
961             Standard and oneandzeroes padding are recommended, as both space and
962             null padding can potentially truncate more characters than they should.
963            
964             =head1 EXAMPLES
965            
966             Two examples, des.pl and idea.pl can be found in the eg/ subdirectory
967             of the Crypt-CBC distribution. These implement command-line DES and
968             IDEA encryption algorithms.
969            
970             =head1 LIMITATIONS
971            
972             The encryption and decryption process is about a tenth the speed of
973             the equivalent SSLeay programs (compiled C). This could be improved
974             by implementing this module in C. It may also be worthwhile to
975             optimize the DES and IDEA block algorithms further.
976            
977             =head1 BUGS
978            
979             Please report them.
980            
981             =head1 AUTHOR
982            
983             Lincoln Stein, lstein@cshl.org
984            
985             This module is distributed under the ARTISTIC LICENSE using the same
986             terms as Perl itself.
987            
988             =head1 SEE ALSO
989            
990             perl(1), Crypt::DES(3), Crypt::IDEA(3), rfc2898 (PKCS#5)
991            
992             =cut
993