Import upstream version 3.04
Debian Janitor
2 years ago
0 | package Crypt::CBC; | |
1 | ||
2 | use Digest::MD5 'md5'; | |
3 | use Carp; | |
4 | use strict; | |
5 | use bytes; | |
6 | use vars qw($VERSION); | |
7 | $VERSION = '2.33'; | |
8 | ||
9 | use constant RANDOM_DEVICE => '/dev/urandom'; | |
10 | ||
11 | sub new { | |
12 | my $class = shift; | |
13 | ||
14 | my $options = {}; | |
15 | ||
16 | # hashref arguments | |
17 | if (ref $_[0] eq 'HASH') { | |
18 | $options = shift; | |
19 | } | |
20 | ||
21 | # CGI style arguments | |
22 | elsif ($_[0] =~ /^-[a-zA-Z_]{1,20}$/) { | |
23 | my %tmp = @_; | |
24 | while ( my($key,$value) = each %tmp) { | |
25 | $key =~ s/^-//; | |
26 | $options->{lc $key} = $value; | |
27 | } | |
28 | } | |
29 | ||
30 | else { | |
31 | $options->{key} = shift; | |
32 | $options->{cipher} = shift; | |
33 | } | |
34 | ||
35 | 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 | my $pass = $options->{key}; | |
40 | ||
41 | if ($cipher_object_provided) { | |
42 | carp "Both a key and a pre-initialized Crypt::* object were passed. The key will be ignored" | |
43 | if defined $pass; | |
44 | $pass ||= ''; | |
45 | } | |
46 | elsif (!defined $pass) { | |
47 | croak "Please provide an encryption/decryption passphrase or key using -key" | |
48 | } | |
49 | ||
50 | # header mode | |
51 | my %valid_modes = map {$_=>1} qw(none salt randomiv); | |
52 | my $header_mode = $options->{header}; | |
53 | $header_mode ||= 'none' if exists $options->{prepend_iv} && !$options->{prepend_iv}; | |
54 | $header_mode ||= 'none' if exists $options->{add_header} && !$options->{add_header}; | |
55 | $header_mode ||= 'salt'; # default | |
56 | croak "Invalid -header mode '$header_mode'" unless $valid_modes{$header_mode}; | |
57 | ||
58 | croak "The -salt argument is incompatible with a -header mode of $header_mode" | |
59 | if exists $options->{salt} && $header_mode ne 'salt'; | |
60 | ||
61 | my $cipher = $options->{cipher}; | |
62 | $cipher = 'Crypt::DES' unless $cipher; | |
63 | my $cipherclass = ref $cipher || $cipher; | |
64 | ||
65 | unless (ref $cipher) { # munge the class name if no object passed | |
66 | $cipher = $cipher=~/^Crypt::/ ? $cipher : "Crypt::$cipher"; | |
67 | $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 | $cipher =~ s/^Crypt::// unless $cipher->can('keysize'); | |
70 | } | |
71 | ||
72 | # allow user to override these values | |
73 | my $ks = $options->{keysize}; | |
74 | my $bs = $options->{blocksize}; | |
75 | ||
76 | # otherwise we get the values from the cipher | |
77 | $ks ||= eval {$cipher->keysize}; | |
78 | $bs ||= eval {$cipher->blocksize}; | |
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 | $ks ||= $cipherclass =~ /blowfish/i ? 56 : 8; | |
85 | $bs ||= $ks; | |
86 | ||
87 | 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 | croak "The options -literal_key and -regenerate_key are incompatible with each other" | |
92 | if exists $options->{literal_key} && exists $options->{regenerate_key}; | |
93 | my $key; | |
94 | $key = $pass if $options->{literal_key}; | |
95 | $key = $pass if exists $options->{regenerate_key} && !$options->{regenerate_key}; | |
96 | ||
97 | # Get the salt. | |
98 | my $salt = $options->{salt}; | |
99 | my $random_salt = 1 unless defined $salt && $salt ne '1'; | |
100 | croak "Argument to -salt must be exactly 8 bytes long" if defined $salt && length $salt != 8 && $salt ne '1'; | |
101 | ||
102 | # note: iv will be autogenerated by start() if not specified in options | |
103 | my $iv = $options->{iv}; | |
104 | my $random_iv = 1 unless defined $iv; | |
105 | croak "Initialization vector must be exactly $bs bytes long when using the $cipherclass cipher" if defined $iv and length($iv) != $bs; | |
106 | ||
107 | my $literal_key = $options->{literal_key} || (exists $options->{regenerate_key} && !$options->{regenerate_key}); | |
108 | my $legacy_hack = $options->{insecure_legacy_decrypt}; | |
109 | my $padding = $options->{padding} || 'standard'; | |
110 | ||
111 | if ($padding && ref($padding) eq 'CODE') { | |
112 | # check to see that this code does its padding correctly | |
113 | for my $i (1..$bs-1) { | |
114 | my $rbs = length($padding->(" "x$i,$bs,'e')); | |
115 | croak "padding method callback does not behave properly: expected $bs bytes back, got $rbs bytes back." | |
116 | unless ($rbs == $bs); | |
117 | } | |
118 | } else { | |
119 | $padding = $padding eq 'none' ? \&_no_padding | |
120 | :$padding eq 'null' ? \&_null_padding | |
121 | :$padding eq 'space' ? \&_space_padding | |
122 | :$padding eq 'oneandzeroes' ? \&_oneandzeroes_padding | |
123 | :$padding eq 'rijndael_compat'? \&_rijndael_compat | |
124 | :$padding eq 'standard' ? \&_standard_padding | |
125 | :croak "'$padding' padding not supported. See perldoc Crypt::CBC for instructions on creating your own."; | |
126 | } | |
127 | ||
128 | # CONSISTENCY CHECKS | |
129 | # HEADER consistency | |
130 | if ($header_mode eq 'salt') { | |
131 | croak "Cannot use salt-based key generation if literal key is specified" | |
132 | if $options->{literal_key}; | |
133 | croak "Cannot use salt-based IV generation if literal IV is specified" | |
134 | if exists $options->{iv}; | |
135 | } | |
136 | elsif ($header_mode eq 'randomiv') { | |
137 | croak "Cannot encrypt using a non-8 byte blocksize cipher when using randomiv header mode" | |
138 | unless $bs == 8 || $legacy_hack; | |
139 | } | |
140 | elsif ($header_mode eq 'none') { | |
141 | croak "You must provide an initialization vector using -iv when using -header=>'none'" | |
142 | unless exists $options->{iv}; | |
143 | } | |
144 | ||
145 | # KEYSIZE consistency | |
146 | if (defined $key && length($key) != $ks) { | |
147 | croak "If specified by -literal_key, then the key length must be equal to the chosen cipher's key length of $ks bytes"; | |
148 | } | |
149 | ||
150 | # IV consistency | |
151 | if (defined $iv && length($iv) != $bs) { | |
152 | croak "If specified by -iv, then the initialization vector length must be equal to the chosen cipher's blocksize of $bs bytes"; | |
153 | } | |
154 | ||
155 | ||
156 | return bless {'cipher' => $cipher, | |
157 | 'passphrase' => $pass, | |
158 | 'key' => $key, | |
159 | 'iv' => $iv, | |
160 | 'salt' => $salt, | |
161 | 'padding' => $padding, | |
162 | 'blocksize' => $bs, | |
163 | 'keysize' => $ks, | |
164 | 'header_mode' => $header_mode, | |
165 | 'legacy_hack' => $legacy_hack, | |
166 | 'literal_key' => $literal_key, | |
167 | 'pcbc' => $pcbc, | |
168 | 'make_random_salt' => $random_salt, | |
169 | 'make_random_iv' => $random_iv, | |
170 | },$class; | |
171 | } | |
172 | ||
173 | sub encrypt (\$$) { | |
174 | my ($self,$data) = @_; | |
175 | $self->start('encrypting'); | |
176 | my $result = $self->crypt($data); | |
177 | $result .= $self->finish; | |
178 | $result; | |
179 | } | |
180 | ||
181 | sub decrypt (\$$){ | |
182 | my ($self,$data) = @_; | |
183 | $self->start('decrypting'); | |
184 | my $result = $self->crypt($data); | |
185 | $result .= $self->finish; | |
186 | $result; | |
187 | } | |
188 | ||
189 | sub encrypt_hex (\$$) { | |
190 | my ($self,$data) = @_; | |
191 | return join('',unpack 'H*',$self->encrypt($data)); | |
192 | } | |
193 | ||
194 | sub decrypt_hex (\$$) { | |
195 | my ($self,$data) = @_; | |
196 | return $self->decrypt(pack'H*',$data); | |
197 | } | |
198 | ||
199 | # call to start a series of encryption/decryption operations | |
200 | sub start (\$$) { | |
201 | my $self = shift; | |
202 | my $operation = shift; | |
203 | croak "Specify <e>ncryption or <d>ecryption" unless $operation=~/^[ed]/i; | |
204 | ||
205 | $self->{'buffer'} = ''; | |
206 | $self->{'decrypt'} = $operation=~/^d/i; | |
207 | } | |
208 | ||
209 | # call to encrypt/decrypt a bit of data | |
210 | sub crypt (\$$){ | |
211 | my $self = shift; | |
212 | my $data = shift; | |
213 | ||
214 | my $result; | |
215 | ||
216 | croak "crypt() called without a preceding start()" | |
217 | unless exists $self->{'buffer'}; | |
218 | ||
219 | my $d = $self->{'decrypt'}; | |
220 | ||
221 | unless ($self->{civ}) { # block cipher has not yet been initialized | |
222 | $result = $self->_generate_iv_and_cipher_from_datastream(\$data) if $d; | |
223 | $result = $self->_generate_iv_and_cipher_from_options() unless $d; | |
224 | } | |
225 | ||
226 | my $iv = $self->{'civ'}; | |
227 | $self->{'buffer'} .= $data; | |
228 | ||
229 | my $bs = $self->{'blocksize'}; | |
230 | ||
231 | croak "When using no padding, plaintext size must be a multiple of $bs" | |
232 | if $self->{'padding'} eq \&_no_padding | |
233 | and length($data) % $bs; | |
234 | ||
235 | croak "When using rijndael_compat padding, plaintext size must be a multiple of $bs" | |
236 | if $self->{'padding'} eq \&_rijndael_compat | |
237 | and length($data) % $bs; | |
238 | ||
239 | return $result unless (length($self->{'buffer'}) >= $bs); | |
240 | ||
241 | my @blocks = unpack("a$bs "x(int(length($self->{'buffer'})/$bs)) . "a*", $self->{'buffer'}); | |
242 | $self->{'buffer'} = ''; | |
243 | ||
244 | if ($d) { # when decrypting, always leave a free block at the end | |
245 | $self->{'buffer'} = length($blocks[-1]) < $bs ? join '',splice(@blocks,-2) : pop(@blocks); | |
246 | } else { | |
247 | $self->{'buffer'} = pop @blocks if length($blocks[-1]) < $bs; # what's left over | |
248 | } | |
249 | ||
250 | foreach my $block (@blocks) { | |
251 | if ($d) { # decrypting | |
252 | $result .= $iv = $iv ^ $self->{'crypt'}->decrypt($block); | |
253 | $iv = $block unless $self->{pcbc}; | |
254 | } else { # encrypting | |
255 | $result .= $iv = $self->{'crypt'}->encrypt($iv ^ $block); | |
256 | } | |
257 | $iv = $iv ^ $block if $self->{pcbc}; | |
258 | } | |
259 | $self->{'civ'} = $iv; # remember the iv | |
260 | return $result; | |
261 | } | |
262 | ||
263 | # this is called at the end to flush whatever's left | |
264 | sub finish (\$) { | |
265 | my $self = shift; | |
266 | my $bs = $self->{'blocksize'}; | |
267 | my $block = defined $self->{'buffer'} ? $self->{'buffer'} : ''; | |
268 | ||
269 | $self->{civ} ||= ''; | |
270 | ||
271 | my $result; | |
272 | if ($self->{'decrypt'}) { #decrypting | |
273 | $block = length $block ? pack("a$bs",$block) : ''; # pad and truncate to block size | |
274 | ||
275 | if (length($block)) { | |
276 | $result = $self->{'civ'} ^ $self->{'crypt'}->decrypt($block); | |
277 | $result = $self->{'padding'}->($result, $bs, 'd'); | |
278 | } else { | |
279 | $result = ''; | |
280 | } | |
281 | ||
282 | } else { # encrypting | |
283 | $block = $self->{'padding'}->($block,$bs,'e') || ''; | |
284 | $result = length $block ? $self->{'crypt'}->encrypt($self->{'civ'} ^ $block) : ''; | |
285 | } | |
286 | delete $self->{'civ'}; | |
287 | delete $self->{'buffer'}; | |
288 | return $result; | |
289 | } | |
290 | ||
291 | # this subroutine will generate the actual {en,de}cryption key, the iv | |
292 | # and the block cipher object. This is called when reading from a datastream | |
293 | # and so it uses previous values of salt or iv if they are encoded in datastream | |
294 | # header | |
295 | sub _generate_iv_and_cipher_from_datastream { | |
296 | my $self = shift; | |
297 | my $input_stream = shift; | |
298 | my $bs = $self->blocksize; | |
299 | ||
300 | # use our header mode to figure out what to do with the data stream | |
301 | my $header_mode = $self->header_mode; | |
302 | ||
303 | if ($header_mode eq 'none') { | |
304 | croak "You must specify a $bs byte initialization vector by passing the -iv option to new() when using -header_mode=>'none'" | |
305 | unless exists $self->{iv}; | |
306 | $self->{civ} = $self->{iv}; # current IV equals saved IV | |
307 | $self->{key} ||= $self->_key_from_key($self->{passphrase}); | |
308 | } | |
309 | ||
310 | elsif ($header_mode eq 'salt') { | |
311 | my ($salt) = $$input_stream =~ /^Salted__(.{8})/s; | |
312 | croak "Ciphertext does not begin with a valid header for 'salt' header mode" unless defined $salt; | |
313 | $self->{salt} = $salt; # new salt | |
314 | substr($$input_stream,0,16) = ''; | |
315 | my ($key,$iv) = $self->_salted_key_and_iv($self->{passphrase},$salt); | |
316 | $self->{iv} = $self->{civ} = $iv; | |
317 | $self->{key} = $key; | |
318 | } | |
319 | ||
320 | elsif ($header_mode eq 'randomiv') { | |
321 | my ($iv) = $$input_stream =~ /^RandomIV(.{8})/s; | |
322 | croak "Ciphertext does not begin with a valid header for 'randomiv' header mode" unless defined $iv; | |
323 | 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; | |
324 | $self->{iv} = $self->{civ} = $iv; | |
325 | $self->{key} = $self->_key_from_key($self->{passphrase}); | |
326 | undef $self->{salt}; # paranoia | |
327 | substr($$input_stream,0,16) = ''; # truncate | |
328 | } | |
329 | ||
330 | else { | |
331 | croak "Invalid header mode '$header_mode'"; | |
332 | } | |
333 | ||
334 | # we should have the key and iv now, or we are dead in the water | |
335 | croak "Cipher stream did not contain IV or salt, and you did not specify these values in new()" | |
336 | unless $self->{key} && $self->{civ}; | |
337 | ||
338 | # now we can generate the crypt object itself | |
339 | $self->{crypt} = ref $self->{cipher} ? $self->{cipher} | |
340 | : $self->{cipher}->new($self->{key}) | |
341 | or croak "Could not create $self->{cipher} object: $@"; | |
342 | return ''; | |
343 | } | |
344 | ||
345 | sub _generate_iv_and_cipher_from_options { | |
346 | my $self = shift; | |
347 | my $blocksize = $self->blocksize; | |
348 | ||
349 | my $result = ''; | |
350 | ||
351 | my $header_mode = $self->header_mode; | |
352 | if ($header_mode eq 'none') { | |
353 | croak "You must specify a $blocksize byte initialization vector by passing the -iv option to new() when using -header_mode=>'none'" | |
354 | unless exists $self->{iv}; | |
355 | $self->{civ} = $self->{iv}; | |
356 | $self->{key} ||= $self->_key_from_key($self->{passphrase}); | |
357 | } | |
358 | ||
359 | elsif ($header_mode eq 'salt') { | |
360 | $self->{salt} = $self->_get_random_bytes(8) if $self->{make_random_salt}; | |
361 | defined (my $salt = $self->{salt}) or croak "No header_mode of 'salt' specified, but no salt value provided"; # shouldn't happen | |
362 | length($salt) == 8 or croak "Salt must be exactly 8 bytes long"; | |
363 | my ($key,$iv) = $self->_salted_key_and_iv($self->{passphrase},$salt); | |
364 | $self->{key} = $key; | |
365 | $self->{civ} = $self->{iv} = $iv; | |
366 | $result = "Salted__${salt}"; | |
367 | } | |
368 | ||
369 | elsif ($header_mode eq 'randomiv') { | |
370 | croak "randomiv header mode cannot be used when encrypting with a >8 byte block cipher. There is no option to allow this" | |
371 | unless $blocksize == 8; | |
372 | $self->{key} ||= $self->_key_from_key($self->{passphrase}); | |
373 | $self->{iv} = $self->_get_random_bytes(8) if $self->{make_random_iv}; | |
374 | length($self->{iv}) == 8 or croak "IV must be exactly 8 bytes long when used with header mode of 'randomiv'"; | |
375 | $self->{civ} = $self->{iv}; | |
376 | $result = "RandomIV$self->{iv}"; | |
377 | } | |
378 | ||
379 | croak "key and/or iv are missing" unless defined $self->{key} && defined $self->{civ}; | |
380 | ||
381 | $self->_taintcheck($self->{key}); | |
382 | $self->{crypt} = ref $self->{cipher} ? $self->{cipher} | |
383 | : $self->{cipher}->new($self->{key}) | |
384 | or croak "Could not create $self->{cipher} object: $@"; | |
385 | return $result; | |
386 | } | |
387 | ||
388 | sub _taintcheck { | |
389 | my $self = shift; | |
390 | my $key = shift; | |
391 | return unless ${^TAINT}; | |
392 | ||
393 | my $has_scalar_util = eval "require Scalar::Util; 1"; | |
394 | my $tainted; | |
395 | ||
396 | ||
397 | if ($has_scalar_util) { | |
398 | $tainted = Scalar::Util::tainted($key); | |
399 | } else { | |
400 | local($@, $SIG{__DIE__}, $SIG{__WARN__}); | |
401 | local $^W = 0; | |
402 | eval { kill 0 * $key }; | |
403 | $tainted = $@ =~ /^Insecure/; | |
404 | } | |
405 | ||
406 | croak "Taint checks are turned on and your key is tainted. Please untaint the key and try again" | |
407 | if $tainted; | |
408 | } | |
409 | ||
410 | sub _key_from_key { | |
411 | my $self = shift; | |
412 | my $pass = shift; | |
413 | my $ks = $self->{keysize}; | |
414 | ||
415 | return $pass if $self->{literal_key}; | |
416 | ||
417 | my $material = md5($pass); | |
418 | while (length($material) < $ks) { | |
419 | $material .= md5($material); | |
420 | } | |
421 | return substr($material,0,$ks); | |
422 | } | |
423 | ||
424 | sub _salted_key_and_iv { | |
425 | my $self = shift; | |
426 | my ($pass,$salt) = @_; | |
427 | ||
428 | croak "Salt must be 8 bytes long" unless length $salt == 8; | |
429 | ||
430 | my $key_len = $self->{keysize}; | |
431 | my $iv_len = $self->{blocksize}; | |
432 | ||
433 | my $desired_len = $key_len+$iv_len; | |
434 | ||
435 | my $data = ''; | |
436 | my $d = ''; | |
437 | ||
438 | while (length $data < $desired_len) { | |
439 | $d = md5($d . $pass . $salt); | |
440 | $data .= $d; | |
441 | } | |
442 | return (substr($data,0,$key_len),substr($data,$key_len,$iv_len)); | |
443 | } | |
444 | ||
445 | sub random_bytes { | |
446 | my $self = shift; | |
447 | my $bytes = shift or croak "usage: random_bytes(\$byte_length)"; | |
448 | $self->_get_random_bytes($bytes); | |
449 | } | |
450 | ||
451 | sub _get_random_bytes { | |
452 | my $self = shift; | |
453 | my $length = shift; | |
454 | my $result; | |
455 | ||
456 | if (-r RANDOM_DEVICE && open(F,RANDOM_DEVICE)) { | |
457 | read(F,$result,$length); | |
458 | close F; | |
459 | } else { | |
460 | $result = pack("C*",map {rand(256)} 1..$length); | |
461 | } | |
462 | # Clear taint and check length | |
463 | $result =~ /^(.+)$/s; | |
464 | length($1) == $length or croak "Invalid length while gathering $length random bytes"; | |
465 | return $1; | |
466 | } | |
467 | ||
468 | sub _standard_padding ($$$) { | |
469 | my ($b,$bs,$decrypt) = @_; | |
470 | $b = length $b ? $b : ''; | |
471 | if ($decrypt eq 'd') { | |
472 | my $pad_length = unpack("C",substr($b,-1)); | |
473 | ||
474 | # sanity check for implementations that don't pad correctly | |
475 | return $b unless $pad_length >= 0 && $pad_length <= $bs; | |
476 | my @pad_chars = unpack("C*",substr($b,-$pad_length)); | |
477 | return $b if grep {$pad_length != $_} @pad_chars; | |
478 | ||
479 | return substr($b,0,$bs-$pad_length); | |
480 | } | |
481 | my $pad = $bs - length($b) % $bs; | |
482 | return $b . pack("C*",($pad)x$pad); | |
483 | } | |
484 | ||
485 | sub _space_padding ($$$) { | |
486 | my ($b,$bs,$decrypt) = @_; | |
487 | return unless length $b; | |
488 | $b = length $b ? $b : ''; | |
489 | if ($decrypt eq 'd') { | |
490 | $b=~ s/ *\z//s; | |
491 | return $b; | |
492 | } | |
493 | return $b . pack("C*", (32) x ($bs - length($b) % $bs)); | |
494 | } | |
495 | ||
496 | sub _no_padding ($$$) { | |
497 | my ($b,$bs,$decrypt) = @_; | |
498 | return $b; | |
499 | } | |
500 | ||
501 | sub _null_padding ($$$) { | |
502 | my ($b,$bs,$decrypt) = @_; | |
503 | return unless length $b; | |
504 | $b = length $b ? $b : ''; | |
505 | if ($decrypt eq 'd') { | |
506 | $b=~ s/\0*\z//s; | |
507 | return $b; | |
508 | } | |
509 | return $b . pack("C*", (0) x ($bs - length($b) % $bs)); | |
510 | } | |
511 | ||
512 | sub _oneandzeroes_padding ($$$) { | |
513 | my ($b,$bs,$decrypt) = @_; | |
514 | $b = length $b ? $b : ''; | |
515 | if ($decrypt eq 'd') { | |
516 | $b=~ s/\x80\0*\z//s; | |
517 | return $b; | |
518 | } | |
519 | return $b . pack("C*", 128, (0) x ($bs - length($b) % $bs - 1) ); | |
520 | } | |
521 | ||
522 | sub _rijndael_compat ($$$) { | |
523 | my ($b,$bs,$decrypt) = @_; | |
524 | return unless length $b; | |
525 | if ($decrypt eq 'd') { | |
526 | $b=~ s/\x80\0*\z//s; | |
527 | return $b; | |
528 | } | |
529 | return $b . pack("C*", 128, (0) x ($bs - length($b) % $bs - 1) ); | |
530 | } | |
531 | ||
532 | sub get_initialization_vector (\$) { | |
533 | my $self = shift; | |
534 | $self->iv(); | |
535 | } | |
536 | ||
537 | sub set_initialization_vector (\$$) { | |
538 | my $self = shift; | |
539 | my $iv = shift; | |
540 | my $bs = $self->blocksize; | |
541 | croak "Initialization vector must be $bs bytes in length" unless length($iv) == $bs; | |
542 | $self->iv($iv); | |
543 | } | |
544 | ||
545 | sub salt { | |
546 | my $self = shift; | |
547 | my $d = $self->{salt}; | |
548 | $self->{salt} = shift if @_; | |
549 | $d; | |
550 | } | |
551 | ||
552 | sub iv { | |
553 | my $self = shift; | |
554 | my $d = $self->{iv}; | |
555 | $self->{iv} = shift if @_; | |
556 | $d; | |
557 | } | |
558 | ||
559 | sub key { | |
560 | my $self = shift; | |
561 | my $d = $self->{key}; | |
562 | $self->{key} = shift if @_; | |
563 | $d; | |
564 | } | |
565 | ||
566 | sub passphrase { | |
567 | my $self = shift; | |
568 | my $d = $self->{passphrase}; | |
569 | if (@_) { | |
570 | undef $self->{key}; | |
571 | undef $self->{iv}; | |
572 | $self->{passphrase} = shift; | |
573 | } | |
574 | $d; | |
575 | } | |
576 | ||
577 | sub cipher { shift->{cipher} } | |
578 | sub padding { shift->{padding} } | |
579 | sub keysize { shift->{keysize} } | |
580 | sub blocksize { shift->{blocksize} } | |
581 | sub pcbc { shift->{pcbc} } | |
582 | sub header_mode {shift->{header_mode} } | |
583 | sub legacy_hack { shift->{legacy_hack} } | |
584 | ||
585 | 1; | |
586 | __END__ | |
587 | ||
588 | =head1 NAME | |
589 | ||
590 | Crypt::CBC - Encrypt Data with Cipher Block Chaining Mode | |
591 | ||
592 | =head1 SYNOPSIS | |
593 | ||
594 | use Crypt::CBC; | |
595 | $cipher = Crypt::CBC->new( -key => 'my secret key', | |
596 | -cipher => 'Blowfish' | |
597 | ); | |
598 | ||
599 | $ciphertext = $cipher->encrypt("This data is hush hush"); | |
600 | $plaintext = $cipher->decrypt($ciphertext); | |
601 | ||
602 | $cipher->start('encrypting'); | |
603 | open(F,"./BIG_FILE"); | |
604 | while (read(F,$buffer,1024)) { | |
605 | print $cipher->crypt($buffer); | |
606 | } | |
607 | print $cipher->finish; | |
608 | ||
609 | # do-it-yourself mode -- specify key, initialization vector yourself | |
610 | $key = Crypt::CBC->random_bytes(8); # assuming a 8-byte block cipher | |
611 | $iv = Crypt::CBC->random_bytes(8); | |
612 | $cipher = Crypt::CBC->new(-literal_key => 1, | |
613 | -key => $key, | |
614 | -iv => $iv, | |
615 | -header => 'none'); | |
616 | ||
617 | $ciphertext = $cipher->encrypt("This data is hush hush"); | |
618 | $plaintext = $cipher->decrypt($ciphertext); | |
619 | ||
620 | # RANDOMIV-compatible mode | |
621 | $cipher = Crypt::CBC->new(-key => 'Super Secret!' | |
622 | -header => 'randomiv'); | |
623 | ||
624 | ||
625 | =head1 DESCRIPTION | |
626 | ||
627 | This module is a Perl-only implementation of the cryptographic cipher | |
628 | block chaining mode (CBC). In combination with a block cipher such as | |
629 | DES or IDEA, you can encrypt and decrypt messages of arbitrarily long | |
630 | length. The encrypted messages are compatible with the encryption | |
631 | format used by the B<OpenSSL> package. | |
632 | ||
633 | To use this module, you will first create a Crypt::CBC cipher object | |
634 | with new(). At the time of cipher creation, you specify an encryption | |
635 | key to use and, optionally, a block encryption algorithm. You will | |
636 | then call the start() method to initialize the encryption or | |
637 | decryption process, crypt() to encrypt or decrypt one or more blocks | |
638 | of data, and lastly finish(), to pad and encrypt the final block. For | |
639 | your convenience, you can call the encrypt() and decrypt() methods to | |
640 | operate on a whole data value at once. | |
641 | ||
642 | =head2 new() | |
643 | ||
644 | $cipher = Crypt::CBC->new( -key => 'my secret key', | |
645 | -cipher => 'Blowfish', | |
646 | ); | |
647 | ||
648 | # or (for compatibility with versions prior to 2.13) | |
649 | $cipher = Crypt::CBC->new( { | |
650 | key => 'my secret key', | |
651 | cipher => 'Blowfish' | |
652 | } | |
653 | ); | |
654 | ||
655 | ||
656 | # or (for compatibility with versions prior to 2.0) | |
657 | $cipher = new Crypt::CBC('my secret key' => 'Blowfish'); | |
658 | ||
659 | The new() method creates a new Crypt::CBC object. It accepts a list of | |
660 | -argument => value pairs selected from the following list: | |
661 | ||
662 | Argument Description | |
663 | -------- ----------- | |
664 | ||
665 | -key The encryption/decryption key (required) | |
666 | ||
667 | -cipher The cipher algorithm (defaults to Crypt::DES), or | |
668 | a preexisting cipher object. | |
669 | ||
670 | -salt Enables OpenSSL-compatibility. If equal to a value | |
671 | of "1" then causes a random salt to be generated | |
672 | and used to derive the encryption key and IV. Other | |
673 | true values are taken to be the literal salt. | |
674 | ||
675 | -iv The initialization vector (IV) | |
676 | ||
677 | -header What type of header to prepend to ciphertext. One of | |
678 | 'salt' -- use OpenSSL-compatible salted header | |
679 | 'randomiv' -- Randomiv-compatible "RandomIV" header | |
680 | 'none' -- prepend no header at all | |
681 | ||
682 | -padding The padding method, one of "standard" (default), | |
683 | "space", "oneandzeroes", "rijndael_compat", | |
684 | "null", or "none" (default "standard"). | |
685 | ||
686 | -literal_key If true, the key provided by "key" is used directly | |
687 | for encryption/decryption. Otherwise the actual | |
688 | key used will be a hash of the provided key. | |
689 | (default false) | |
690 | ||
691 | -pcbc Whether to use the PCBC chaining algorithm rather than | |
692 | the standard CBC algorithm (default false). | |
693 | ||
694 | -keysize Force the cipher keysize to the indicated number of bytes. | |
695 | ||
696 | -blocksize Force the cipher blocksize to the indicated number of bytes. | |
697 | ||
698 | -insecure_legacy_decrypt | |
699 | Allow decryption of data encrypted using the "RandomIV" header | |
700 | produced by pre-2.17 versions of Crypt::CBC. | |
701 | ||
702 | -add_header [deprecated; use -header instread] | |
703 | Whether to add the salt and IV to the header of the output | |
704 | cipher text. | |
705 | ||
706 | -regenerate_key [deprecated; use literal_key instead] | |
707 | Whether to use a hash of the provided key to generate | |
708 | the actual encryption key (default true) | |
709 | ||
710 | -prepend_iv [deprecated; use add_header instead] | |
711 | Whether to prepend the IV to the beginning of the | |
712 | encrypted stream (default true) | |
713 | ||
714 | Crypt::CBC requires three pieces of information to do its job. First | |
715 | it needs the name of the block cipher algorithm that will encrypt or | |
716 | decrypt the data in blocks of fixed length known as the cipher's | |
717 | "blocksize." Second, it needs an encryption/decryption key to pass to | |
718 | the block cipher. Third, it needs an initialization vector (IV) that | |
719 | will be used to propagate information from one encrypted block to the | |
720 | next. Both the key and the IV must be exactly the same length as the | |
721 | chosen cipher's blocksize. | |
722 | ||
723 | Crypt::CBC can derive the key and the IV from a passphrase that you | |
724 | provide, or can let you specify the true key and IV manually. In | |
725 | addition, you have the option of embedding enough information to | |
726 | regenerate the IV in a short header that is emitted at the start of | |
727 | the encrypted stream, or outputting a headerless encryption stream. In | |
728 | the first case, Crypt::CBC will be able to decrypt the stream given | |
729 | just the original key or passphrase. In the second case, you will have | |
730 | to provide the original IV as well as the key/passphrase. | |
731 | ||
732 | The B<-cipher> option specifies which block cipher algorithm to use to | |
733 | encode each section of the message. This argument is optional and | |
734 | will default to the quick-but-not-very-secure DES algorithm unless | |
735 | specified otherwise. You may use any compatible block encryption | |
736 | algorithm that you have installed. Currently, this includes | |
737 | Crypt::DES, Crypt::DES_EDE3, Crypt::IDEA, Crypt::Blowfish, | |
738 | Crypt::CAST5 and Crypt::Rijndael. You may refer to them using their | |
739 | full names ("Crypt::IDEA") or in abbreviated form ("IDEA"). | |
740 | ||
741 | Instead of passing the name of a cipher class, you may pass an | |
742 | already-created block cipher object. This allows you to take advantage | |
743 | of cipher algorithms that have parameterized new() methods, such as | |
744 | Crypt::Eksblowfish: | |
745 | ||
746 | my $eksblowfish = Crypt::Eksblowfish->new(8,$salt,$key); | |
747 | my $cbc = Crypt::CBC->new(-cipher=>$eksblowfish); | |
748 | ||
749 | The B<-key> argument provides either a passphrase to use to generate | |
750 | the encryption key, or the literal value of the block cipher key. If | |
751 | used in passphrase mode (which is the default), B<-key> can be any | |
752 | number of characters; the actual key will be derived by passing the | |
753 | passphrase through a series of MD5 hash operations. To take full | |
754 | advantage of a given block cipher, the length of the passphrase should | |
755 | be at least equal to the cipher's blocksize. To skip this hashing | |
756 | operation and specify the key directly, pass a true value to the | |
757 | B<-literal_key> option. In this case, you should choose a key of | |
758 | length exactly equal to the cipher's key length. You should also | |
759 | specify the IV yourself and a -header mode of 'none'. | |
760 | ||
761 | If you pass an existing Crypt::* object to new(), then the -key | |
762 | argument is ignored and the module will generate a warning. | |
763 | ||
764 | The B<-header> argument specifies what type of header, if any, to | |
765 | prepend to the beginning of the encrypted data stream. The header | |
766 | allows Crypt::CBC to regenerate the original IV and correctly decrypt | |
767 | the data without your having to provide the same IV used to encrypt | |
768 | the data. Valid values for the B<-header> are: | |
769 | ||
770 | "salt" -- Combine the passphrase with an 8-byte random value to | |
771 | generate both the block cipher key and the IV from the | |
772 | provided passphrase. The salt will be appended to the | |
773 | beginning of the data stream allowing decryption to | |
774 | regenerate both the key and IV given the correct passphrase. | |
775 | This method is compatible with current versions of OpenSSL. | |
776 | ||
777 | "randomiv" -- Generate the block cipher key from the passphrase, and | |
778 | choose a random 8-byte value to use as the IV. The IV will | |
779 | be prepended to the data stream. This method is compatible | |
780 | with ciphertext produced by versions of the library prior to | |
781 | 2.17, but is incompatible with block ciphers that have non | |
782 | 8-byte block sizes, such as Rijndael. Crypt::CBC will exit | |
783 | with a fatal error if you try to use this header mode with a | |
784 | non 8-byte cipher. | |
785 | ||
786 | "none" -- Do not generate a header. To decrypt a stream encrypted | |
787 | in this way, you will have to provide the original IV | |
788 | manually. | |
789 | ||
790 | B<The "salt" header is now the default as of Crypt::CBC version 2.17. In | |
791 | all earlier versions "randomiv" was the default.> | |
792 | ||
793 | When using a "salt" header, you may specify your own value of the | |
794 | salt, by passing the desired 8-byte salt to the B<-salt> | |
795 | argument. Otherwise, the module will generate a random salt for | |
796 | you. Crypt::CBC will generate a fatal error if you specify a salt | |
797 | value that isn't exactly 8 bytes long. For backward compatibility | |
798 | reasons, passing a value of "1" will generate a random salt, the same | |
799 | as if no B<-salt> argument was provided. | |
800 | ||
801 | The B<-padding> argument controls how the last few bytes of the | |
802 | encrypted stream are dealt with when they not an exact multiple of the | |
803 | cipher block length. The default is "standard", the method specified | |
804 | in PKCS#5. | |
805 | ||
806 | The B<-pcbc> argument, if true, activates a modified chaining mode | |
807 | known as PCBC. It provides better error propagation characteristics | |
808 | than the default CBC encryption and is required for authenticating to | |
809 | Kerberos4 systems (see RFC 2222). | |
810 | ||
811 | The B<-keysize> and B<-blocksize> arguments can be used to force the | |
812 | cipher's keysize and/or blocksize. This is only currently useful for | |
813 | the Crypt::Blowfish module, which accepts a variable length | |
814 | keysize. If -keysize is not specified, then Crypt::CBC will use the | |
815 | maximum length Blowfish key size of 56 bytes (448 bits). The Openssl | |
816 | library defaults to 16 byte Blowfish key sizes, so for compatibility | |
817 | with Openssl you may wish to set -keysize=>16. There are currently no | |
818 | Crypt::* modules that have variable block sizes, but an option to | |
819 | change the block size is provided just in case. | |
820 | ||
821 | For compatibility with earlier versions of this module, you can | |
822 | provide new() with a hashref containing key/value pairs. The key names | |
823 | are the same as the arguments described earlier, but without the | |
824 | initial hyphen. You may also call new() with one or two positional | |
825 | arguments, in which case the first argument is taken to be the key and | |
826 | the second to be the optional block cipher algorithm. | |
827 | ||
828 | B<IMPORTANT NOTE:> Versions of this module prior to 2.17 were | |
829 | incorrectly using 8-byte IVs when generating the "randomiv" style of | |
830 | header, even when the chosen cipher's blocksize was greater than 8 | |
831 | bytes. This primarily affects the Rijndael algorithm. Such encrypted | |
832 | data streams were B<not secure>. From versions 2.17 onward, Crypt::CBC | |
833 | will refuse to encrypt or decrypt using the "randomiv" header and non-8 | |
834 | byte block ciphers. To decrypt legacy data encrypted with earlier | |
835 | versions of the module, you can override the check using the | |
836 | B<-insecure_legacy_decrypt> option. It is not possible to override | |
837 | encryption. Please use the default "salt" header style, or no headers | |
838 | at all. | |
839 | ||
840 | =head2 start() | |
841 | ||
842 | $cipher->start('encrypting'); | |
843 | $cipher->start('decrypting'); | |
844 | ||
845 | The start() method prepares the cipher for a series of encryption or | |
846 | decryption steps, resetting the internal state of the cipher if | |
847 | necessary. You must provide a string indicating whether you wish to | |
848 | encrypt or decrypt. "E" or any word that begins with an "e" indicates | |
849 | encryption. "D" or any word that begins with a "d" indicates | |
850 | decryption. | |
851 | ||
852 | =head2 crypt() | |
853 | ||
854 | $ciphertext = $cipher->crypt($plaintext); | |
855 | ||
856 | After calling start(), you should call crypt() as many times as | |
857 | necessary to encrypt the desired data. | |
858 | ||
859 | =head2 finish() | |
860 | ||
861 | $ciphertext = $cipher->finish(); | |
862 | ||
863 | The CBC algorithm must buffer data blocks internally until they are | |
864 | even multiples of the encryption algorithm's blocksize (typically 8 | |
865 | bytes). After the last call to crypt() you should call finish(). | |
866 | This flushes the internal buffer and returns any leftover ciphertext. | |
867 | ||
868 | In a typical application you will read the plaintext from a file or | |
869 | input stream and write the result to standard output in a loop that | |
870 | might look like this: | |
871 | ||
872 | $cipher = new Crypt::CBC('hey jude!'); | |
873 | $cipher->start('encrypting'); | |
874 | print $cipher->crypt($_) while <>; | |
875 | print $cipher->finish(); | |
876 | ||
877 | =head2 encrypt() | |
878 | ||
879 | $ciphertext = $cipher->encrypt($plaintext) | |
880 | ||
881 | This convenience function runs the entire sequence of start(), crypt() | |
882 | and finish() for you, processing the provided plaintext and returning | |
883 | the corresponding ciphertext. | |
884 | ||
885 | =head2 decrypt() | |
886 | ||
887 | $plaintext = $cipher->decrypt($ciphertext) | |
888 | ||
889 | This convenience function runs the entire sequence of start(), crypt() | |
890 | and finish() for you, processing the provided ciphertext and returning | |
891 | the corresponding plaintext. | |
892 | ||
893 | =head2 encrypt_hex(), decrypt_hex() | |
894 | ||
895 | $ciphertext = $cipher->encrypt_hex($plaintext) | |
896 | $plaintext = $cipher->decrypt_hex($ciphertext) | |
897 | ||
898 | These are convenience functions that operate on ciphertext in a | |
899 | hexadecimal representation. B<encrypt_hex($plaintext)> is exactly | |
900 | equivalent to B<unpack('H*',encrypt($plaintext))>. These functions | |
901 | can be useful if, for example, you wish to place the encrypted in an | |
902 | email message. | |
903 | ||
904 | =head2 get_initialization_vector() | |
905 | ||
906 | $iv = $cipher->get_initialization_vector() | |
907 | ||
908 | This function will return the IV used in encryption and or decryption. | |
909 | The IV is not guaranteed to be set when encrypting until start() is | |
910 | called, and when decrypting until crypt() is called the first | |
911 | time. Unless the IV was manually specified in the new() call, the IV | |
912 | will change with every complete encryption operation. | |
913 | ||
914 | =head2 set_initialization_vector() | |
915 | ||
916 | $cipher->set_initialization_vector('76543210') | |
917 | ||
918 | This function sets the IV used in encryption and/or decryption. This | |
919 | function may be useful if the IV is not contained within the | |
920 | ciphertext string being decrypted, or if a particular IV is desired | |
921 | for encryption. Note that the IV must match the chosen cipher's | |
922 | blocksize bytes in length. | |
923 | ||
924 | =head2 iv() | |
925 | ||
926 | $iv = $cipher->iv(); | |
927 | $cipher->iv($new_iv); | |
928 | ||
929 | As above, but using a single method call. | |
930 | ||
931 | =head2 key() | |
932 | ||
933 | $key = $cipher->key(); | |
934 | $cipher->key($new_key); | |
935 | ||
936 | Get or set the block cipher key used for encryption/decryption. When | |
937 | encrypting, the key is not guaranteed to exist until start() is | |
938 | called, and when decrypting, the key is not guaranteed to exist until | |
939 | after the first call to crypt(). The key must match the length | |
940 | required by the underlying block cipher. | |
941 | ||
942 | When salted headers are used, the block cipher key will change after | |
943 | each complete sequence of encryption operations. | |
944 | ||
945 | =head2 salt() | |
946 | ||
947 | $salt = $cipher->salt(); | |
948 | $cipher->salt($new_salt); | |
949 | ||
950 | Get or set the salt used for deriving the encryption key and IV when | |
951 | in OpenSSL compatibility mode. | |
952 | ||
953 | =head2 passphrase() | |
954 | ||
955 | $passphrase = $cipher->passphrase(); | |
956 | $cipher->passphrase($new_passphrase); | |
957 | ||
958 | This gets or sets the value of the B<key> passed to new() when | |
959 | B<literal_key> is false. | |
960 | ||
961 | =head2 $data = random_bytes($numbytes) | |
962 | ||
963 | Return $numbytes worth of random data. On systems that support the | |
964 | "/dev/urandom" device file, this data will be read from the | |
965 | device. Otherwise, it will be generated by repeated calls to the Perl | |
966 | rand() function. | |
967 | ||
968 | =head2 cipher(), padding(), keysize(), blocksize(), pcbc() | |
969 | ||
970 | These read-only methods return the identity of the chosen block cipher | |
971 | algorithm, padding method, key and block size of the chosen block | |
972 | cipher, and whether PCBC chaining is in effect. | |
973 | ||
974 | =head2 Padding methods | |
975 | ||
976 | Use the 'padding' option to change the padding method. | |
977 | ||
978 | When the last block of plaintext is shorter than the block size, | |
979 | it must be padded. Padding methods include: "standard" (i.e., PKCS#5), | |
980 | "oneandzeroes", "space", "rijndael_compat", "null", and "none". | |
981 | ||
982 | standard: (default) Binary safe | |
983 | pads with the number of bytes that should be truncated. So, if | |
984 | blocksize is 8, then "0A0B0C" will be padded with "05", resulting | |
985 | in "0A0B0C0505050505". If the final block is a full block of 8 | |
986 | bytes, then a whole block of "0808080808080808" is appended. | |
987 | ||
988 | oneandzeroes: Binary safe | |
989 | pads with "80" followed by as many "00" necessary to fill the | |
990 | block. If the last block is a full block and blocksize is 8, a | |
991 | block of "8000000000000000" will be appended. | |
992 | ||
993 | rijndael_compat: Binary safe, with caveats | |
994 | similar to oneandzeroes, except that no padding is performed if | |
995 | the last block is a full block. This is provided for | |
996 | compatibility with Crypt::Rijndael only and can only be used | |
997 | with messages that are a multiple of the Rijndael blocksize | |
998 | of 16 bytes. | |
999 | ||
1000 | null: text only | |
1001 | pads with as many "00" necessary to fill the block. If the last | |
1002 | block is a full block and blocksize is 8, a block of | |
1003 | "0000000000000000" will be appended. | |
1004 | ||
1005 | space: text only | |
1006 | same as "null", but with "20". | |
1007 | ||
1008 | none: | |
1009 | no padding added. Useful for special-purpose applications where | |
1010 | you wish to add custom padding to the message. | |
1011 | ||
1012 | Both the standard and oneandzeroes paddings are binary safe. The | |
1013 | space and null paddings are recommended only for text data. Which | |
1014 | type of padding you use depends on whether you wish to communicate | |
1015 | with an external (non Crypt::CBC library). If this is the case, use | |
1016 | whatever padding method is compatible. | |
1017 | ||
1018 | You can also pass in a custom padding function. To do this, create a | |
1019 | function that takes the arguments: | |
1020 | ||
1021 | $padded_block = function($block,$blocksize,$direction); | |
1022 | ||
1023 | where $block is the current block of data, $blocksize is the size to | |
1024 | pad it to, $direction is "e" for encrypting and "d" for decrypting, | |
1025 | and $padded_block is the result after padding or depadding. | |
1026 | ||
1027 | When encrypting, the function should always return a string of | |
1028 | <blocksize> length, and when decrypting, can expect the string coming | |
1029 | in to always be that length. See _standard_padding(), _space_padding(), | |
1030 | _null_padding(), or _oneandzeroes_padding() in the source for examples. | |
1031 | ||
1032 | Standard and oneandzeroes padding are recommended, as both space and | |
1033 | null padding can potentially truncate more characters than they should. | |
1034 | ||
1035 | =head1 EXAMPLES | |
1036 | ||
1037 | Two examples, des.pl and idea.pl can be found in the eg/ subdirectory | |
1038 | of the Crypt-CBC distribution. These implement command-line DES and | |
1039 | IDEA encryption algorithms. | |
1040 | ||
1041 | =head1 LIMITATIONS | |
1042 | ||
1043 | The encryption and decryption process is about a tenth the speed of | |
1044 | the equivalent SSLeay programs (compiled C). This could be improved | |
1045 | by implementing this module in C. It may also be worthwhile to | |
1046 | optimize the DES and IDEA block algorithms further. | |
1047 | ||
1048 | =head1 BUGS | |
1049 | ||
1050 | Please report them. | |
1051 | ||
1052 | =head1 AUTHOR | |
1053 | ||
1054 | Lincoln Stein, lstein@cshl.org | |
1055 | ||
1056 | This module is distributed under the ARTISTIC LICENSE using the same | |
1057 | terms as Perl itself. | |
1058 | ||
1059 | =head1 SEE ALSO | |
1060 | ||
1061 | perl(1), Crypt::DES(3), Crypt::IDEA(3), rfc2898 (PKCS#5) | |
1062 | ||
1063 | =cut |
0 | 0 | Revision history for Perl extension Crypt::CBC. |
1 | 3.04 Mon 17 May 2021 10:58:37 AM EDT | |
2 | - Fixed bug involving manually-specified IV not being used in some circumstances. | |
3 | ||
4 | 3.03 Sun 18 Apr 2021 10:54:19 PM EDT | |
5 | - Fixed bug which caused an extraneous block of garbage data to be appended to encrypted | |
6 | string when "nopadding" specified and plaintext is even multiple of blocksize. | |
7 | ||
8 | 3.02 | |
9 | - CTR mode now requires the Math::Int128 module, which gives a ~5x performance | |
10 | boost over Math::BigInt. | |
11 | ||
12 | 3.01 | |
13 | - Warn when the deprecated opensslv1 PBKDF (key derivation function) is used | |
14 | for encryption. Turn off with -nodeprecate=>1 or by choosing a different | |
15 | PBKDF, such as -pbkdf=>'pbkdf2'. | |
16 | - Fix a regression when passing the legacy -salt=>1 argument. | |
17 | ||
18 | 3.00 Sun Feb 7 10:28:08 EST 2021 | |
19 | - Released version 3.00 in recognition of multiple new features | |
20 | and cleanups. | |
21 | ||
22 | 2.37 Sun Feb 7 10:20:17 EST 2021 | |
23 | - Added better argument checking. | |
24 | - Fixed long-standing standard padding bug: plaintext ending with | |
25 | bytes between 0x00 and 0x0A would be truncated in some conditions. | |
26 | - Fixed Rijndael_compat padding. | |
27 | ||
28 | 2.36 Wed 03 Feb 2021 09:19:06 AM EST | |
29 | - Add support for OFB, CFB and CTR chain modes. | |
30 | - New dependency: Math::BigInt | |
31 | ||
32 | 2.35 Sun Jan 31 22:02:42 EST 2021 | |
33 | - Add support for PBKDF2 key derivation algorithm | |
34 | - New dependencies: Digest::SHA, Crypt::PBKDF2, Crypt::Cipher::AES | |
35 | ||
36 | 2.34 Fri Jan 29 18:08:12 EST 2021 | |
37 | - Support for openssl SHA-256 key derivation algorithm | |
38 | ||
1 | 39 | 2.33 Tue Jul 30 16:02:04 EDT 2013 |
2 | 40 | - Fix minor RT bugs 83175 and 86455. |
3 | 41 |
0 | CBC.pm | |
1 | 0 | Changes |
2 | MANIFEST | |
3 | META.yml Module meta-data (added by MakeMaker) | |
4 | Makefile.PL | |
5 | README | |
6 | 1 | Crypt-CBC-2.16-vulnerability.txt |
7 | 2 | eg/aes.pl |
8 | 3 | eg/des.pl |
9 | 4 | eg/idea.pl |
5 | lib/Crypt/CBC.pm | |
6 | lib/Crypt/CBC/PBKDF.pm | |
7 | lib/Crypt/CBC/PBKDF/none.pm | |
8 | lib/Crypt/CBC/PBKDF/randomiv.pm | |
9 | lib/Crypt/CBC/PBKDF/opensslv1.pm | |
10 | lib/Crypt/CBC/PBKDF/opensslv2.pm | |
11 | lib/Crypt/CBC/PBKDF/pbkdf2.pm | |
12 | Makefile.PL | |
13 | MANIFEST | |
14 | META.yml Module meta-data (added by MakeMaker) | |
15 | README | |
16 | README.md | |
17 | t/AES.t | |
10 | 18 | t/Blowfish.t |
11 | 19 | t/Blowfish_PP.t |
12 | 20 | t/CAST5.t |
13 | 21 | t/DES.t |
22 | t/func.t | |
14 | 23 | t/IDEA.t |
24 | t/null_data.t | |
25 | t/nopadding.t | |
26 | t/OFB.t | |
27 | t/onezeropadding.t | |
28 | t/parameters.t | |
29 | t/pbkdf.t | |
15 | 30 | t/PCBC.t |
31 | t/preexisting.t | |
16 | 32 | t/Rijndael.t |
17 | t/onezeropadding.t | |
18 | 33 | t/Rijndael_compat.t |
19 | t/func.t | |
20 | t/null_data.t | |
21 | t/parameters.t | |
22 | t/preexisting.t | |
23 | ||
24 | 34 | META.json Module JSON meta-data (added by MakeMaker) |
3 | 3 | "unknown" |
4 | 4 | ], |
5 | 5 | "dynamic_config" : 1, |
6 | "generated_by" : "ExtUtils::MakeMaker version 6.68, CPAN::Meta::Converter version 2.112621", | |
6 | "generated_by" : "ExtUtils::MakeMaker version 7.34, CPAN::Meta::Converter version 2.150010", | |
7 | 7 | "license" : [ |
8 | 8 | "unknown" |
9 | 9 | ], |
10 | 10 | "meta-spec" : { |
11 | 11 | "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", |
12 | "version" : "2" | |
12 | "version" : 2 | |
13 | 13 | }, |
14 | 14 | "name" : "Crypt-CBC", |
15 | 15 | "no_index" : { |
21 | 21 | "prereqs" : { |
22 | 22 | "build" : { |
23 | 23 | "requires" : { |
24 | "ExtUtils::MakeMaker" : 0 | |
24 | "ExtUtils::MakeMaker" : "0" | |
25 | 25 | } |
26 | 26 | }, |
27 | 27 | "configure" : { |
28 | 28 | "requires" : { |
29 | "ExtUtils::MakeMaker" : 0 | |
29 | "ExtUtils::MakeMaker" : "0" | |
30 | 30 | } |
31 | 31 | }, |
32 | 32 | "runtime" : { |
33 | 33 | "requires" : { |
34 | "Digest::MD5" : "2.00" | |
34 | "Crypt::Cipher::AES" : "0", | |
35 | "Crypt::PBKDF2" : "0", | |
36 | "Digest::MD5" : "0", | |
37 | "Digest::SHA" : "0" | |
35 | 38 | } |
36 | 39 | } |
37 | 40 | }, |
38 | 41 | "release_status" : "stable", |
39 | "version" : "2.33" | |
42 | "version" : "3.04", | |
43 | "x_serialization_backend" : "JSON::PP version 4.02" | |
40 | 44 | } |
2 | 2 | author: |
3 | 3 | - unknown |
4 | 4 | build_requires: |
5 | ExtUtils::MakeMaker: 0 | |
5 | ExtUtils::MakeMaker: '0' | |
6 | 6 | configure_requires: |
7 | ExtUtils::MakeMaker: 0 | |
7 | ExtUtils::MakeMaker: '0' | |
8 | 8 | dynamic_config: 1 |
9 | generated_by: 'ExtUtils::MakeMaker version 6.68, CPAN::Meta::Converter version 2.112621' | |
9 | generated_by: 'ExtUtils::MakeMaker version 7.34, CPAN::Meta::Converter version 2.150010' | |
10 | 10 | license: unknown |
11 | 11 | meta-spec: |
12 | 12 | url: http://module-build.sourceforge.net/META-spec-v1.4.html |
13 | version: 1.4 | |
13 | version: '1.4' | |
14 | 14 | name: Crypt-CBC |
15 | 15 | no_index: |
16 | 16 | directory: |
17 | 17 | - t |
18 | 18 | - inc |
19 | 19 | requires: |
20 | Digest::MD5: 2.00 | |
21 | version: 2.33 | |
20 | Crypt::Cipher::AES: '0' | |
21 | Crypt::PBKDF2: '0' | |
22 | Digest::MD5: '0' | |
23 | Digest::SHA: '0' | |
24 | version: '3.04' | |
25 | x_serialization_backend: 'CPAN::Meta::YAML version 0.018' |
2 | 2 | # the contents of the Makefile that is written. |
3 | 3 | WriteMakefile( |
4 | 4 | 'NAME' => 'Crypt::CBC', |
5 | 'VERSION_FROM' => 'CBC.pm', # finds $VERSION | |
6 | 'PREREQ_PM' => {'Digest::MD5' => '2.00' }, | |
5 | 'VERSION_FROM' => 'lib/Crypt/CBC.pm', # finds $VERSION | |
6 | 'PREREQ_PM' => { | |
7 | 'Digest::MD5' => 0, | |
8 | 'Digest::SHA' => 0, | |
9 | 'Crypt::PBKDF2' => 0, | |
10 | 'Crypt::Cipher::AES' => 0, | |
11 | }, | |
7 | 12 | 'LIBS' => [''], # e.g., '-lm' |
8 | 13 | 'DEFINE' => '', # e.g., '-DHAVE_SOMETHING' |
9 | 14 | 'INC' => '', # e.g., '-I/usr/include/other' |
0 | # NAME | |
1 | ||
2 | Crypt::CBC - Encrypt Data with Cipher Block Chaining Mode | |
3 | ||
4 | # SYNOPSIS | |
5 | ||
6 | use Crypt::CBC; | |
7 | $cipher = Crypt::CBC->new( -pass => 'my secret password', | |
8 | -cipher => 'Cipher::AES' | |
9 | ); | |
10 | ||
11 | # one shot mode | |
12 | $ciphertext = $cipher->encrypt("This data is hush hush"); | |
13 | $plaintext = $cipher->decrypt($ciphertext); | |
14 | ||
15 | # stream mode | |
16 | $cipher->start('encrypting'); | |
17 | open(F,"./BIG_FILE"); | |
18 | while (read(F,$buffer,1024)) { | |
19 | print $cipher->crypt($buffer); | |
20 | } | |
21 | print $cipher->finish; | |
22 | ||
23 | # do-it-yourself mode -- specify key && initialization vector yourself | |
24 | $key = Crypt::CBC->random_bytes(8); # assuming a 8-byte block cipher | |
25 | $iv = Crypt::CBC->random_bytes(8); | |
26 | $cipher = Crypt::CBC->new(-pbkdf => 'none', | |
27 | -key => $key, | |
28 | -iv => $iv); | |
29 | ||
30 | $ciphertext = $cipher->encrypt("This data is hush hush"); | |
31 | $plaintext = $cipher->decrypt($ciphertext); | |
32 | ||
33 | # encrypting via a filehandle (requires Crypt::FileHandle> | |
34 | $fh = Crypt::CBC->filehandle(-pass => 'secret'); | |
35 | open $fh,'>','encrypted.txt" or die $! | |
36 | print $fh "This will be encrypted\n"; | |
37 | close $fh; | |
38 | ||
39 | # DESCRIPTION | |
40 | ||
41 | This module is a Perl-only implementation of the cryptographic cipher | |
42 | block chaining mode (CBC). In combination with a block cipher such as | |
43 | AES or Blowfish, you can encrypt and decrypt messages of arbitrarily | |
44 | long length. The encrypted messages are compatible with the | |
45 | encryption format used by the **OpenSSL** package. | |
46 | ||
47 | To use this module, you will first create a Crypt::CBC cipher object | |
48 | with new(). At the time of cipher creation, you specify an encryption | |
49 | key to use and, optionally, a block encryption algorithm. You will | |
50 | then call the start() method to initialize the encryption or | |
51 | decryption process, crypt() to encrypt or decrypt one or more blocks | |
52 | of data, and lastly finish(), to pad and encrypt the final block. For | |
53 | your convenience, you can call the encrypt() and decrypt() methods to | |
54 | operate on a whole data value at once. | |
55 | ||
56 | ## new() | |
57 | ||
58 | $cipher = Crypt::CBC->new( -pass => 'my secret key', | |
59 | -cipher => 'Cipher::AES', | |
60 | ); | |
61 | ||
62 | # or (for compatibility with versions prior to 2.0) | |
63 | $cipher = new Crypt::CBC('my secret key' => 'Cipher::AES'); | |
64 | ||
65 | The new() method creates a new Crypt::CBC object. It accepts a list of | |
66 | \-argument => value pairs selected from the following list: | |
67 | ||
68 | Argument Description | |
69 | -------- ----------- | |
70 | ||
71 | -pass,-key The encryption/decryption passphrase. These arguments | |
72 | are interchangeable, but -pass is preferred | |
73 | ("key" is a misnomer, as it is not the literal | |
74 | encryption key). | |
75 | ||
76 | -cipher The cipher algorithm (defaults to Crypt::Cipher:AES), or | |
77 | a previously created cipher object reference. For | |
78 | convenience, you may omit the initial "Crypt::" part | |
79 | of the classname and use the basename, e.g. "Blowfish" | |
80 | instead of "Crypt::Blowfish". | |
81 | ||
82 | -keysize Force the cipher keysize to the indicated number of bytes. This can be used | |
83 | to set the keysize for variable keylength ciphers such as AES. | |
84 | ||
85 | -chain_mode The block chaining mode to use. Current options are: | |
86 | 'cbc' -- cipher-block chaining mode [default] | |
87 | 'pcbc' -- plaintext cipher-block chaining mode | |
88 | 'cfb' -- cipher feedback mode | |
89 | 'ofb' -- output feedback mode | |
90 | 'ctr' -- counter mode | |
91 | ||
92 | -pbkdf The passphrase-based key derivation function used to derive | |
93 | the encryption key and initialization vector from the | |
94 | provided passphrase. For backward compatibility, Crypt::CBC | |
95 | will default to "opensslv1", but it is recommended to use | |
96 | the standard "pbkdf2"algorithm instead. If you wish to interoperate | |
97 | with OpenSSL, be aware that different versions of the software | |
98 | support a series of derivation functions. | |
99 | ||
100 | 'none' -- The value provided in -pass/-key is used directly. | |
101 | This is the same as passing true to -literal_key. | |
102 | You must also manually specify the IV with -iv. | |
103 | The key and the IV must match the keylength | |
104 | and blocklength of the chosen cipher. | |
105 | 'randomiv' -- Use insecure key derivation method found | |
106 | in prehistoric versions of OpenSSL (dangerous) | |
107 | 'opensslv1' -- [default] Use the salted MD5 method that was default | |
108 | in versions of OpenSSL through v1.0.2. | |
109 | 'opensslv2' -- [better] Use the salted SHA-256 method that was | |
110 | the default in versions of OpenSSL through v1.1.0. | |
111 | 'pbkdf2' -- [best] Use the PBKDF2 method that was first | |
112 | introduced in OpenSSL v1.1.1. | |
113 | ||
114 | More derivation functions may be added in the future. To see the | |
115 | supported list, use the command | |
116 | perl -MCrypt::CBC::PBKDF -e 'print join "\n",Crypt::CBC::PBKDF->list' | |
117 | ||
118 | -iter If the 'pbkdf2' key derivation algorithm is used, this specifies the number of | |
119 | hashing cycles to be applied to the passphrase+salt (longer is more secure). | |
120 | [default 10,000] | |
121 | ||
122 | -hasher If the 'pbkdf2' key derivation algorithm is chosen, you can use this to provide | |
123 | an initialized Crypt::PBKDF2::Hash object. | |
124 | [default HMACSHA2 for OpenSSL compatability] | |
125 | ||
126 | -header What type of header to prepend to the ciphertext. One of | |
127 | 'salt' -- use OpenSSL-compatible salted header (default) | |
128 | 'randomiv' -- Randomiv-compatible "RandomIV" header | |
129 | 'none' -- prepend no header at all | |
130 | (compatible with prehistoric versions | |
131 | of OpenSSL) | |
132 | ||
133 | -iv The initialization vector (IV). If not provided, it will be generated | |
134 | by the key derivation function. | |
135 | ||
136 | -salt The salt passed to the key derivation function. If not provided, will be | |
137 | generated randomly (recommended). | |
138 | ||
139 | -padding The padding method, one of "standard" (default), | |
140 | "space", "oneandzeroes", "rijndael_compat", | |
141 | "null", or "none" (default "standard"). | |
142 | ||
143 | -literal_key [deprected, use -pbkdf=>'none'] | |
144 | If true, the key provided by "-key" or "-pass" is used | |
145 | directly for encryption/decryption without salting or | |
146 | hashing. The key must be the right length for the chosen | |
147 | cipher. | |
148 | [default false) | |
149 | ||
150 | -pcbc [deprecated, use -chaining_mode=>'pcbc'] | |
151 | Whether to use the PCBC chaining algorithm rather than | |
152 | the standard CBC algorithm (default false). | |
153 | ||
154 | -add_header [deprecated; use -header instead] | |
155 | Whether to add the salt and IV to the header of the output | |
156 | cipher text. | |
157 | ||
158 | -regenerate_key [deprecated; use -literal_key instead] | |
159 | Whether to use a hash of the provided key to generate | |
160 | the actual encryption key (default true) | |
161 | ||
162 | -prepend_iv [deprecated; use -header instead] | |
163 | Whether to prepend the IV to the beginning of the | |
164 | encrypted stream (default true) | |
165 | ||
166 | Crypt::CBC requires three pieces of information to do its job. First | |
167 | it needs the name of the block cipher algorithm that will encrypt or | |
168 | decrypt the data in blocks of fixed length known as the cipher's | |
169 | "blocksize." Second, it needs an encryption/decryption key to pass to | |
170 | the block cipher. Third, it needs an initialization vector (IV) that | |
171 | will be used to propagate information from one encrypted block to the | |
172 | next. Both the key and the IV must be exactly the same length as the | |
173 | chosen cipher's blocksize. | |
174 | ||
175 | Crypt::CBC can derive the key and the IV from a passphrase that you | |
176 | provide, or can let you specify the true key and IV manually. In | |
177 | addition, you have the option of embedding enough information to | |
178 | regenerate the IV in a short header that is emitted at the start of | |
179 | the encrypted stream, or outputting a headerless encryption stream. In | |
180 | the first case, Crypt::CBC will be able to decrypt the stream given | |
181 | just the original key or passphrase. In the second case, you will have | |
182 | to provide the original IV as well as the key/passphrase. | |
183 | ||
184 | The **-cipher** option specifies which block cipher algorithm to use to | |
185 | encode each section of the message. This argument is optional and | |
186 | will default to the secure Crypt::Cipher::AES algorithm. | |
187 | You may use any compatible block encryption | |
188 | algorithm that you have installed. Currently, this includes | |
189 | Crypt::Cipher::AES, Crypt::DES, Crypt::DES\_EDE3, Crypt::IDEA, Crypt::Blowfish, | |
190 | Crypt::CAST5 and Crypt::Rijndael. You may refer to them using their | |
191 | full names ("Crypt::IDEA") or in abbreviated form ("IDEA"). | |
192 | ||
193 | Instead of passing the name of a cipher class, you may pass an | |
194 | already-created block cipher object. This allows you to take advantage | |
195 | of cipher algorithms that have parameterized new() methods, such as | |
196 | Crypt::Eksblowfish: | |
197 | ||
198 | my $eksblowfish = Crypt::Eksblowfish->new(8,$salt,$key); | |
199 | my $cbc = Crypt::CBC->new(-cipher=>$eksblowfish); | |
200 | ||
201 | The **-pass** argument provides a passphrase to use to generate the | |
202 | encryption key or the literal value of the block cipher key. If used | |
203 | in passphrase mode (which is the default), **-pass** can be any number | |
204 | of characters; the actual key will be derived by passing the | |
205 | passphrase through a series of hashing operations. To take full | |
206 | advantage of a given block cipher, the length of the passphrase should | |
207 | be at least equal to the cipher's blocksize. For backward | |
208 | compatibility, you may also refer to this argument using **-key**. | |
209 | ||
210 | To skip this hashing operation and specify the key directly, provide | |
211 | the actual key as a string to **-key** and specify a key derivation | |
212 | function of "none" to the **-pbkdf** argument. Alternatively, you may | |
213 | pass a true value to the **-literal\_key** argument. When you manually | |
214 | specify the key in this way, should choose a key of length exactly | |
215 | equal to the cipher's key length. You will also have to specify an IV | |
216 | equal in length to the cipher's blocksize. These choices imply a | |
217 | header mode of "none." | |
218 | ||
219 | If you pass an existing Crypt::\* object to new(), then the | |
220 | **-pass**/**-key** argument is ignored and the module will generate a | |
221 | warning. | |
222 | ||
223 | The **-pbkdf** argument specifies the algorithm used to derive the true | |
224 | key and IV from the provided passphrase (PBKDF stands for | |
225 | "passphrase-based key derivation function"). Valid values are: | |
226 | ||
227 | "opensslv1" -- [default] A fast algorithm that derives the key by | |
228 | combining a random salt values with the passphrase via | |
229 | a series of MD5 hashes. | |
230 | ||
231 | "opensslv2" -- an improved version that uses SHA-256 rather | |
232 | than MD5, and has been OpenSSL's default since v1.1.0. | |
233 | However, it has been deprecated in favor of pbkdf2 | |
234 | since OpenSSL v1.1.1. | |
235 | ||
236 | "pbkdf2" -- a better algorithm implemented in OpenSSL v1.1.1, | |
237 | described in RFC 2898 L<https://tools.ietf.org/html/rfc2898> | |
238 | ||
239 | "none" -- don't use a derivation function, but treat the passphrase | |
240 | as the literal key. This is the same as B<-literal_key> true. | |
241 | ||
242 | "nosalt" -- an insecure key derivation method used by prehistoric versions | |
243 | of OpenSSL, provided for backward compatibility. Don't use. | |
244 | ||
245 | "opensslv1" was OpenSSL's default key derivation algorithm through | |
246 | version 1.0.2, but is susceptible to dictionary attacks and is no | |
247 | longer supported. It remains the default for Crypt::CBC in order to | |
248 | avoid breaking compatibility with previously-encrypted messages. Using | |
249 | this option will issue a deprecation warning when initiating | |
250 | encryption. You can suppress the warning by passing a true value to | |
251 | the **-nodeprecate** option. | |
252 | ||
253 | It is recommended to specify the "pbkdf2" key derivation algorithm | |
254 | when compatibility with older versions of Crypt::CBC is not | |
255 | needed. This algorithm is deliberately computationally expensive in | |
256 | order to make dictionary-based attacks harder. As a result, it | |
257 | introduces a slight delay before an encryption or decryption | |
258 | operation starts. | |
259 | ||
260 | The **-iter** argument is used in conjunction with the "pbkdf2" key | |
261 | derivation option. Its value indicates the number of hashing cycles | |
262 | used to derive the key. Larger values are more secure, but impose a | |
263 | longer delay before encryption/decryption starts. The default is | |
264 | 10,000 for compatibility with OpenSSL's default. | |
265 | ||
266 | The **-hasher** argument is used in conjunction with the "pbkdf2" key | |
267 | derivation option to pass the reference to an initialized | |
268 | Crypt::PBKDF2::Hash object. If not provided, it defaults to the | |
269 | OpenSSL-compatible hash function HMACSHA2 initialized with its default | |
270 | options (SHA-256 hash). | |
271 | ||
272 | The **-header** argument specifies what type of header, if any, to | |
273 | prepend to the beginning of the encrypted data stream. The header | |
274 | allows Crypt::CBC to regenerate the original IV and correctly decrypt | |
275 | the data without your having to provide the same IV used to encrypt | |
276 | the data. Valid values for the **-header** are: | |
277 | ||
278 | "salt" -- Combine the passphrase with an 8-byte random value to | |
279 | generate both the block cipher key and the IV from the | |
280 | provided passphrase. The salt will be appended to the | |
281 | beginning of the data stream allowing decryption to | |
282 | regenerate both the key and IV given the correct passphrase. | |
283 | This method is compatible with current versions of OpenSSL. | |
284 | ||
285 | "randomiv" -- Generate the block cipher key from the passphrase, and | |
286 | choose a random 8-byte value to use as the IV. The IV will | |
287 | be prepended to the data stream. This method is compatible | |
288 | with ciphertext produced by versions of the library prior to | |
289 | 2.17, but is incompatible with block ciphers that have non | |
290 | 8-byte block sizes, such as Rijndael. Crypt::CBC will exit | |
291 | with a fatal error if you try to use this header mode with a | |
292 | non 8-byte cipher. This header type is NOT secure and NOT | |
293 | recommended. | |
294 | ||
295 | "none" -- Do not generate a header. To decrypt a stream encrypted | |
296 | in this way, you will have to provide the true key and IV | |
297 | manually. | |
298 | ||
299 | **The "salt" header is now the default as of Crypt::CBC version 2.17. In | |
300 | all earlier versions "randomiv" was the default.** | |
301 | ||
302 | When using a "salt" header, you may specify your own value of the | |
303 | salt, by passing the desired 8-byte character string to the **-salt** | |
304 | argument. Otherwise, the module will generate a random salt for | |
305 | you. Crypt::CBC will generate a fatal error if you specify a salt | |
306 | value that isn't exactly 8 bytes long. For backward compatibility | |
307 | reasons, passing a value of "1" will generate a random salt, the same | |
308 | as if no **-salt** argument was provided. | |
309 | ||
310 | The **-padding** argument controls how the last few bytes of the | |
311 | encrypted stream are dealt with when they not an exact multiple of the | |
312 | cipher block length. The default is "standard", the method specified | |
313 | in PKCS#5. | |
314 | ||
315 | The **-chaining\_mode** argument will select among several different | |
316 | block chaining modes. Values are: | |
317 | ||
318 | 'cbc' -- [default] traditional Cipher-Block Chaining mode. It has | |
319 | the property that if one block in the ciphertext message | |
320 | is damaged, only that block and the next one will be | |
321 | rendered un-decryptable. | |
322 | ||
323 | 'pcbc' -- Plaintext Cipher-Block Chaining mode. This has the property | |
324 | that one damaged ciphertext block will render the | |
325 | remainder of the message unreadable | |
326 | ||
327 | 'cfb' -- Cipher Feedback Mode. In this mode, both encryption and decryption | |
328 | are performed using the block cipher's "encrypt" algorithm. | |
329 | The error propagation behaviour is similar to CBC's. | |
330 | ||
331 | 'ofb' -- Output Feedback Mode. Similar to CFB, the block cipher's encrypt | |
332 | algorithm is used for both encryption and decryption. If one bit | |
333 | of the plaintext or ciphertext message is damaged, the damage is | |
334 | confined to a single block of the corresponding ciphertext or | |
335 | plaintext, and error correction algorithms can be used to reconstruct | |
336 | the damaged part. | |
337 | ||
338 | 'ctr' -- Counter Mode. This mode uses a one-time "nonce" instead of | |
339 | an IV. The nonce is incremented by one for each block of | |
340 | plain or ciphertext, encrypted using the chosen | |
341 | algorithm, and then applied to the block of text. If one | |
342 | bit of the input text is damaged, it only affects 1 bit | |
343 | of the output text. To use CTR mode you will need to | |
344 | install the Perl Math::Int128 module. | |
345 | ||
346 | Passing a **-pcbc** argument of true will have the same effect as | |
347 | \-chaining\_mode=>'pcbc', and is included for backward | |
348 | compatibility. \[deprecated\]. | |
349 | ||
350 | For more information on chaining modes, see | |
351 | [http://www.crypto-it.net/eng/theory/modes-of-block-ciphers.html](http://www.crypto-it.net/eng/theory/modes-of-block-ciphers.html). | |
352 | ||
353 | The **-keysize** argument can be used to force the cipher's | |
354 | keysize. This is useful for several of the newer algorithms, including | |
355 | AES, ARIA, Blowfish, and CAMELLIA. If -keysize is not specified, then | |
356 | Crypt::CBC will use the value returned by the cipher's max\_keylength() | |
357 | method. Note that versions of CBC::Crypt prior to 2.36 could also | |
358 | allow you to set the blocksie, but this was never supported by any | |
359 | ciphers and has been removed. | |
360 | ||
361 | For compatibility with earlier versions of this module, you can | |
362 | provide new() with a hashref containing key/value pairs. The key names | |
363 | are the same as the arguments described earlier, but without the | |
364 | initial hyphen. You may also call new() with one or two positional | |
365 | arguments, in which case the first argument is taken to be the key and | |
366 | the second to be the optional block cipher algorithm. | |
367 | ||
368 | ## start() | |
369 | ||
370 | $cipher->start('encrypting'); | |
371 | $cipher->start('decrypting'); | |
372 | ||
373 | The start() method prepares the cipher for a series of encryption or | |
374 | decryption steps, resetting the internal state of the cipher if | |
375 | necessary. You must provide a string indicating whether you wish to | |
376 | encrypt or decrypt. "E" or any word that begins with an "e" indicates | |
377 | encryption. "D" or any word that begins with a "d" indicates | |
378 | decryption. | |
379 | ||
380 | ## crypt() | |
381 | ||
382 | $ciphertext = $cipher->crypt($plaintext); | |
383 | ||
384 | After calling start(), you should call crypt() as many times as | |
385 | necessary to encrypt the desired data. | |
386 | ||
387 | ## finish() | |
388 | ||
389 | $ciphertext = $cipher->finish(); | |
390 | ||
391 | The CBC algorithm must buffer data blocks internally until they are | |
392 | even multiples of the encryption algorithm's blocksize (typically 8 | |
393 | bytes). After the last call to crypt() you should call finish(). | |
394 | This flushes the internal buffer and returns any leftover ciphertext. | |
395 | ||
396 | In a typical application you will read the plaintext from a file or | |
397 | input stream and write the result to standard output in a loop that | |
398 | might look like this: | |
399 | ||
400 | $cipher = new Crypt::CBC('hey jude!'); | |
401 | $cipher->start('encrypting'); | |
402 | print $cipher->crypt($_) while <>; | |
403 | print $cipher->finish(); | |
404 | ||
405 | ## encrypt() | |
406 | ||
407 | $ciphertext = $cipher->encrypt($plaintext) | |
408 | ||
409 | This convenience function runs the entire sequence of start(), crypt() | |
410 | and finish() for you, processing the provided plaintext and returning | |
411 | the corresponding ciphertext. | |
412 | ||
413 | ## decrypt() | |
414 | ||
415 | $plaintext = $cipher->decrypt($ciphertext) | |
416 | ||
417 | This convenience function runs the entire sequence of start(), crypt() | |
418 | and finish() for you, processing the provided ciphertext and returning | |
419 | the corresponding plaintext. | |
420 | ||
421 | ## encrypt\_hex(), decrypt\_hex() | |
422 | ||
423 | $ciphertext = $cipher->encrypt_hex($plaintext) | |
424 | $plaintext = $cipher->decrypt_hex($ciphertext) | |
425 | ||
426 | These are convenience functions that operate on ciphertext in a | |
427 | hexadecimal representation. **encrypt\_hex($plaintext)** is exactly | |
428 | equivalent to **unpack('H\*',encrypt($plaintext))**. These functions | |
429 | can be useful if, for example, you wish to place the encrypted in an | |
430 | email message. | |
431 | ||
432 | ## filehandle() | |
433 | ||
434 | This method returns a filehandle for transparent encryption or | |
435 | decryption using Christopher Dunkle's excellent [Crypt::FileHandle](https://metacpan.org/pod/Crypt%3A%3AFileHandle) | |
436 | module. This module must be installed in order to use this method. | |
437 | ||
438 | filehandle() can be called as a class method using the same arguments | |
439 | as new(): | |
440 | ||
441 | $fh = Crypt::CBC->filehandle(-cipher=> 'Blowfish', | |
442 | -pass => "You'll never guess"); | |
443 | ||
444 | or on a previously-created Crypt::CBC object: | |
445 | ||
446 | $cbc = Crypt::CBC->new(-cipher=> 'Blowfish', | |
447 | -pass => "You'll never guess"); | |
448 | $fh = $cbc->filehandle; | |
449 | ||
450 | The filehandle can then be opened using the familiar open() syntax. | |
451 | Printing to a filehandle opened for writing will encrypt the | |
452 | data. Filehandles opened for input will be decrypted. | |
453 | ||
454 | Here is an example: | |
455 | ||
456 | # transparent encryption | |
457 | open $fh,'>','encrypted.out' or die $!; | |
458 | print $fh "You won't be able to read me!\n"; | |
459 | close $fh; | |
460 | ||
461 | # transparent decryption | |
462 | open $fh,'<','encrypted.out' or die $!; | |
463 | while (<$fh>) { print $_ } | |
464 | close $fh; | |
465 | ||
466 | ## get\_initialization\_vector() | |
467 | ||
468 | $iv = $cipher->get_initialization_vector() | |
469 | ||
470 | This function will return the IV used in encryption and or decryption. | |
471 | The IV is not guaranteed to be set when encrypting until start() is | |
472 | called, and when decrypting until crypt() is called the first | |
473 | time. Unless the IV was manually specified in the new() call, the IV | |
474 | will change with every complete encryption operation. | |
475 | ||
476 | ## set\_initialization\_vector() | |
477 | ||
478 | $cipher->set_initialization_vector('76543210') | |
479 | ||
480 | This function sets the IV used in encryption and/or decryption. This | |
481 | function may be useful if the IV is not contained within the | |
482 | ciphertext string being decrypted, or if a particular IV is desired | |
483 | for encryption. Note that the IV must match the chosen cipher's | |
484 | blocksize bytes in length. | |
485 | ||
486 | ## iv() | |
487 | ||
488 | $iv = $cipher->iv(); | |
489 | $cipher->iv($new_iv); | |
490 | ||
491 | As above, but using a single method call. | |
492 | ||
493 | ## key() | |
494 | ||
495 | $key = $cipher->key(); | |
496 | $cipher->key($new_key); | |
497 | ||
498 | Get or set the block cipher key used for encryption/decryption. When | |
499 | encrypting, the key is not guaranteed to exist until start() is | |
500 | called, and when decrypting, the key is not guaranteed to exist until | |
501 | after the first call to crypt(). The key must match the length | |
502 | required by the underlying block cipher. | |
503 | ||
504 | When salted headers are used, the block cipher key will change after | |
505 | each complete sequence of encryption operations. | |
506 | ||
507 | ## salt() | |
508 | ||
509 | $salt = $cipher->salt(); | |
510 | $cipher->salt($new_salt); | |
511 | ||
512 | Get or set the salt used for deriving the encryption key and IV when | |
513 | in OpenSSL compatibility mode. | |
514 | ||
515 | ## passphrase() | |
516 | ||
517 | $passphrase = $cipher->passphrase(); | |
518 | $cipher->passphrase($new_passphrase); | |
519 | ||
520 | This gets or sets the value of the **passphrase** passed to new() when | |
521 | **literal\_key** is false. | |
522 | ||
523 | ## $data = random\_bytes($numbytes) | |
524 | ||
525 | Return $numbytes worth of random data. On systems that support the | |
526 | "/dev/urandom" device file, this data will be read from the | |
527 | device. Otherwise, it will be generated by repeated calls to the Perl | |
528 | rand() function. | |
529 | ||
530 | ## cipher(), pbkdf(), padding(), keysize(), blocksize(), chain\_mode() | |
531 | ||
532 | These read-only methods return the identity of the chosen block cipher | |
533 | algorithm, the key derivation function (e.g. "opensslv1"), padding | |
534 | method, key and block size of the chosen block cipher, and what | |
535 | chaining mode ("cbc", "ofb" ,etc) is being used. | |
536 | ||
537 | ## Padding methods | |
538 | ||
539 | Use the 'padding' option to change the padding method. | |
540 | ||
541 | When the last block of plaintext is shorter than the block size, | |
542 | it must be padded. Padding methods include: "standard" (i.e., PKCS#5), | |
543 | "oneandzeroes", "space", "rijndael\_compat", "null", and "none". | |
544 | ||
545 | standard: (default) Binary safe | |
546 | pads with the number of bytes that should be truncated. So, if | |
547 | blocksize is 8, then "0A0B0C" will be padded with "05", resulting | |
548 | in "0A0B0C0505050505". If the final block is a full block of 8 | |
549 | bytes, then a whole block of "0808080808080808" is appended. | |
550 | ||
551 | oneandzeroes: Binary safe | |
552 | pads with "80" followed by as many "00" necessary to fill the | |
553 | block. If the last block is a full block and blocksize is 8, a | |
554 | block of "8000000000000000" will be appended. | |
555 | ||
556 | rijndael_compat: Binary safe, with caveats | |
557 | similar to oneandzeroes, except that no padding is performed if | |
558 | the last block is a full block. This is provided for | |
559 | compatibility with Crypt::Rijndael's buit-in MODE_CBC. | |
560 | Note that Crypt::Rijndael's implementation of CBC only | |
561 | works with messages that are even multiples of 16 bytes. | |
562 | ||
563 | null: text only | |
564 | pads with as many "00" necessary to fill the block. If the last | |
565 | block is a full block and blocksize is 8, a block of | |
566 | "0000000000000000" will be appended. | |
567 | ||
568 | space: text only | |
569 | same as "null", but with "20". | |
570 | ||
571 | none: | |
572 | no padding added. Useful for special-purpose applications where | |
573 | you wish to add custom padding to the message. | |
574 | ||
575 | Both the standard and oneandzeroes paddings are binary safe. The | |
576 | space and null paddings are recommended only for text data. Which | |
577 | type of padding you use depends on whether you wish to communicate | |
578 | with an external (non Crypt::CBC library). If this is the case, use | |
579 | whatever padding method is compatible. | |
580 | ||
581 | You can also pass in a custom padding function. To do this, create a | |
582 | function that takes the arguments: | |
583 | ||
584 | $padded_block = function($block,$blocksize,$direction); | |
585 | ||
586 | where $block is the current block of data, $blocksize is the size to | |
587 | pad it to, $direction is "e" for encrypting and "d" for decrypting, | |
588 | and $padded\_block is the result after padding or depadding. | |
589 | ||
590 | When encrypting, the function should always return a string of | |
591 | <blocksize> length, and when decrypting, can expect the string coming | |
592 | in to always be that length. See \_standard\_padding(), \_space\_padding(), | |
593 | \_null\_padding(), or \_oneandzeroes\_padding() in the source for examples. | |
594 | ||
595 | Standard and oneandzeroes padding are recommended, as both space and | |
596 | null padding can potentially truncate more characters than they should. | |
597 | ||
598 | # Comparison to Crypt::Mode::CBC | |
599 | ||
600 | The [CryptX](https://metacpan.org/pod/CryptX) modules [Crypt::Mode::CBC](https://metacpan.org/pod/Crypt%3A%3AMode%3A%3ACBC), [Crypt::Mode::OFB](https://metacpan.org/pod/Crypt%3A%3AMode%3A%3AOFB), | |
601 | [Crypt::Mode::CFB](https://metacpan.org/pod/Crypt%3A%3AMode%3A%3ACFB), and [Crypt::Mode::CTR](https://metacpan.org/pod/Crypt%3A%3AMode%3A%3ACTR) provide fast | |
602 | implementations of the respective cipherblock chaining modes (roughly | |
603 | 5x the speed of Crypt::CBC). Crypt::CBC was designed to encrypt and | |
604 | decrypt messages in a manner compatible with OpenSSL's "enc" | |
605 | function. Hence it handles the derivation of the key and IV from a | |
606 | passphrase using the same conventions as OpenSSL, and it writes out an | |
607 | OpenSSL-compatible header in the encrypted message in a manner that | |
608 | allows the key and IV to be regenerated during decryption. | |
609 | ||
610 | In contrast, the CryptX modules do not automatically derive the key | |
611 | and IV from a passphrase or write out an encrypted header. You will | |
612 | need to derive and store the key and IV by other means (e.g. with | |
613 | CryptX's Crypt::KeyDerivation module, or with Crypt::PBKDF2). | |
614 | ||
615 | # EXAMPLES | |
616 | ||
617 | Three examples, aes.pl, des.pl and idea.pl can be found in the eg/ | |
618 | subdirectory of the Crypt-CBC distribution. These implement | |
619 | command-line DES and IDEA encryption algorithms using default | |
620 | parameters, and should be compatible with recent versions of | |
621 | OpenSSL. Note that aes.pl uses the "pbkdf2" key derivation function to | |
622 | generate its keys. The other two were distributed with pre-PBKDF2 | |
623 | versions of Crypt::CBC, and use the older "opensslv1" algorithm. | |
624 | ||
625 | # LIMITATIONS | |
626 | ||
627 | The encryption and decryption process is about a tenth the speed of | |
628 | the equivalent OpenSSL tool and about a fifth of the Crypt::Mode::CBC | |
629 | module (both which use compiled C). | |
630 | ||
631 | # BUGS | |
632 | ||
633 | Please report them. | |
634 | ||
635 | # AUTHOR | |
636 | ||
637 | Lincoln Stein, lstein@cshl.org | |
638 | ||
639 | This module is distributed under the ARTISTIC LICENSE v2 using the | |
640 | same terms as Perl itself. | |
641 | ||
642 | # SEE ALSO | |
643 | ||
644 | perl(1), CryptX, Crypt::FileHandle, Crypt::Cipher::AES, | |
645 | Crypt::Blowfish, Crypt::CAST5, Crypt::DES, Crypt::IDEA, | |
646 | Crypt::Rijndael |
7 | 7 | |
8 | 8 | my %options; |
9 | 9 | |
10 | getopts('edk:i:o:',\%options) || die <<USAGE; | |
10 | getopts('edk:p:i:o:',\%options) || die <<USAGE; | |
11 | 11 | Usage: aes.pl [options] file1 file2 file3... |
12 | AES encrypt/decrypt files using Cipher Block Chaining mode. | |
12 | AES encrypt/decrypt files using Cipher Block Chaining mode, and | |
13 | the PBKDF2 key derivation function. | |
14 | ||
15 | It is compatible with files encrypted using | |
16 | "openssl enc -pbkdf2 -aes-256-cbc". | |
13 | 17 | Options: |
14 | -e encrypt (default) | |
15 | -d decrypt | |
16 | -k 'key' provide key on command line | |
17 | -i file input file | |
18 | -o file output file | |
19 | ||
20 | (NB: The Rijndael cipher is the basis for AES) | |
18 | -e encrypt (default) | |
19 | -d decrypt | |
20 | -p,-k 'passphrase' provide passphrase on command line | |
21 | -i file input file | |
22 | -o file output file | |
21 | 23 | USAGE |
22 | 24 | ; |
23 | 25 | |
26 | 28 | open(STDOUT,">$options{'o'}") or die "$options{'o'}: $!" |
27 | 29 | if $options{'o'}; |
28 | 30 | |
29 | my $key = $options{'k'} || get_key(); | |
30 | my $cipher = Crypt::CBC->new(-key => $key, | |
31 | -cipher => 'Rijndael', | |
32 | -salt => 1, | |
31 | my $decrypt = $options{'d'} and !$options{'e'}; | |
32 | my $key = $options{'k'} || $options{'p'} || get_key(!$decrypt); | |
33 | my $cipher = Crypt::CBC->new(-pass => $key, | |
34 | -cipher => 'Crypt::Cipher::AES', | |
35 | -pbkdf => 'pbkdf2', | |
36 | -chain_mode => 'ctr', | |
33 | 37 | ) || die "Couldn't create CBC object"; |
34 | my $decrypt = $options{'d'} and !$options{'e'}; | |
35 | 38 | $cipher->start($decrypt ? 'decrypt' : 'encrypt'); |
36 | 39 | |
37 | 40 | my $in; |
44 | 47 | print $cipher->finish; |
45 | 48 | |
46 | 49 | sub get_key { |
50 | my $verify = shift; | |
51 | ||
47 | 52 | local($|) = 1; |
48 | 53 | local(*TTY); |
49 | 54 | open(TTY,"/dev/tty"); |
52 | 57 | do { |
53 | 58 | print STDERR "AES key: "; |
54 | 59 | chomp($key1 = <TTY>); |
55 | print STDERR "\r\nRe-type key: "; | |
56 | chomp($key2 = <TTY>); | |
57 | print STDERR "\r\n"; | |
58 | print STDERR "The two keys don't match. Try again.\r\n" | |
59 | unless $key1 eq $key2; | |
60 | if ($verify) { | |
61 | print STDERR "\r\nRe-type key: "; | |
62 | chomp($key2 = <TTY>); | |
63 | print STDERR "\r\n"; | |
64 | print STDERR "The two keys don't match. Try again.\r\n" | |
65 | unless $key1 eq $key2; | |
66 | } else { | |
67 | $key2 = $key1; | |
68 | } | |
60 | 69 | } until $key1 eq $key2; |
61 | 70 | system "stty echo </dev/tty"; |
62 | 71 | close(TTY); |
9 | 9 | |
10 | 10 | getopts('edk:i:o:',\%options) || die <<USAGE; |
11 | 11 | Usage: des.pl [options] file1 file2 file3... |
12 | DES encrypt/decrypt files using Cipher Block Chaining mode. | |
12 | DES encrypt/decrypt files using Cipher Block Chaining mode. | |
13 | ||
14 | It is compatible with files encrypted using | |
15 | "openssl enc -des-cbc -md md5". | |
13 | 16 | Options: |
14 | 17 | -e encrypt (default) |
15 | 18 | -d decrypt |
0 | package Crypt::CBC::PBKDF::none; | |
1 | use strict; | |
2 | use Carp 'croak'; | |
3 | use base 'Crypt::CBC::PBKDF::opensslv1'; | |
4 | ||
5 | # options: | |
6 | # key_len => 32 default | |
7 | # iv_len => 16 default | |
8 | ||
9 | sub generate_hash { | |
10 | my $self = shift; | |
11 | my ($salt,$passphrase) = @_; | |
12 | # ALERT: in this case passphrase IS the key and the salt is ignored | |
13 | # Croak unless key matches key length | |
14 | my $keylen = $self->{key_len}; | |
15 | length($passphrase) == $keylen or croak "For selected cipher, the key must be exactly $keylen bytes long"; | |
16 | return $passphrase; | |
17 | } | |
18 | ||
19 | 1; |
0 | package Crypt::CBC::PBKDF::opensslv1; | |
1 | use strict; | |
2 | use base 'Crypt::CBC::PBKDF'; | |
3 | use Digest::MD5 'md5'; | |
4 | ||
5 | # options: | |
6 | # salt_len => 8 default | |
7 | # key_len => 32 default | |
8 | # iv_len => 16 default | |
9 | ||
10 | sub create { | |
11 | my $class = shift; | |
12 | my %options = @_; | |
13 | $options{salt_len} ||= 8; | |
14 | $options{key_len} ||= 32; | |
15 | $options{iv_len} ||= 16; | |
16 | return bless \%options,$class; | |
17 | } | |
18 | ||
19 | sub generate_hash { | |
20 | my $self = shift; | |
21 | my ($salt,$passphrase) = @_; | |
22 | my $desired_len = $self->{key_len} + $self->{iv_len}; | |
23 | my $data = ''; | |
24 | my $d = ''; | |
25 | while (length $data < $desired_len) { | |
26 | $d = md5($d . $passphrase . $salt); | |
27 | $data .= $d; | |
28 | } | |
29 | return $data; | |
30 | } | |
31 | ||
32 | 1; |
0 | package Crypt::CBC::PBKDF::opensslv2; | |
1 | use strict; | |
2 | use base 'Crypt::CBC::PBKDF::opensslv1'; | |
3 | use Digest::SHA 'sha256'; | |
4 | ||
5 | # options: | |
6 | # key_len => 32 default | |
7 | # iv_len => 16 default | |
8 | ||
9 | sub generate_hash { | |
10 | my $self = shift; | |
11 | my ($salt,$passphrase) = @_; | |
12 | my $desired_len = $self->{key_len} + $self->{iv_len}; | |
13 | my $data = ''; | |
14 | my $d = ''; | |
15 | while (length $data < $desired_len) { | |
16 | $d = sha256($d . $passphrase . $salt); | |
17 | $data .= $d; | |
18 | } | |
19 | return $data; | |
20 | } | |
21 | ||
22 | 1; |
0 | package Crypt::CBC::PBKDF::pbkdf2; | |
1 | use strict; | |
2 | ||
3 | use base 'Crypt::CBC::PBKDF'; | |
4 | use Crypt::PBKDF2; | |
5 | ||
6 | # options: | |
7 | # key_len => 32 default | |
8 | # iv_len => 16 default | |
9 | # iterations => 10000 default | |
10 | # hash_class => 'HMACSHA2' default | |
11 | ||
12 | sub create { | |
13 | my $class = shift; | |
14 | my %options = @_; | |
15 | $options{key_len} ||= 32; | |
16 | $options{iv_len} ||= 16; | |
17 | $options{iterations} ||= 10_000; | |
18 | $options{hash_class} ||= 'HMACSHA2'; | |
19 | return bless \%options,$class; | |
20 | } | |
21 | ||
22 | sub generate_hash { | |
23 | my $self = shift; | |
24 | my ($salt,$passphrase) = @_; | |
25 | my $pbkdf2 = Crypt::PBKDF2->new(%$self, | |
26 | output_len => $self->{key_len} + $self->{iv_len}); | |
27 | return $pbkdf2->PBKDF2($salt,$passphrase); | |
28 | } | |
29 | ||
30 | 1; |
0 | package Crypt::CBC::PBKDF::randomiv; | |
1 | ||
2 | # This is for compatibility with early (pre v1.0) versions of OpenSSL | |
3 | # THE KEYS GENERATED BY THIS ALGORITHM ARE INSECURE!!! | |
4 | use strict; | |
5 | use base 'Crypt::CBC::PBKDF'; | |
6 | use Digest::MD5 'md5'; | |
7 | ||
8 | # options: | |
9 | # salt_len => 8 default | |
10 | # key_len => 32 default | |
11 | # iv_len => 16 default | |
12 | ||
13 | sub create { | |
14 | my $class = shift; | |
15 | my %options = @_; | |
16 | $options{salt_len} ||= 8; | |
17 | $options{key_len} ||= 32; | |
18 | $options{iv_len} ||= 16; | |
19 | return bless \%options,$class; | |
20 | } | |
21 | ||
22 | sub generate_hash { | |
23 | my $self = shift; | |
24 | my ($salt,$passphrase) = @_; | |
25 | my $desired_len = $self->{key_len}; | |
26 | my $material = md5($passphrase); | |
27 | while (length($material) < $desired_len) { | |
28 | $material .= md5($material); | |
29 | } | |
30 | substr($material,$desired_len) = ''; | |
31 | $material .= Crypt::CBC->_get_random_bytes($self->{iv_len}); | |
32 | return $material; | |
33 | } | |
34 | ||
35 | 1; |
0 | package Crypt::CBC::PBKDF; | |
1 | ||
2 | # just a virtual base class for passphrase=>key derivation functions | |
3 | use strict; | |
4 | use File::Basename 'dirname','basename'; | |
5 | use Carp 'croak'; | |
6 | ||
7 | sub new { | |
8 | my $class = shift; | |
9 | my $subclass = shift; | |
10 | my $options = shift; | |
11 | ||
12 | my $package = __PACKAGE__."::$subclass"; | |
13 | eval "use $package; 1" or | |
14 | croak "Could not load $subclass: $@"; | |
15 | ||
16 | return $package->create(%$options); | |
17 | } | |
18 | ||
19 | # returns a series of subclasses | |
20 | sub list { | |
21 | my $self = shift; | |
22 | my $dir = dirname(__FILE__); | |
23 | my @pm_files = <$dir/PBKDF/*.pm>; | |
24 | my @subclasses; | |
25 | foreach (@pm_files) { | |
26 | my $base = basename($_); | |
27 | $base =~ s/\.pm$//; | |
28 | push @subclasses,$base; | |
29 | } | |
30 | return @subclasses; | |
31 | } | |
32 | ||
33 | sub generate_hash { | |
34 | my $self = shift; | |
35 | my ($salt,$passphrase) = @_; | |
36 | croak "generate() method not implemented in this class. Use one of the subclasses",join(',',$self->list); | |
37 | } | |
38 | ||
39 | sub key_and_iv { | |
40 | my $self = shift; | |
41 | croak 'usage $obj->salt_key_iv($salt,$passphrase)' unless @_ == 2; | |
42 | ||
43 | my $hash = $self->generate_hash(@_); | |
44 | ||
45 | my $key = substr($hash,0,$self->{key_len}); | |
46 | my $iv = substr($hash,$self->{key_len},$self->{iv_len}); | |
47 | return ($key,$iv); | |
48 | } | |
49 | ||
50 | 1; |
0 | package Crypt::CBC; | |
1 | ||
2 | use strict; | |
3 | use Carp 'croak','carp'; | |
4 | use Crypt::CBC::PBKDF; | |
5 | use bytes; | |
6 | use vars qw($VERSION); | |
7 | no warnings 'uninitialized'; | |
8 | $VERSION = '3.04'; | |
9 | ||
10 | use constant RANDOM_DEVICE => '/dev/urandom'; | |
11 | use constant DEFAULT_PBKDF => 'opensslv1'; | |
12 | use constant DEFAULT_ITER => 10_000; # same as OpenSSL default | |
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 | 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 | my $options = $class->_get_options(@_); | |
41 | eval {$class->_validate_options($options)} or croak $@; | |
42 | ||
43 | my $cipher = $class->_get_cipher_obj($options); | |
44 | my $header_mode = $class->_get_header_mode($options); | |
45 | my ($ks,$bs) = $class->_get_key_and_block_sizes($cipher,$options); | |
46 | my ($pass,$iv,$salt,$key, | |
47 | $random_salt,$random_iv) = $class->_get_key_materials($options); | |
48 | my $padding = $class->_get_padding_mode($bs,$options); | |
49 | my ($pbkdf,$iter, | |
50 | $hc,$nodeprecate) = $class->_get_key_derivation_options($options,$header_mode); | |
51 | 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 | $key ||= $pass if $pbkdf eq 'none'; # just in case | |
57 | my $literal_key = defined $key; | |
58 | ||
59 | # check length of initialization vector | |
60 | 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 | croak "invalid cipher block chain mode: $chain_mode" | |
65 | unless $class->can("_${chain_mode}_encrypt"); | |
66 | ||
67 | # KEYSIZE consistency | |
68 | if (defined $key && length($key) != $ks) { | |
69 | 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 | if ($header_mode eq 'salt') { | |
74 | croak "Cannot use salt-based key generation if literal key is specified" | |
75 | if $literal_key; | |
76 | } | |
77 | elsif ($header_mode eq 'randomiv') { | |
78 | croak "Cannot encrypt using a non-8 byte blocksize cipher when using randomiv header mode" | |
79 | unless $bs == 8 | |
80 | } | |
81 | ||
82 | croak "If a key derivation function (-pbkdf) of 'none' is provided, a literal key and iv must be provided" | |
83 | if $pbkdf eq 'none' && (!defined $key || !defined $iv); | |
84 | ||
85 | 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 | 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 | my $self = shift; | |
112 | $self->_load_module('Crypt::FileHandle') | |
113 | or croak "Optional Crypt::FileHandle module must be installed to use the filehandle() method"; | |
114 | ||
115 | if (ref $self) { # already initialized | |
116 | return Crypt::FileHandle->new($self); | |
117 | } | |
118 | else { # create object | |
119 | return Crypt::FileHandle->new($self->new(@_)); | |
120 | } | |
121 | } | |
122 | ||
123 | sub encrypt (\$$) { | |
124 | my ($self,$data) = @_; | |
125 | $self->start('encrypting'); | |
126 | my $result = $self->crypt($data); | |
127 | $result .= $self->finish; | |
128 | $result; | |
129 | } | |
130 | ||
131 | sub decrypt (\$$){ | |
132 | my ($self,$data) = @_; | |
133 | $self->start('decrypting'); | |
134 | my $result = $self->crypt($data); | |
135 | $result .= $self->finish; | |
136 | $result; | |
137 | } | |
138 | ||
139 | sub encrypt_hex (\$$) { | |
140 | my ($self,$data) = @_; | |
141 | return join('',unpack 'H*',$self->encrypt($data)); | |
142 | } | |
143 | ||
144 | sub decrypt_hex (\$$) { | |
145 | my ($self,$data) = @_; | |
146 | return $self->decrypt(pack 'H*',$data); | |
147 | } | |
148 | ||
149 | # call to start a series of encryption/decryption operations | |
150 | sub start (\$$) { | |
151 | my $self = shift; | |
152 | my $operation = shift; | |
153 | croak "Specify <e>ncryption or <d>ecryption" unless $operation=~/^[ed]/i; | |
154 | ||
155 | delete $self->{'civ'}; | |
156 | $self->{'buffer'} = ''; | |
157 | $self->{'decrypt'} = $operation=~/^d/i; | |
158 | $self->_deprecation_warning; | |
159 | } | |
160 | ||
161 | sub chain_mode { shift->{chain_mode} || 'cbc' } | |
162 | ||
163 | sub chaining_method { | |
164 | my $self = shift; | |
165 | my $decrypt = shift; | |
166 | ||
167 | # memoize this result | |
168 | return $self->{chaining_method}{$decrypt} | |
169 | if exists $self->{chaining_method}{$decrypt}; | |
170 | ||
171 | my $cm = $self->chain_mode; | |
172 | my $code = $self->can($decrypt ? "_${cm}_decrypt" : "_${cm}_encrypt"); | |
173 | croak "Chain mode $cm not supported" unless $code; | |
174 | return $self->{chaining_method}{$decrypt} = $code; | |
175 | } | |
176 | ||
177 | # call to encrypt/decrypt a bit of data | |
178 | sub crypt (\$$){ | |
179 | my $self = shift; | |
180 | my $data = shift; | |
181 | ||
182 | my $result; | |
183 | ||
184 | croak "crypt() called without a preceding start()" | |
185 | unless exists $self->{'buffer'}; | |
186 | ||
187 | my $d = $self->{'decrypt'}; | |
188 | ||
189 | unless ($self->{civ}) { # block cipher has not yet been initialized | |
190 | $result = $self->_generate_iv_and_cipher_from_datastream(\$data) if $d; | |
191 | $result = $self->_generate_iv_and_cipher_from_options() unless $d; | |
192 | } | |
193 | ||
194 | my $iv = $self->{'civ'}; | |
195 | $self->{'buffer'} .= $data; | |
196 | ||
197 | 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 | and $self->{'padding'} eq \&_no_padding | |
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 | and $self->{'padding'} eq \&_rijndael_compat | |
207 | and length($data) % $bs; | |
208 | ||
209 | return $result unless (length($self->{'buffer'}) >= $bs); | |
210 | ||
211 | my @blocks = unpack("(a$bs)*",$self->{buffer}); | |
212 | $self->{buffer} = ''; | |
213 | ||
214 | # if decrypting, leave the last block in the buffer for padding | |
215 | if ($d) { | |
216 | $self->{buffer} = pop @blocks; | |
217 | } else { | |
218 | $self->{buffer} = pop @blocks if length $blocks[-1] < $bs; | |
219 | } | |
220 | ||
221 | 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 | $code->($self,$self->{crypt},\$iv,\$result,\@blocks); | |
225 | ||
226 | $self->{'civ'} = $iv; # remember the iv | |
227 | return $result; | |
228 | } | |
229 | ||
230 | # this is called at the end to flush whatever's left | |
231 | sub finish (\$) { | |
232 | my $self = shift; | |
233 | my $bs = $self->{'blocksize'}; | |
234 | ||
235 | my $block = $self->{buffer}; # what's left | |
236 | ||
237 | # Special case hack for backward compatibility with Crypt::Rijndael's CBC_MODE. | |
238 | if (length $block == 0 && $self->{padding} eq \&_rijndael_compat) { | |
239 | delete $self->{'civ'}; | |
240 | delete $self->{'buffer'}; | |
241 | return ''; | |
242 | } | |
243 | ||
244 | $self->{civ} ||= ''; | |
245 | my $iv = $self->{civ}; | |
246 | my $code = $self->chaining_method($self->{decrypt}); | |
247 | ||
248 | my $result = ''; | |
249 | if ($self->{decrypt}) { | |
250 | $self->$code($self->{crypt},\$iv,\$result,[$block]); | |
251 | $result = $self->{padding}->($result,$bs,'d') if $self->_needs_padding; | |
252 | } else { | |
253 | $block = $self->{padding}->($block,$bs,'e') if $self->_needs_padding; | |
254 | $self->$code($self->{crypt},\$iv,\$result,[$block]) unless length $block==0 && !$self->_needs_padding | |
255 | } | |
256 | ||
257 | delete $self->{'civ'}; | |
258 | delete $self->{'buffer'}; | |
259 | return $result; | |
260 | } | |
261 | ||
262 | ############# Move the boring new() argument processing here ####### | |
263 | sub _get_options { | |
264 | my $class = shift; | |
265 | ||
266 | my $options = {}; | |
267 | ||
268 | # hashref arguments | |
269 | if (ref $_[0] eq 'HASH') { | |
270 | $options = shift; | |
271 | } | |
272 | ||
273 | # CGI style arguments | |
274 | elsif ($_[0] =~ /^-[a-zA-Z_]{1,20}$/) { | |
275 | my %tmp = @_; | |
276 | while ( my($key,$value) = each %tmp) { | |
277 | $key =~ s/^-//; | |
278 | $options->{lc $key} = $value; | |
279 | } | |
280 | } | |
281 | ||
282 | else { | |
283 | $options->{key} = shift; | |
284 | $options->{cipher} = shift; | |
285 | } | |
286 | return $options; | |
287 | } | |
288 | ||
289 | sub _get_cipher_obj { | |
290 | my $class = shift; | |
291 | my $options = shift; | |
292 | ||
293 | my $cipher = $options->{cipher}; | |
294 | $cipher = 'Crypt::Cipher::AES' unless $cipher; | |
295 | ||
296 | unless (ref $cipher) { # munge the class name if no object passed | |
297 | $cipher = $cipher=~/^Crypt::/ ? $cipher : "Crypt::$cipher"; | |
298 | $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 | $cipher =~ s/^Crypt::// unless $cipher->can('keysize'); | |
301 | } | |
302 | ||
303 | return $cipher; | |
304 | } | |
305 | ||
306 | sub _validate_options { | |
307 | my $self = shift; | |
308 | my $options = shift; | |
309 | my %valid_options = map {$_=>1} @valid_options; | |
310 | for my $o (keys %$options) { | |
311 | die "'$o' is not a recognized argument" unless $valid_options{$o}; | |
312 | } | |
313 | return 1; | |
314 | } | |
315 | ||
316 | sub _get_header_mode { | |
317 | my $class = shift; | |
318 | my $options = shift; | |
319 | ||
320 | # header mode checking | |
321 | my %valid_modes = map {$_=>1} qw(none salt randomiv); | |
322 | my $header_mode = $options->{header}; | |
323 | $header_mode ||= 'none' if exists $options->{prepend_iv} && !$options->{prepend_iv}; | |
324 | $header_mode ||= 'none' if exists $options->{add_header} && !$options->{add_header}; | |
325 | $header_mode ||= 'none' if $options->{literal_key} || (exists $options->{pbkdf} && $options->{pbkdf} eq 'none'); | |
326 | $header_mode ||= 'salt'; # default | |
327 | croak "Invalid -header mode '$header_mode'" unless $valid_modes{$header_mode}; | |
328 | ||
329 | return $header_mode; | |
330 | } | |
331 | ||
332 | sub _get_padding_mode { | |
333 | my $class = shift; | |
334 | my ($bs,$options) = @_; | |
335 | ||
336 | my $padding = $options->{padding} || 'standard'; | |
337 | ||
338 | if ($padding && ref($padding) eq 'CODE') { | |
339 | # check to see that this code does its padding correctly | |
340 | for my $i (1..$bs-1) { | |
341 | my $rbs = length($padding->(" "x$i,$bs,'e')); | |
342 | croak "padding method callback does not behave properly: expected $bs bytes back, got $rbs bytes back." | |
343 | unless ($rbs == $bs); | |
344 | } | |
345 | } else { | |
346 | $padding = $padding eq 'none' ? \&_no_padding | |
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 | return $padding; | |
355 | } | |
356 | ||
357 | sub _get_key_and_block_sizes { | |
358 | my $class = shift; | |
359 | my $cipher = shift; | |
360 | my $options = shift; | |
361 | ||
362 | # allow user to override the keysize value | |
363 | my $ks = $options->{keysize} || eval {$cipher->keysize} || eval {$cipher->max_keysize} | |
364 | or croak "Cannot derive keysize from $cipher"; | |
365 | ||
366 | my $bs = eval {$cipher->blocksize} | |
367 | or croak "$cipher did not provide a blocksize"; | |
368 | ||
369 | return ($ks,$bs); | |
370 | } | |
371 | ||
372 | sub _get_key_materials { | |
373 | my $self = shift; | |
374 | 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 | my $pass = $options->{pass} || $options->{key}; | |
379 | ||
380 | my $cipher_object_provided = $options->{cipher} && ref $options->{cipher}; | |
381 | if ($cipher_object_provided) { | |
382 | carp "Both a key and a pre-initialized Crypt::* object were passed. The key will be ignored" | |
383 | if defined $pass; | |
384 | $pass ||= ''; | |
385 | } | |
386 | ||
387 | 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 | if exists $options->{literal_key} && exists $options->{regenerate_key}; | |
394 | ||
395 | my $key = $pass if $options->{literal_key}; | |
396 | $key = $pass if exists $options->{regenerate_key} && !$options->{regenerate_key}; | |
397 | ||
398 | # Get the salt. | |
399 | my $salt = $options->{salt}; | |
400 | my $random_salt = 1 unless defined $salt && $salt ne '1'; | |
401 | croak "Argument to -salt must be exactly 8 bytes long" if defined $salt && length $salt != 8 && $salt ne '1'; | |
402 | ||
403 | # note: iv will be autogenerated by start() if not specified in options | |
404 | my $iv = $options->{iv}; | |
405 | my $random_iv = 1 unless defined $iv; | |
406 | ||
407 | my $literal_key = $options->{literal_key} || (exists $options->{regenerate_key} && !$options->{regenerate_key}); | |
408 | undef $pass if $literal_key; | |
409 | ||
410 | return ($pass,$iv,$salt,$key,$random_salt,$random_iv); | |
411 | } | |
412 | ||
413 | sub _get_key_derivation_options { | |
414 | my $self = shift; | |
415 | 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 | my $pbkdf = $options->{pbkdf} || ($options->{literal_key} ? 'none' | |
423 | :$header_mode eq 'randomiv' ? 'randomiv' | |
424 | :DEFAULT_PBKDF); | |
425 | # iterations | |
426 | my $iter = $options->{iter} || DEFAULT_ITER; | |
427 | $iter =~ /[\d_]+/ && $iter >= 1 or croak "-iterations argument must be greater than or equal to 1"; | |
428 | $iter =~ /[\d_]+/ && $iter >= 1 or croak "-iterations argument must be greater than or equal to 1"; | |
429 | ||
430 | # hasher | |
431 | my $hc = $options->{hasher}; | |
432 | my $nodeprecate = $options->{nodeprecate}; | |
433 | ||
434 | return ($pbkdf,$iter,$hc,$nodeprecate); | |
435 | } | |
436 | ||
437 | sub _get_chain_mode { | |
438 | my $self = shift; | |
439 | my $options = shift; | |
440 | return $options->{chain_mode} ? $options->{chain_mode} | |
441 | :$options->{pcbc} ? 'pcbc' | |
442 | :'cbc'; | |
443 | } | |
444 | ||
445 | sub _load_module { | |
446 | my $self = shift; | |
447 | my ($module,$args) = @_; | |
448 | my $result = eval "use $module $args; 1;"; | |
449 | warn $@ if $@; | |
450 | return $result; | |
451 | } | |
452 | ||
453 | sub _deprecation_warning { | |
454 | my $self = shift; | |
455 | return if $self->nodeprecate; | |
456 | return if $self->{decrypt}; | |
457 | my $pbkdf = $self->pbkdf; | |
458 | 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 | my $self = shift; | |
469 | $self->chain_mode =~ /^p?cbc$/ && $self->padding ne \&_no_padding; | |
470 | } | |
471 | ||
472 | sub _cbc_encrypt { | |
473 | my $self = shift; | |
474 | my ($crypt,$iv,$result,$blocks) = @_; | |
475 | # the copying looks silly, but it is slightly faster than dereferencing the | |
476 | # variables each time | |
477 | my ($i,$r) = ($$iv,$$result); | |
478 | foreach (@$blocks) { | |
479 | $r .= $i = $crypt->encrypt($i ^ $_); | |
480 | } | |
481 | ($$iv,$$result) = ($i,$r); | |
482 | } | |
483 | ||
484 | sub _cbc_decrypt { | |
485 | my $self = shift; | |
486 | my ($crypt,$iv,$result,$blocks) = @_; | |
487 | # the copying looks silly, but it is slightly faster than dereferencing the | |
488 | # variables each time | |
489 | my ($i,$r) = ($$iv,$$result); | |
490 | foreach (@$blocks) { | |
491 | $r .= $i ^ $crypt->decrypt($_); | |
492 | $i = $_; | |
493 | } | |
494 | ($$iv,$$result) = ($i,$r); | |
495 | } | |
496 | ||
497 | sub _pcbc_encrypt { | |
498 | my $self = shift; | |
499 | my ($crypt,$iv,$result,$blocks) = @_; | |
500 | foreach my $plaintext (@$blocks) { | |
501 | $$result .= $$iv = $crypt->encrypt($$iv ^ $plaintext); | |
502 | $$iv ^= $plaintext; | |
503 | } | |
504 | } | |
505 | ||
506 | sub _pcbc_decrypt { | |
507 | my $self = shift; | |
508 | my ($crypt,$iv,$result,$blocks) = @_; | |
509 | foreach my $ciphertext (@$blocks) { | |
510 | $$result .= $$iv = $$iv ^ $crypt->decrypt($ciphertext); | |
511 | $$iv ^= $ciphertext; | |
512 | } | |
513 | } | |
514 | ||
515 | sub _cfb_encrypt { | |
516 | my $self = shift; | |
517 | my ($crypt,$iv,$result,$blocks) = @_; | |
518 | my ($i,$r) = ($$iv,$$result); | |
519 | foreach my $plaintext (@$blocks) { | |
520 | $r .= $i = $plaintext ^ $crypt->encrypt($i) | |
521 | } | |
522 | ($$iv,$$result) = ($i,$r); | |
523 | } | |
524 | ||
525 | sub _cfb_decrypt { | |
526 | my $self = shift; | |
527 | my ($crypt,$iv,$result,$blocks) = @_; | |
528 | my ($i,$r) = ($$iv,$$result); | |
529 | foreach my $ciphertext (@$blocks) { | |
530 | $r .= $ciphertext ^ $crypt->encrypt($i); | |
531 | $i = $ciphertext; | |
532 | } | |
533 | ($$iv,$$result) = ($i,$r); | |
534 | } | |
535 | ||
536 | sub _ofb_encrypt { | |
537 | my $self = shift; | |
538 | my ($crypt,$iv,$result,$blocks) = @_; | |
539 | my ($i,$r) = ($$iv,$$result); | |
540 | foreach my $plaintext (@$blocks) { | |
541 | my $ciphertext = $plaintext ^ ($i = $crypt->encrypt($i)); | |
542 | substr($ciphertext,length $plaintext) = ''; # truncate | |
543 | $r .= $ciphertext; | |
544 | } | |
545 | ($$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 | my $self = shift; | |
559 | my ($crypt,$iv,$result,$blocks) = @_; | |
560 | my $bs = $self->blocksize; | |
561 | ||
562 | $self->_upgrade_iv_to_ctr($iv); | |
563 | my ($i,$r) = ($$iv,$$result); | |
564 | ||
565 | foreach my $plaintext (@$blocks) { | |
566 | 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 | if ($bs > length $bytes) { | |
571 | substr($bytes,0,0) = "\000"x($bs-length $bytes) ; | |
572 | } | |
573 | ||
574 | my $ciphertext = $plaintext ^ ($crypt->encrypt($bytes)); | |
575 | substr($ciphertext,length $plaintext) = ''; # truncate | |
576 | $r .= $ciphertext; | |
577 | } | |
578 | ($$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 | my $self = shift; | |
587 | my $iv = shift; # this is a scalar reference | |
588 | return if ref $$iv; # already upgraded to an object | |
589 | ||
590 | $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 | $$iv = net_to_int128($$iv); | |
594 | return 1; | |
595 | } | |
596 | ||
597 | ######################################### chaining mode methods ################################3 | |
598 | ||
599 | sub pbkdf { shift->{pbkdf} } | |
600 | ||
601 | # get the initialized PBKDF object | |
602 | sub pbkdf_obj { | |
603 | my $self = shift; | |
604 | my $pbkdf = $self->pbkdf; | |
605 | my $iter = $self->{iter}; | |
606 | my $hc = $self->{hasher}; | |
607 | my @hash_args = $hc ? ref ($hc) ? (hasher => $hc) : (hash_class => $hc) | |
608 | : (); | |
609 | return Crypt::CBC::PBKDF->new($pbkdf => | |
610 | { | |
611 | key_len => $self->{keysize}, | |
612 | iv_len => $self->{blocksize}, | |
613 | iterations => $iter, | |
614 | @hash_args, | |
615 | } | |
616 | ); | |
617 | } | |
618 | ||
619 | ############################# generating key, iv and salt ######################## | |
620 | # hopefully a replacement for mess below | |
621 | sub set_key_and_iv { | |
622 | my $self = shift; | |
623 | ||
624 | if (!$self->{literal_key}) { | |
625 | my ($key,$iv) = $self->pbkdf_obj->key_and_iv($self->{salt},$self->{passphrase}); | |
626 | $self->{key} = $key; | |
627 | $self->{iv} = $iv if $self->{make_random_iv}; | |
628 | } else { | |
629 | $self->{iv} = $self->_get_random_bytes($self->blocksize) if $self->{make_random_iv}; | |
630 | } | |
631 | ||
632 | length $self->{salt} == 8 or croak "Salt must be exactly 8 bytes long"; | |
633 | length $self->{iv} == $self->{blocksize} or croak "IV must be exactly $self->{blocksize} bytes long"; | |
634 | } | |
635 | ||
636 | # derive the salt, iv and key from the datastream header + passphrase | |
637 | sub _read_key_and_iv { | |
638 | my $self = shift; | |
639 | my $input_stream = shift; | |
640 | my $bs = $self->blocksize; | |
641 | ||
642 | # use our header mode to figure out what to do with the data stream | |
643 | my $header_mode = $self->header_mode; | |
644 | ||
645 | if ($header_mode eq 'none') { | |
646 | $self->{salt} ||= $self->_get_random_bytes(8); | |
647 | return $self->set_key_and_iv; | |
648 | } | |
649 | ||
650 | elsif ($header_mode eq 'salt') { | |
651 | ($self->{salt}) = $$input_stream =~ /^Salted__(.{8})/s; | |
652 | croak "Ciphertext does not begin with a valid header for 'salt' header mode" unless defined $self->{salt}; | |
653 | substr($$input_stream,0,16) = ''; | |
654 | my ($k,$i) = $self->pbkdf_obj->key_and_iv($self->{salt},$self->{passphrase}); | |
655 | $self->{key} = $k unless $self->{literal_key}; | |
656 | $self->{iv} = $i unless $self->{literal_iv}; | |
657 | } | |
658 | ||
659 | elsif ($header_mode eq 'randomiv') { | |
660 | ($self->{iv}) = $$input_stream =~ /^RandomIV(.{8})/s; | |
661 | croak "Ciphertext does not begin with a valid header for 'randomiv' header mode" unless defined $self->{iv}; | |
662 | croak "randomiv header mode cannot be used securely when decrypting with a >8 byte block cipher.\n" | |
663 | unless $self->blocksize == 8; | |
664 | (undef,$self->{key}) = $self->pbkdf_obj->key_and_iv(undef,$self->{passphrase}); | |
665 | substr($$input_stream,0,16) = ''; # truncate | |
666 | } | |
667 | ||
668 | else { | |
669 | croak "Invalid header mode '$header_mode'"; | |
670 | } | |
671 | } | |
672 | ||
673 | # this subroutine will generate the actual {en,de}cryption key, the iv | |
674 | # and the block cipher object. This is called when reading from a datastream | |
675 | # and so it uses previous values of salt or iv if they are encoded in datastream | |
676 | # header | |
677 | sub _generate_iv_and_cipher_from_datastream { | |
678 | my $self = shift; | |
679 | my $input_stream = shift; | |
680 | ||
681 | $self->_read_key_and_iv($input_stream); | |
682 | $self->{civ} = $self->{iv}; | |
683 | ||
684 | # we should have the key and iv now, or we are dead in the water | |
685 | croak "Could not derive key or iv from cipher stream, and you did not specify these values in new()" | |
686 | unless $self->{key} && $self->{civ}; | |
687 | ||
688 | # now we can generate the crypt object itself | |
689 | $self->{crypt} = ref $self->{cipher} ? $self->{cipher} | |
690 | : $self->{cipher}->new($self->{key}) | |
691 | or croak "Could not create $self->{cipher} object: $@"; | |
692 | return ''; | |
693 | } | |
694 | ||
695 | sub _generate_iv_and_cipher_from_options { | |
696 | my $self = shift; | |
697 | ||
698 | $self->{salt} = $self->_get_random_bytes(8) if $self->{make_random_salt}; | |
699 | $self->set_key_and_iv; | |
700 | $self->{civ} = $self->{iv}; | |
701 | ||
702 | my $result = ''; | |
703 | my $header_mode = $self->header_mode; | |
704 | ||
705 | if ($header_mode eq 'salt') { | |
706 | $result = "Salted__$self->{salt}"; | |
707 | } | |
708 | ||
709 | elsif ($header_mode eq 'randomiv') { | |
710 | $result = "RandomIV$self->{iv}"; | |
711 | undef $self->{salt}; # shouldn't be there! | |
712 | } | |
713 | ||
714 | croak "key and/or iv are missing" unless defined $self->{key} && defined $self->{civ}; | |
715 | ||
716 | $self->_taintcheck($self->{key}); | |
717 | $self->{crypt} = ref $self->{cipher} ? $self->{cipher} | |
718 | : $self->{cipher}->new($self->{key}) | |
719 | or croak "Could not create $self->{cipher} object: $@"; | |
720 | return $result; | |
721 | } | |
722 | ||
723 | sub _taintcheck { | |
724 | my $self = shift; | |
725 | my $key = shift; | |
726 | return unless ${^TAINT}; | |
727 | ||
728 | my $has_scalar_util = eval "require Scalar::Util; 1"; | |
729 | my $tainted; | |
730 | ||
731 | ||
732 | if ($has_scalar_util) { | |
733 | $tainted = Scalar::Util::tainted($key); | |
734 | } else { | |
735 | local($@, $SIG{__DIE__}, $SIG{__WARN__}); | |
736 | local $^W = 0; | |
737 | eval { kill 0 * $key }; | |
738 | $tainted = $@ =~ /^Insecure/; | |
739 | } | |
740 | ||
741 | croak "Taint checks are turned on and your key is tainted. Please untaint the key and try again" | |
742 | if $tainted; | |
743 | } | |
744 | ||
745 | sub _digest_obj { | |
746 | my $self = shift; | |
747 | ||
748 | if ($self->{digest_obj}) { | |
749 | $self->{digest_obj}->reset(); | |
750 | return $self->{digest_obj}; | |
751 | } | |
752 | ||
753 | my $alg = $self->{digest_alg}; | |
754 | return $alg if ref $alg && $alg->can('digest'); | |
755 | my $obj = eval {Digest->new($alg)}; | |
756 | croak "Unable to instantiate '$alg' digest object: $@" if $@; | |
757 | ||
758 | return $self->{digest_obj} = $obj; | |
759 | } | |
760 | ||
761 | sub random_bytes { | |
762 | my $self = shift; | |
763 | my $bytes = shift or croak "usage: random_bytes(\$byte_length)"; | |
764 | $self->_get_random_bytes($bytes); | |
765 | } | |
766 | ||
767 | sub _get_random_bytes { | |
768 | my $self = shift; | |
769 | my $length = shift; | |
770 | my $result; | |
771 | ||
772 | if (-r RANDOM_DEVICE && open(F,RANDOM_DEVICE)) { | |
773 | read(F,$result,$length); | |
774 | close F; | |
775 | } else { | |
776 | $result = pack("C*",map {rand(256)} 1..$length); | |
777 | } | |
778 | # Clear taint and check length | |
779 | $result =~ /^(.+)$/s; | |
780 | length($1) == $length or croak "Invalid length while gathering $length random bytes"; | |
781 | return $1; | |
782 | } | |
783 | ||
784 | sub _standard_padding ($$$) { | |
785 | my ($b,$bs,$decrypt) = @_; | |
786 | ||
787 | if ($decrypt eq 'd') { | |
788 | my $pad_length = unpack("C",substr($b,-1)); | |
789 | return substr($b,0,$bs-$pad_length); | |
790 | } | |
791 | my $pad = $bs - length($b); | |
792 | return $b . pack("C*",($pad)x$pad); | |
793 | } | |
794 | ||
795 | sub _space_padding ($$$) { | |
796 | my ($b,$bs,$decrypt) = @_; | |
797 | ||
798 | if ($decrypt eq 'd') { | |
799 | $b=~ s/ *\z//s; | |
800 | } else { | |
801 | $b .= pack("C*", (32) x ($bs-length($b))); | |
802 | } | |
803 | return $b; | |
804 | } | |
805 | ||
806 | sub _no_padding ($$$) { | |
807 | my ($b,$bs,$decrypt) = @_; | |
808 | return $b; | |
809 | } | |
810 | ||
811 | sub _null_padding ($$$) { | |
812 | my ($b,$bs,$decrypt) = @_; | |
813 | return unless length $b; | |
814 | $b = length $b ? $b : ''; | |
815 | if ($decrypt eq 'd') { | |
816 | $b=~ s/\0*\z//s; | |
817 | return $b; | |
818 | } | |
819 | return $b . pack("C*", (0) x ($bs - length($b) % $bs)); | |
820 | } | |
821 | ||
822 | sub _oneandzeroes_padding ($$$) { | |
823 | my ($b,$bs,$decrypt) = @_; | |
824 | if ($decrypt eq 'd') { | |
825 | $b=~ s/\x80\0*\z//s; | |
826 | return $b; | |
827 | } | |
828 | return $b . pack("C*", 128, (0) x ($bs - length($b) - 1) ); | |
829 | } | |
830 | ||
831 | sub _rijndael_compat ($$$) { | |
832 | my ($b,$bs,$decrypt) = @_; | |
833 | ||
834 | return unless length $b; | |
835 | if ($decrypt eq 'd') { | |
836 | $b=~ s/\x80\0*\z//s; | |
837 | return $b; | |
838 | } | |
839 | return $b . pack("C*", 128, (0) x ($bs - length($b) % $bs - 1) ); | |
840 | } | |
841 | ||
842 | sub get_initialization_vector (\$) { | |
843 | my $self = shift; | |
844 | $self->iv(); | |
845 | } | |
846 | ||
847 | sub set_initialization_vector (\$$) { | |
848 | my $self = shift; | |
849 | my $iv = shift; | |
850 | my $bs = $self->blocksize; | |
851 | croak "Initialization vector must be $bs bytes in length" unless length($iv) == $bs; | |
852 | $self->iv($iv); | |
853 | } | |
854 | ||
855 | sub salt { | |
856 | my $self = shift; | |
857 | my $d = $self->{salt}; | |
858 | $self->{salt} = shift if @_; | |
859 | $d; | |
860 | } | |
861 | ||
862 | sub iv { | |
863 | my $self = shift; | |
864 | my $d = $self->{iv}; | |
865 | $self->{iv} = shift if @_; | |
866 | $d; | |
867 | } | |
868 | ||
869 | sub key { | |
870 | my $self = shift; | |
871 | my $d = $self->{key}; | |
872 | $self->{key} = shift if @_; | |
873 | $d; | |
874 | } | |
875 | ||
876 | sub passphrase { | |
877 | my $self = shift; | |
878 | my $d = $self->{passphrase}; | |
879 | if (@_) { | |
880 | undef $self->{key}; | |
881 | undef $self->{iv}; | |
882 | $self->{passphrase} = shift; | |
883 | } | |
884 | $d; | |
885 | } | |
886 | ||
887 | sub keysize { | |
888 | my $self = shift; | |
889 | $self->{keysize} = shift if @_; | |
890 | $self->{keysize}; | |
891 | } | |
892 | ||
893 | sub cipher { shift->{cipher} } | |
894 | sub padding { shift->{padding} } | |
895 | sub blocksize { shift->{blocksize} } | |
896 | sub pcbc { shift->{pcbc} } | |
897 | sub header_mode {shift->{header_mode} } | |
898 | sub literal_key {shift->{literal_key}} | |
899 | sub nodeprecate {shift->{nodeprecate}} | |
900 | ||
901 | 1; | |
902 | __END__ | |
903 | ||
904 | =head1 NAME | |
905 | ||
906 | Crypt::CBC - Encrypt Data with Cipher Block Chaining Mode | |
907 | ||
908 | =head1 SYNOPSIS | |
909 | ||
910 | use Crypt::CBC; | |
911 | $cipher = Crypt::CBC->new( -pass => 'my secret password', | |
912 | -cipher => 'Cipher::AES' | |
913 | ); | |
914 | ||
915 | # one shot mode | |
916 | $ciphertext = $cipher->encrypt("This data is hush hush"); | |
917 | $plaintext = $cipher->decrypt($ciphertext); | |
918 | ||
919 | # stream mode | |
920 | $cipher->start('encrypting'); | |
921 | open(F,"./BIG_FILE"); | |
922 | while (read(F,$buffer,1024)) { | |
923 | print $cipher->crypt($buffer); | |
924 | } | |
925 | print $cipher->finish; | |
926 | ||
927 | # do-it-yourself mode -- specify key && initialization vector yourself | |
928 | $key = Crypt::CBC->random_bytes(8); # assuming a 8-byte block cipher | |
929 | $iv = Crypt::CBC->random_bytes(8); | |
930 | $cipher = Crypt::CBC->new(-pbkdf => 'none', | |
931 | -key => $key, | |
932 | -iv => $iv); | |
933 | ||
934 | $ciphertext = $cipher->encrypt("This data is hush hush"); | |
935 | $plaintext = $cipher->decrypt($ciphertext); | |
936 | ||
937 | # encrypting via a filehandle (requires Crypt::FileHandle> | |
938 | $fh = Crypt::CBC->filehandle(-pass => 'secret'); | |
939 | open $fh,'>','encrypted.txt" or die $! | |
940 | print $fh "This will be encrypted\n"; | |
941 | close $fh; | |
942 | ||
943 | =head1 DESCRIPTION | |
944 | ||
945 | This module is a Perl-only implementation of the cryptographic cipher | |
946 | block chaining mode (CBC). In combination with a block cipher such as | |
947 | AES or Blowfish, you can encrypt and decrypt messages of arbitrarily | |
948 | long length. The encrypted messages are compatible with the | |
949 | encryption format used by the B<OpenSSL> package. | |
950 | ||
951 | To use this module, you will first create a Crypt::CBC cipher object | |
952 | with new(). At the time of cipher creation, you specify an encryption | |
953 | key to use and, optionally, a block encryption algorithm. You will | |
954 | then call the start() method to initialize the encryption or | |
955 | decryption process, crypt() to encrypt or decrypt one or more blocks | |
956 | of data, and lastly finish(), to pad and encrypt the final block. For | |
957 | your convenience, you can call the encrypt() and decrypt() methods to | |
958 | operate on a whole data value at once. | |
959 | ||
960 | =head2 new() | |
961 | ||
962 | $cipher = Crypt::CBC->new( -pass => 'my secret key', | |
963 | -cipher => 'Cipher::AES', | |
964 | ); | |
965 | ||
966 | # or (for compatibility with versions prior to 2.0) | |
967 | $cipher = new Crypt::CBC('my secret key' => 'Cipher::AES'); | |
968 | ||
969 | The new() method creates a new Crypt::CBC object. It accepts a list of | |
970 | -argument => value pairs selected from the following list: | |
971 | ||
972 | Argument Description | |
973 | -------- ----------- | |
974 | ||
975 | -pass,-key The encryption/decryption passphrase. These arguments | |
976 | are interchangeable, but -pass is preferred | |
977 | ("key" is a misnomer, as it is not the literal | |
978 | encryption key). | |
979 | ||
980 | -cipher The cipher algorithm (defaults to Crypt::Cipher:AES), or | |
981 | a previously created cipher object reference. For | |
982 | convenience, you may omit the initial "Crypt::" part | |
983 | of the classname and use the basename, e.g. "Blowfish" | |
984 | instead of "Crypt::Blowfish". | |
985 | ||
986 | -keysize Force the cipher keysize to the indicated number of bytes. This can be used | |
987 | to set the keysize for variable keylength ciphers such as AES. | |
988 | ||
989 | -chain_mode The block chaining mode to use. Current options are: | |
990 | 'cbc' -- cipher-block chaining mode [default] | |
991 | 'pcbc' -- plaintext cipher-block chaining mode | |
992 | 'cfb' -- cipher feedback mode | |
993 | 'ofb' -- output feedback mode | |
994 | 'ctr' -- counter mode | |
995 | ||
996 | -pbkdf The passphrase-based key derivation function used to derive | |
997 | the encryption key and initialization vector from the | |
998 | provided passphrase. For backward compatibility, Crypt::CBC | |
999 | will default to "opensslv1", but it is recommended to use | |
1000 | the standard "pbkdf2"algorithm instead. If you wish to interoperate | |
1001 | with OpenSSL, be aware that different versions of the software | |
1002 | support a series of derivation functions. | |
1003 | ||
1004 | 'none' -- The value provided in -pass/-key is used directly. | |
1005 | This is the same as passing true to -literal_key. | |
1006 | You must also manually specify the IV with -iv. | |
1007 | The key and the IV must match the keylength | |
1008 | and blocklength of the chosen cipher. | |
1009 | 'randomiv' -- Use insecure key derivation method found | |
1010 | in prehistoric versions of OpenSSL (dangerous) | |
1011 | 'opensslv1' -- [default] Use the salted MD5 method that was default | |
1012 | in versions of OpenSSL through v1.0.2. | |
1013 | 'opensslv2' -- [better] Use the salted SHA-256 method that was | |
1014 | the default in versions of OpenSSL through v1.1.0. | |
1015 | 'pbkdf2' -- [best] Use the PBKDF2 method that was first | |
1016 | introduced in OpenSSL v1.1.1. | |
1017 | ||
1018 | More derivation functions may be added in the future. To see the | |
1019 | supported list, use the command | |
1020 | perl -MCrypt::CBC::PBKDF -e 'print join "\n",Crypt::CBC::PBKDF->list' | |
1021 | ||
1022 | -iter If the 'pbkdf2' key derivation algorithm is used, this specifies the number of | |
1023 | hashing cycles to be applied to the passphrase+salt (longer is more secure). | |
1024 | [default 10,000] | |
1025 | ||
1026 | -hasher If the 'pbkdf2' key derivation algorithm is chosen, you can use this to provide | |
1027 | an initialized Crypt::PBKDF2::Hash object. | |
1028 | [default HMACSHA2 for OpenSSL compatability] | |
1029 | ||
1030 | -header What type of header to prepend to the ciphertext. One of | |
1031 | 'salt' -- use OpenSSL-compatible salted header (default) | |
1032 | 'randomiv' -- Randomiv-compatible "RandomIV" header | |
1033 | 'none' -- prepend no header at all | |
1034 | (compatible with prehistoric versions | |
1035 | of OpenSSL) | |
1036 | ||
1037 | -iv The initialization vector (IV). If not provided, it will be generated | |
1038 | by the key derivation function. | |
1039 | ||
1040 | -salt The salt passed to the key derivation function. If not provided, will be | |
1041 | generated randomly (recommended). | |
1042 | ||
1043 | -padding The padding method, one of "standard" (default), | |
1044 | "space", "oneandzeroes", "rijndael_compat", | |
1045 | "null", or "none" (default "standard"). | |
1046 | ||
1047 | -literal_key [deprected, use -pbkdf=>'none'] | |
1048 | If true, the key provided by "-key" or "-pass" is used | |
1049 | directly for encryption/decryption without salting or | |
1050 | hashing. The key must be the right length for the chosen | |
1051 | cipher. | |
1052 | [default false) | |
1053 | ||
1054 | -pcbc [deprecated, use -chaining_mode=>'pcbc'] | |
1055 | Whether to use the PCBC chaining algorithm rather than | |
1056 | the standard CBC algorithm (default false). | |
1057 | ||
1058 | -add_header [deprecated; use -header instead] | |
1059 | Whether to add the salt and IV to the header of the output | |
1060 | cipher text. | |
1061 | ||
1062 | -regenerate_key [deprecated; use -literal_key instead] | |
1063 | Whether to use a hash of the provided key to generate | |
1064 | the actual encryption key (default true) | |
1065 | ||
1066 | -prepend_iv [deprecated; use -header instead] | |
1067 | Whether to prepend the IV to the beginning of the | |
1068 | encrypted stream (default true) | |
1069 | ||
1070 | Crypt::CBC requires three pieces of information to do its job. First | |
1071 | it needs the name of the block cipher algorithm that will encrypt or | |
1072 | decrypt the data in blocks of fixed length known as the cipher's | |
1073 | "blocksize." Second, it needs an encryption/decryption key to pass to | |
1074 | the block cipher. Third, it needs an initialization vector (IV) that | |
1075 | will be used to propagate information from one encrypted block to the | |
1076 | next. Both the key and the IV must be exactly the same length as the | |
1077 | chosen cipher's blocksize. | |
1078 | ||
1079 | Crypt::CBC can derive the key and the IV from a passphrase that you | |
1080 | provide, or can let you specify the true key and IV manually. In | |
1081 | addition, you have the option of embedding enough information to | |
1082 | regenerate the IV in a short header that is emitted at the start of | |
1083 | the encrypted stream, or outputting a headerless encryption stream. In | |
1084 | the first case, Crypt::CBC will be able to decrypt the stream given | |
1085 | just the original key or passphrase. In the second case, you will have | |
1086 | to provide the original IV as well as the key/passphrase. | |
1087 | ||
1088 | The B<-cipher> option specifies which block cipher algorithm to use to | |
1089 | encode each section of the message. This argument is optional and | |
1090 | will default to the secure Crypt::Cipher::AES algorithm. | |
1091 | You may use any compatible block encryption | |
1092 | algorithm that you have installed. Currently, this includes | |
1093 | Crypt::Cipher::AES, Crypt::DES, Crypt::DES_EDE3, Crypt::IDEA, Crypt::Blowfish, | |
1094 | Crypt::CAST5 and Crypt::Rijndael. You may refer to them using their | |
1095 | full names ("Crypt::IDEA") or in abbreviated form ("IDEA"). | |
1096 | ||
1097 | Instead of passing the name of a cipher class, you may pass an | |
1098 | already-created block cipher object. This allows you to take advantage | |
1099 | of cipher algorithms that have parameterized new() methods, such as | |
1100 | Crypt::Eksblowfish: | |
1101 | ||
1102 | my $eksblowfish = Crypt::Eksblowfish->new(8,$salt,$key); | |
1103 | my $cbc = Crypt::CBC->new(-cipher=>$eksblowfish); | |
1104 | ||
1105 | The B<-pass> argument provides a passphrase to use to generate the | |
1106 | encryption key or the literal value of the block cipher key. If used | |
1107 | in passphrase mode (which is the default), B<-pass> can be any number | |
1108 | of characters; the actual key will be derived by passing the | |
1109 | passphrase through a series of hashing operations. To take full | |
1110 | advantage of a given block cipher, the length of the passphrase should | |
1111 | be at least equal to the cipher's blocksize. For backward | |
1112 | compatibility, you may also refer to this argument using B<-key>. | |
1113 | ||
1114 | To skip this hashing operation and specify the key directly, provide | |
1115 | the actual key as a string to B<-key> and specify a key derivation | |
1116 | function of "none" to the B<-pbkdf> argument. Alternatively, you may | |
1117 | pass a true value to the B<-literal_key> argument. When you manually | |
1118 | specify the key in this way, should choose a key of length exactly | |
1119 | equal to the cipher's key length. You will also have to specify an IV | |
1120 | equal in length to the cipher's blocksize. These choices imply a | |
1121 | header mode of "none." | |
1122 | ||
1123 | If you pass an existing Crypt::* object to new(), then the | |
1124 | B<-pass>/B<-key> argument is ignored and the module will generate a | |
1125 | warning. | |
1126 | ||
1127 | The B<-pbkdf> argument specifies the algorithm used to derive the true | |
1128 | key and IV from the provided passphrase (PBKDF stands for | |
1129 | "passphrase-based key derivation function"). Valid values are: | |
1130 | ||
1131 | "opensslv1" -- [default] A fast algorithm that derives the key by | |
1132 | combining a random salt values with the passphrase via | |
1133 | a series of MD5 hashes. | |
1134 | ||
1135 | "opensslv2" -- an improved version that uses SHA-256 rather | |
1136 | than MD5, and has been OpenSSL's default since v1.1.0. | |
1137 | However, it has been deprecated in favor of pbkdf2 | |
1138 | since OpenSSL v1.1.1. | |
1139 | ||
1140 | "pbkdf2" -- a better algorithm implemented in OpenSSL v1.1.1, | |
1141 | described in RFC 2898 L<https://tools.ietf.org/html/rfc2898> | |
1142 | ||
1143 | "none" -- don't use a derivation function, but treat the passphrase | |
1144 | as the literal key. This is the same as B<-literal_key> true. | |
1145 | ||
1146 | "nosalt" -- an insecure key derivation method used by prehistoric versions | |
1147 | of OpenSSL, provided for backward compatibility. Don't use. | |
1148 | ||
1149 | "opensslv1" was OpenSSL's default key derivation algorithm through | |
1150 | version 1.0.2, but is susceptible to dictionary attacks and is no | |
1151 | longer supported. It remains the default for Crypt::CBC in order to | |
1152 | avoid breaking compatibility with previously-encrypted messages. Using | |
1153 | this option will issue a deprecation warning when initiating | |
1154 | encryption. You can suppress the warning by passing a true value to | |
1155 | the B<-nodeprecate> option. | |
1156 | ||
1157 | It is recommended to specify the "pbkdf2" key derivation algorithm | |
1158 | when compatibility with older versions of Crypt::CBC is not | |
1159 | needed. This algorithm is deliberately computationally expensive in | |
1160 | order to make dictionary-based attacks harder. As a result, it | |
1161 | introduces a slight delay before an encryption or decryption | |
1162 | operation starts. | |
1163 | ||
1164 | The B<-iter> argument is used in conjunction with the "pbkdf2" key | |
1165 | derivation option. Its value indicates the number of hashing cycles | |
1166 | used to derive the key. Larger values are more secure, but impose a | |
1167 | longer delay before encryption/decryption starts. The default is | |
1168 | 10,000 for compatibility with OpenSSL's default. | |
1169 | ||
1170 | The B<-hasher> argument is used in conjunction with the "pbkdf2" key | |
1171 | derivation option to pass the reference to an initialized | |
1172 | Crypt::PBKDF2::Hash object. If not provided, it defaults to the | |
1173 | OpenSSL-compatible hash function HMACSHA2 initialized with its default | |
1174 | options (SHA-256 hash). | |
1175 | ||
1176 | The B<-header> argument specifies what type of header, if any, to | |
1177 | prepend to the beginning of the encrypted data stream. The header | |
1178 | allows Crypt::CBC to regenerate the original IV and correctly decrypt | |
1179 | the data without your having to provide the same IV used to encrypt | |
1180 | the data. Valid values for the B<-header> are: | |
1181 | ||
1182 | "salt" -- Combine the passphrase with an 8-byte random value to | |
1183 | generate both the block cipher key and the IV from the | |
1184 | provided passphrase. The salt will be appended to the | |
1185 | beginning of the data stream allowing decryption to | |
1186 | regenerate both the key and IV given the correct passphrase. | |
1187 | This method is compatible with current versions of OpenSSL. | |
1188 | ||
1189 | "randomiv" -- Generate the block cipher key from the passphrase, and | |
1190 | choose a random 8-byte value to use as the IV. The IV will | |
1191 | be prepended to the data stream. This method is compatible | |
1192 | with ciphertext produced by versions of the library prior to | |
1193 | 2.17, but is incompatible with block ciphers that have non | |
1194 | 8-byte block sizes, such as Rijndael. Crypt::CBC will exit | |
1195 | with a fatal error if you try to use this header mode with a | |
1196 | non 8-byte cipher. This header type is NOT secure and NOT | |
1197 | recommended. | |
1198 | ||
1199 | "none" -- Do not generate a header. To decrypt a stream encrypted | |
1200 | in this way, you will have to provide the true key and IV | |
1201 | manually. | |
1202 | ||
1203 | B<The "salt" header is now the default as of Crypt::CBC version 2.17. In | |
1204 | all earlier versions "randomiv" was the default.> | |
1205 | ||
1206 | When using a "salt" header, you may specify your own value of the | |
1207 | salt, by passing the desired 8-byte character string to the B<-salt> | |
1208 | argument. Otherwise, the module will generate a random salt for | |
1209 | you. Crypt::CBC will generate a fatal error if you specify a salt | |
1210 | value that isn't exactly 8 bytes long. For backward compatibility | |
1211 | reasons, passing a value of "1" will generate a random salt, the same | |
1212 | as if no B<-salt> argument was provided. | |
1213 | ||
1214 | The B<-padding> argument controls how the last few bytes of the | |
1215 | encrypted stream are dealt with when they not an exact multiple of the | |
1216 | cipher block length. The default is "standard", the method specified | |
1217 | in PKCS#5. | |
1218 | ||
1219 | The B<-chaining_mode> argument will select among several different | |
1220 | block chaining modes. Values are: | |
1221 | ||
1222 | 'cbc' -- [default] traditional Cipher-Block Chaining mode. It has | |
1223 | the property that if one block in the ciphertext message | |
1224 | is damaged, only that block and the next one will be | |
1225 | rendered un-decryptable. | |
1226 | ||
1227 | 'pcbc' -- Plaintext Cipher-Block Chaining mode. This has the property | |
1228 | that one damaged ciphertext block will render the | |
1229 | remainder of the message unreadable | |
1230 | ||
1231 | 'cfb' -- Cipher Feedback Mode. In this mode, both encryption and decryption | |
1232 | are performed using the block cipher's "encrypt" algorithm. | |
1233 | The error propagation behaviour is similar to CBC's. | |
1234 | ||
1235 | 'ofb' -- Output Feedback Mode. Similar to CFB, the block cipher's encrypt | |
1236 | algorithm is used for both encryption and decryption. If one bit | |
1237 | of the plaintext or ciphertext message is damaged, the damage is | |
1238 | confined to a single block of the corresponding ciphertext or | |
1239 | plaintext, and error correction algorithms can be used to reconstruct | |
1240 | the damaged part. | |
1241 | ||
1242 | 'ctr' -- Counter Mode. This mode uses a one-time "nonce" instead of | |
1243 | an IV. The nonce is incremented by one for each block of | |
1244 | plain or ciphertext, encrypted using the chosen | |
1245 | algorithm, and then applied to the block of text. If one | |
1246 | bit of the input text is damaged, it only affects 1 bit | |
1247 | of the output text. To use CTR mode you will need to | |
1248 | install the Perl Math::Int128 module. This chaining method | |
1249 | is roughly half the speed of the others due to integer | |
1250 | arithmetic. | |
1251 | ||
1252 | Passing a B<-pcbc> argument of true will have the same effect as | |
1253 | -chaining_mode=>'pcbc', and is included for backward | |
1254 | compatibility. [deprecated]. | |
1255 | ||
1256 | For more information on chaining modes, see | |
1257 | L<http://www.crypto-it.net/eng/theory/modes-of-block-ciphers.html>. | |
1258 | ||
1259 | The B<-keysize> argument can be used to force the cipher's | |
1260 | keysize. This is useful for several of the newer algorithms, including | |
1261 | AES, ARIA, Blowfish, and CAMELLIA. If -keysize is not specified, then | |
1262 | Crypt::CBC will use the value returned by the cipher's max_keylength() | |
1263 | method. Note that versions of CBC::Crypt prior to 2.36 could also | |
1264 | allow you to set the blocksie, but this was never supported by any | |
1265 | ciphers and has been removed. | |
1266 | ||
1267 | For compatibility with earlier versions of this module, you can | |
1268 | provide new() with a hashref containing key/value pairs. The key names | |
1269 | are the same as the arguments described earlier, but without the | |
1270 | initial hyphen. You may also call new() with one or two positional | |
1271 | arguments, in which case the first argument is taken to be the key and | |
1272 | the second to be the optional block cipher algorithm. | |
1273 | ||
1274 | ||
1275 | =head2 start() | |
1276 | ||
1277 | $cipher->start('encrypting'); | |
1278 | $cipher->start('decrypting'); | |
1279 | ||
1280 | The start() method prepares the cipher for a series of encryption or | |
1281 | decryption steps, resetting the internal state of the cipher if | |
1282 | necessary. You must provide a string indicating whether you wish to | |
1283 | encrypt or decrypt. "E" or any word that begins with an "e" indicates | |
1284 | encryption. "D" or any word that begins with a "d" indicates | |
1285 | decryption. | |
1286 | ||
1287 | =head2 crypt() | |
1288 | ||
1289 | $ciphertext = $cipher->crypt($plaintext); | |
1290 | ||
1291 | After calling start(), you should call crypt() as many times as | |
1292 | necessary to encrypt the desired data. | |
1293 | ||
1294 | =head2 finish() | |
1295 | ||
1296 | $ciphertext = $cipher->finish(); | |
1297 | ||
1298 | The CBC algorithm must buffer data blocks internally until they are | |
1299 | even multiples of the encryption algorithm's blocksize (typically 8 | |
1300 | bytes). After the last call to crypt() you should call finish(). | |
1301 | This flushes the internal buffer and returns any leftover ciphertext. | |
1302 | ||
1303 | In a typical application you will read the plaintext from a file or | |
1304 | input stream and write the result to standard output in a loop that | |
1305 | might look like this: | |
1306 | ||
1307 | $cipher = new Crypt::CBC('hey jude!'); | |
1308 | $cipher->start('encrypting'); | |
1309 | print $cipher->crypt($_) while <>; | |
1310 | print $cipher->finish(); | |
1311 | ||
1312 | =head2 encrypt() | |
1313 | ||
1314 | $ciphertext = $cipher->encrypt($plaintext) | |
1315 | ||
1316 | This convenience function runs the entire sequence of start(), crypt() | |
1317 | and finish() for you, processing the provided plaintext and returning | |
1318 | the corresponding ciphertext. | |
1319 | ||
1320 | =head2 decrypt() | |
1321 | ||
1322 | $plaintext = $cipher->decrypt($ciphertext) | |
1323 | ||
1324 | This convenience function runs the entire sequence of start(), crypt() | |
1325 | and finish() for you, processing the provided ciphertext and returning | |
1326 | the corresponding plaintext. | |
1327 | ||
1328 | =head2 encrypt_hex(), decrypt_hex() | |
1329 | ||
1330 | $ciphertext = $cipher->encrypt_hex($plaintext) | |
1331 | $plaintext = $cipher->decrypt_hex($ciphertext) | |
1332 | ||
1333 | These are convenience functions that operate on ciphertext in a | |
1334 | hexadecimal representation. B<encrypt_hex($plaintext)> is exactly | |
1335 | equivalent to B<unpack('H*',encrypt($plaintext))>. These functions | |
1336 | can be useful if, for example, you wish to place the encrypted in an | |
1337 | email message. | |
1338 | ||
1339 | =head2 filehandle() | |
1340 | ||
1341 | This method returns a filehandle for transparent encryption or | |
1342 | decryption using Christopher Dunkle's excellent L<Crypt::FileHandle> | |
1343 | module. This module must be installed in order to use this method. | |
1344 | ||
1345 | filehandle() can be called as a class method using the same arguments | |
1346 | as new(): | |
1347 | ||
1348 | $fh = Crypt::CBC->filehandle(-cipher=> 'Blowfish', | |
1349 | -pass => "You'll never guess"); | |
1350 | ||
1351 | or on a previously-created Crypt::CBC object: | |
1352 | ||
1353 | $cbc = Crypt::CBC->new(-cipher=> 'Blowfish', | |
1354 | -pass => "You'll never guess"); | |
1355 | $fh = $cbc->filehandle; | |
1356 | ||
1357 | The filehandle can then be opened using the familiar open() syntax. | |
1358 | Printing to a filehandle opened for writing will encrypt the | |
1359 | data. Filehandles opened for input will be decrypted. | |
1360 | ||
1361 | Here is an example: | |
1362 | ||
1363 | # transparent encryption | |
1364 | open $fh,'>','encrypted.out' or die $!; | |
1365 | print $fh "You won't be able to read me!\n"; | |
1366 | close $fh; | |
1367 | ||
1368 | # transparent decryption | |
1369 | open $fh,'<','encrypted.out' or die $!; | |
1370 | while (<$fh>) { print $_ } | |
1371 | close $fh; | |
1372 | ||
1373 | =head2 get_initialization_vector() | |
1374 | ||
1375 | $iv = $cipher->get_initialization_vector() | |
1376 | ||
1377 | This function will return the IV used in encryption and or decryption. | |
1378 | The IV is not guaranteed to be set when encrypting until start() is | |
1379 | called, and when decrypting until crypt() is called the first | |
1380 | time. Unless the IV was manually specified in the new() call, the IV | |
1381 | will change with every complete encryption operation. | |
1382 | ||
1383 | =head2 set_initialization_vector() | |
1384 | ||
1385 | $cipher->set_initialization_vector('76543210') | |
1386 | ||
1387 | This function sets the IV used in encryption and/or decryption. This | |
1388 | function may be useful if the IV is not contained within the | |
1389 | ciphertext string being decrypted, or if a particular IV is desired | |
1390 | for encryption. Note that the IV must match the chosen cipher's | |
1391 | blocksize bytes in length. | |
1392 | ||
1393 | =head2 iv() | |
1394 | ||
1395 | $iv = $cipher->iv(); | |
1396 | $cipher->iv($new_iv); | |
1397 | ||
1398 | As above, but using a single method call. | |
1399 | ||
1400 | =head2 key() | |
1401 | ||
1402 | $key = $cipher->key(); | |
1403 | $cipher->key($new_key); | |
1404 | ||
1405 | Get or set the block cipher key used for encryption/decryption. When | |
1406 | encrypting, the key is not guaranteed to exist until start() is | |
1407 | called, and when decrypting, the key is not guaranteed to exist until | |
1408 | after the first call to crypt(). The key must match the length | |
1409 | required by the underlying block cipher. | |
1410 | ||
1411 | When salted headers are used, the block cipher key will change after | |
1412 | each complete sequence of encryption operations. | |
1413 | ||
1414 | =head2 salt() | |
1415 | ||
1416 | $salt = $cipher->salt(); | |
1417 | $cipher->salt($new_salt); | |
1418 | ||
1419 | Get or set the salt used for deriving the encryption key and IV when | |
1420 | in OpenSSL compatibility mode. | |
1421 | ||
1422 | =head2 passphrase() | |
1423 | ||
1424 | $passphrase = $cipher->passphrase(); | |
1425 | $cipher->passphrase($new_passphrase); | |
1426 | ||
1427 | This gets or sets the value of the B<passphrase> passed to new() when | |
1428 | B<literal_key> is false. | |
1429 | ||
1430 | =head2 $data = random_bytes($numbytes) | |
1431 | ||
1432 | Return $numbytes worth of random data. On systems that support the | |
1433 | "/dev/urandom" device file, this data will be read from the | |
1434 | device. Otherwise, it will be generated by repeated calls to the Perl | |
1435 | rand() function. | |
1436 | ||
1437 | =head2 cipher(), pbkdf(), padding(), keysize(), blocksize(), chain_mode() | |
1438 | ||
1439 | These read-only methods return the identity of the chosen block cipher | |
1440 | algorithm, the key derivation function (e.g. "opensslv1"), padding | |
1441 | method, key and block size of the chosen block cipher, and what | |
1442 | chaining mode ("cbc", "ofb" ,etc) is being used. | |
1443 | ||
1444 | =head2 Padding methods | |
1445 | ||
1446 | Use the 'padding' option to change the padding method. | |
1447 | ||
1448 | When the last block of plaintext is shorter than the block size, | |
1449 | it must be padded. Padding methods include: "standard" (i.e., PKCS#5), | |
1450 | "oneandzeroes", "space", "rijndael_compat", "null", and "none". | |
1451 | ||
1452 | standard: (default) Binary safe | |
1453 | pads with the number of bytes that should be truncated. So, if | |
1454 | blocksize is 8, then "0A0B0C" will be padded with "05", resulting | |
1455 | in "0A0B0C0505050505". If the final block is a full block of 8 | |
1456 | bytes, then a whole block of "0808080808080808" is appended. | |
1457 | ||
1458 | oneandzeroes: Binary safe | |
1459 | pads with "80" followed by as many "00" necessary to fill the | |
1460 | block. If the last block is a full block and blocksize is 8, a | |
1461 | block of "8000000000000000" will be appended. | |
1462 | ||
1463 | rijndael_compat: Binary safe, with caveats | |
1464 | similar to oneandzeroes, except that no padding is performed if | |
1465 | the last block is a full block. This is provided for | |
1466 | compatibility with Crypt::Rijndael's buit-in MODE_CBC. | |
1467 | Note that Crypt::Rijndael's implementation of CBC only | |
1468 | works with messages that are even multiples of 16 bytes. | |
1469 | ||
1470 | null: text only | |
1471 | pads with as many "00" necessary to fill the block. If the last | |
1472 | block is a full block and blocksize is 8, a block of | |
1473 | "0000000000000000" will be appended. | |
1474 | ||
1475 | space: text only | |
1476 | same as "null", but with "20". | |
1477 | ||
1478 | none: | |
1479 | no padding added. Useful for special-purpose applications where | |
1480 | you wish to add custom padding to the message. | |
1481 | ||
1482 | Both the standard and oneandzeroes paddings are binary safe. The | |
1483 | space and null paddings are recommended only for text data. Which | |
1484 | type of padding you use depends on whether you wish to communicate | |
1485 | with an external (non Crypt::CBC library). If this is the case, use | |
1486 | whatever padding method is compatible. | |
1487 | ||
1488 | You can also pass in a custom padding function. To do this, create a | |
1489 | function that takes the arguments: | |
1490 | ||
1491 | $padded_block = function($block,$blocksize,$direction); | |
1492 | ||
1493 | where $block is the current block of data, $blocksize is the size to | |
1494 | pad it to, $direction is "e" for encrypting and "d" for decrypting, | |
1495 | and $padded_block is the result after padding or depadding. | |
1496 | ||
1497 | When encrypting, the function should always return a string of | |
1498 | <blocksize> length, and when decrypting, can expect the string coming | |
1499 | in to always be that length. See _standard_padding(), _space_padding(), | |
1500 | _null_padding(), or _oneandzeroes_padding() in the source for examples. | |
1501 | ||
1502 | Standard and oneandzeroes padding are recommended, as both space and | |
1503 | null padding can potentially truncate more characters than they should. | |
1504 | ||
1505 | =head1 Comparison to Crypt::Mode::CBC | |
1506 | ||
1507 | The L<CryptX> modules L<Crypt::Mode::CBC>, L<Crypt::Mode::OFB>, | |
1508 | L<Crypt::Mode::CFB>, and L<Crypt::Mode::CTR> provide fast | |
1509 | implementations of the respective cipherblock chaining modes (roughly | |
1510 | 5x the speed of Crypt::CBC). Crypt::CBC was designed to encrypt and | |
1511 | decrypt messages in a manner compatible with OpenSSL's "enc" | |
1512 | function. Hence it handles the derivation of the key and IV from a | |
1513 | passphrase using the same conventions as OpenSSL, and it writes out an | |
1514 | OpenSSL-compatible header in the encrypted message in a manner that | |
1515 | allows the key and IV to be regenerated during decryption. | |
1516 | ||
1517 | In contrast, the CryptX modules do not automatically derive the key | |
1518 | and IV from a passphrase or write out an encrypted header. You will | |
1519 | need to derive and store the key and IV by other means (e.g. with | |
1520 | CryptX's Crypt::KeyDerivation module, or with Crypt::PBKDF2). | |
1521 | ||
1522 | =head1 EXAMPLES | |
1523 | ||
1524 | Three examples, aes.pl, des.pl and idea.pl can be found in the eg/ | |
1525 | subdirectory of the Crypt-CBC distribution. These implement | |
1526 | command-line DES and IDEA encryption algorithms using default | |
1527 | parameters, and should be compatible with recent versions of | |
1528 | OpenSSL. Note that aes.pl uses the "pbkdf2" key derivation function to | |
1529 | generate its keys. The other two were distributed with pre-PBKDF2 | |
1530 | versions of Crypt::CBC, and use the older "opensslv1" algorithm. | |
1531 | ||
1532 | =head1 LIMITATIONS | |
1533 | ||
1534 | The encryption and decryption process is about a tenth the speed of | |
1535 | the equivalent OpenSSL tool and about a fifth of the Crypt::Mode::CBC | |
1536 | module (both which use compiled C). | |
1537 | ||
1538 | =head1 BUGS | |
1539 | ||
1540 | Please report them. | |
1541 | ||
1542 | =head1 AUTHOR | |
1543 | ||
1544 | Lincoln Stein, lstein@cshl.org | |
1545 | ||
1546 | This module is distributed under the ARTISTIC LICENSE v2 using the | |
1547 | same terms as Perl itself. | |
1548 | ||
1549 | =head1 SEE ALSO | |
1550 | ||
1551 | perl(1), CryptX, Crypt::FileHandle, Crypt::Cipher::AES, | |
1552 | Crypt::Blowfish, Crypt::CAST5, Crypt::DES, Crypt::IDEA, | |
1553 | Crypt::Rijndael | |
1554 | ||
1555 | =cut |
0 | #!/usr/bin/perl | |
1 | ||
2 | use lib '../lib','./lib','./blib/lib'; | |
3 | ||
4 | eval "use Crypt::Cipher::AES()"; | |
5 | if ($@) { | |
6 | print "1..0 # Skipped: Crypt::Cipher::AES not installed\n"; | |
7 | exit; | |
8 | } | |
9 | ||
10 | print "1..33\n"; | |
11 | ||
12 | sub test { | |
13 | local($^W) = 0; | |
14 | my($num, $true,$msg) = @_; | |
15 | print($true ? "ok $num\n" : "not ok $num $msg\n"); | |
16 | } | |
17 | ||
18 | $test_data = <<END; | |
19 | Mary had a little lamb, | |
20 | Its fleece was black as coal, | |
21 | And everywere that Mary went, | |
22 | That lamb would dig a hole. | |
23 | END | |
24 | ; | |
25 | ||
26 | eval "use Crypt::CBC"; | |
27 | ||
28 | test(1,!$@,"Couldn't load module"); | |
29 | test(2,$i = Crypt::CBC->new(-pass=>'secret', | |
30 | -cipher => 'Cipher::AES', | |
31 | -pbkdf => 'pbkdf2' | |
32 | ),"Couldn't create new object"); | |
33 | test(3,$c = $i->encrypt($test_data),"Couldn't encrypt"); | |
34 | test(4,$p = $i->decrypt($c),"Couldn't decrypt"); | |
35 | test(5,$p eq $test_data,"Decrypted ciphertext doesn't match plaintext"); | |
36 | ||
37 | # now try various truncations of the whole | |
38 | for (my $c=1;$c<=7;$c++) { | |
39 | substr($test_data,-$c) = ''; # truncate | |
40 | test(5+$c,$i->decrypt($i->encrypt($test_data)) eq $test_data); | |
41 | } | |
42 | ||
43 | # now try various short strings | |
44 | for (my $c=0;$c<=18;$c++) { | |
45 | $test_data = 'i' x $c; | |
46 | test (13+$c,$i->decrypt($i->encrypt($test_data)) eq $test_data); | |
47 | } | |
48 | ||
49 | ||
50 | # make sure that strings that end in spaces or nulls are treated correctly | |
51 | $test_data = "This string ends in a null\0"; | |
52 | test (32,$i->decrypt($i->encrypt($test_data)) eq $test_data); | |
53 | ||
54 | $test_data = "This string ends in some spaces "; | |
55 | test (33,$i->decrypt($i->encrypt($test_data)) eq $test_data); |
0 | #!/usr/local/bin/perl -Tw | |
0 | #!/usr/local/bin/perl | |
1 | 1 | |
2 | use lib '..','../blib/lib','.','./blib/lib'; | |
2 | use lib './lib','../lib','./blib/lib'; | |
3 | 3 | |
4 | 4 | eval "use Crypt::Blowfish()"; |
5 | 5 | if ($@) { |
26 | 26 | eval "use Crypt::CBC"; |
27 | 27 | |
28 | 28 | test(1,!$@,"Couldn't load module"); |
29 | test(2,$i = Crypt::CBC->new(-key=>'secret',-cipher=>'Blowfish'),"Couldn't create new object"); | |
29 | test(2,$i = Crypt::CBC->new(-pass=>'secret',-cipher=>'Blowfish',-nodeprecate=>1),"Couldn't create new object"); | |
30 | 30 | test(3,$c = $i->encrypt($test_data),"Couldn't encrypt"); |
31 | 31 | test(4,$p = $i->decrypt($c),"Couldn't decrypt"); |
32 | 32 | test(5,$p eq $test_data,"Decrypted ciphertext doesn't match plaintext"); |
49 | 49 | |
50 | 50 | $test_data = "This string ends in some spaces "; |
51 | 51 | test (33,$i->decrypt($i->encrypt($test_data)) eq $test_data); |
52 |
0 | 0 | #!/usr/local/bin/perl -Tw |
1 | 1 | |
2 | use lib '..','../blib/lib','.','./blib/lib'; | |
2 | use lib './lib','./blib/lib'; | |
3 | 3 | |
4 | 4 | eval "use Crypt::Blowfish_PP()"; |
5 | 5 | if ($@) { |
26 | 26 | eval "use Crypt::CBC"; |
27 | 27 | |
28 | 28 | test(1,!$@,"Couldn't load module"); |
29 | test(2,$i = Crypt::CBC->new('secret','Blowfish_PP'),"Couldn't create new object"); | |
29 | test(2,$i = Crypt::CBC->new(-pass=>'secret',-cipher=>'Blowfish_PP',-nodeprecate=>1),"Couldn't create new object"); | |
30 | 30 | test(3,$c = $i->encrypt($test_data),"Couldn't encrypt"); |
31 | 31 | test(4,$p = $i->decrypt($c),"Couldn't decrypt"); |
32 | 32 | test(5,$p eq $test_data,"Decrypted ciphertext doesn't match plaintext"); |
0 | #!/usr/local/bin/perl -Tw | |
0 | #!/usr/bin/perl -w | |
1 | 1 | |
2 | use lib '..','../blib/lib','.','./blib/lib'; | |
2 | use lib './lib','./blib/lib'; | |
3 | 3 | |
4 | 4 | eval "use Crypt::CAST5()"; |
5 | 5 | if ($@) { |
26 | 26 | eval "use Crypt::CBC"; |
27 | 27 | |
28 | 28 | test(1,!$@,"Couldn't load module"); |
29 | test(2,$i = Crypt::CBC->new({key=>'secret',cipher=>'CAST5'}),"Couldn't create new object"); | |
29 | test(2,$i = Crypt::CBC->new({key=>'secret',cipher=>'CAST5',nodeprecate=>1}),"Couldn't create new object"); | |
30 | 30 | test(3,$c = $i->encrypt($test_data),"Couldn't encrypt"); |
31 | 31 | test(4,$p = $i->decrypt($c),"Couldn't decrypt"); |
32 | 32 | test(5,$p eq $test_data,"Decrypted ciphertext doesn't match plaintext"); |
0 | #!/usr/local/bin/perl -Tw | |
0 | #!/usr/bin/perl -w | |
1 | 1 | |
2 | use lib '..','../blib/lib','.','./blib/lib'; | |
2 | use lib './lib','./blib/lib'; | |
3 | 3 | |
4 | 4 | eval "use Crypt::DES()"; |
5 | 5 | if ($@) { |
26 | 26 | eval "use Crypt::CBC"; |
27 | 27 | |
28 | 28 | test(1,!$@,"Couldn't load module"); |
29 | test(2,$i = Crypt::CBC->new('secret','DES'),"Couldn't create new object"); | |
29 | test(2,$i = Crypt::CBC->new(-pass=>'secret',-cipher=>'DES',-pbkdf=>'pbkdf2'),"Couldn't create new object"); | |
30 | 30 | test(3,$c = $i->encrypt($test_data),"Couldn't encrypt"); |
31 | 31 | test(4,$p = $i->decrypt($c),"Couldn't decrypt"); |
32 | 32 | test(5,$p eq $test_data,"Decrypted ciphertext doesn't match plaintext"); |
0 | 0 | #!/usr/local/bin/perl -Tw |
1 | 1 | |
2 | use lib '..','../blib/lib','.','./blib/lib'; | |
2 | use lib './lib','./blib/lib'; | |
3 | 3 | |
4 | 4 | eval "use Crypt::IDEA()"; |
5 | 5 | if ($@) { |
26 | 26 | eval "use Crypt::CBC"; |
27 | 27 | |
28 | 28 | test(1,!$@,"Couldn't load module"); |
29 | test(2,$i = Crypt::CBC->new('secret','IDEA'),"Couldn't create new object"); | |
29 | test(2,$i = Crypt::CBC->new(-pass=>'secret', | |
30 | -cipher=>'IDEA', | |
31 | -nodeprecate=>1, | |
32 | ),"Couldn't create new object"); | |
30 | 33 | test(3,$c = $i->encrypt($test_data),"Couldn't encrypt"); |
31 | 34 | test(4,$p = $i->decrypt($c),"Couldn't decrypt"); |
32 | 35 | test(5,$p eq $test_data,"Decrypted ciphertext doesn't match plaintext"); |
0 | #!/usr/bin/perl | |
1 | ||
2 | use lib './lib','./blib/lib','../lib'; | |
3 | ||
4 | eval "use Crypt::Cipher::AES"; | |
5 | if ($@) { | |
6 | print "1..0 # Skipped: Crypt::Cipher::AES not installed\n"; | |
7 | exit; | |
8 | } | |
9 | ||
10 | print "1..33\n"; | |
11 | ||
12 | sub test { | |
13 | local($^W) = 0; | |
14 | my($num, $true,$msg) = @_; | |
15 | print($true ? "ok $num\n" : "not ok $num $msg\n"); | |
16 | } | |
17 | ||
18 | $test_data = <<END; | |
19 | Mary had a little lamb, | |
20 | Its fleece was black as coal, | |
21 | And everywere that Mary went, | |
22 | That lamb would dig a big hole. | |
23 | END | |
24 | ; | |
25 | ||
26 | eval "use Crypt::CBC"; | |
27 | ||
28 | test(1,!$@,"Couldn't load module"); | |
29 | test(2,$i = Crypt::CBC->new(-key => 'secret', | |
30 | -cipher => 'Cipher::AES', | |
31 | -chain_mode => 'ofb', | |
32 | -pbkdf => 'opensslv2', | |
33 | ),"Couldn't create new object"); | |
34 | test(3,$c = $i->encrypt($test_data),"Couldn't encrypt"); | |
35 | test(4,$p = $i->decrypt($c),"Couldn't decrypt"); | |
36 | test(5,$p eq $test_data,"Decrypted ciphertext doesn't match plaintext"); | |
37 | ||
38 | # now try various truncations of the whole | |
39 | for (my $c=1;$c<=7;$c++) { | |
40 | substr($test_data,-$c) = ''; # truncate | |
41 | test(5+$c,$i->decrypt($i->encrypt($test_data)) eq $test_data); | |
42 | } | |
43 | ||
44 | # now try various short strings | |
45 | for (my $c=0;$c<=18;$c++) { | |
46 | $test_data = 'i' x $c; | |
47 | test (13+$c,$i->decrypt($i->encrypt($test_data)) eq $test_data); | |
48 | } | |
49 | ||
50 | ||
51 | # make sure that strings that end in spaces or nulls are treated correctly | |
52 | $test_data = "This string ends in a null\0"; | |
53 | test (32,$i->decrypt($i->encrypt($test_data)) eq $test_data); | |
54 | ||
55 | $test_data = "This string ends in some spaces "; | |
56 | test (33,$i->decrypt($i->encrypt($test_data)) eq $test_data); |
0 | #!/usr/local/bin/perl -Tw | |
0 | #!/usr/local/bin/perl | |
1 | 1 | |
2 | use lib '..','../blib/lib','.','./blib/lib'; | |
2 | use lib './lib','./blib/lib'; | |
3 | 3 | |
4 | eval "use Crypt::DES()"; | |
4 | eval "use Crypt::Cipher::AES"; | |
5 | 5 | if ($@) { |
6 | print "1..0 # Skipped: Crypt::DES not installed\n"; | |
6 | print "1..0 # Skipped: Crypt::Cipher::AES not installed\n"; | |
7 | 7 | exit; |
8 | 8 | } |
9 | 9 | |
27 | 27 | |
28 | 28 | test(1,!$@,"Couldn't load module"); |
29 | 29 | test(2,$i = Crypt::CBC->new(-key=>'secret', |
30 | -cipher=>'DES', | |
31 | -pcbc=>1, | |
30 | -cipher=>'Cipher::AES', | |
31 | -chain_mode => 'pcbc', | |
32 | -pbkdf => 'pbkdf2', | |
32 | 33 | ),"Couldn't create new object"); |
33 | 34 | test(3,$c = $i->encrypt($test_data),"Couldn't encrypt"); |
34 | 35 | test(4,$p = $i->decrypt($c),"Couldn't decrypt"); |
0 | 0 | #!/usr/local/bin/perl -Tw |
1 | 1 | |
2 | use lib '..','../blib/lib','.','./blib/lib'; | |
2 | use lib './lib','./blib/lib'; | |
3 | 3 | |
4 | 4 | eval "use Crypt::Rijndael()"; |
5 | 5 | if ($@) { |
26 | 26 | eval "use Crypt::CBC"; |
27 | 27 | |
28 | 28 | test(1,!$@,"Couldn't load module"); |
29 | test(2,$i = Crypt::CBC->new('secret','Rijndael'),"Couldn't create new object"); | |
29 | test(2,$i = Crypt::CBC->new(-pass=>'secret',-cipher=>'Rijndael',-pbkdf=>'opensslv2'),"Couldn't create new object"); | |
30 | 30 | test(3,$c = $i->encrypt($test_data),"Couldn't encrypt"); |
31 | 31 | test(4,$p = $i->decrypt($c),"Couldn't decrypt"); |
32 | 32 | test(5,$p eq $test_data,"Decrypted ciphertext doesn't match plaintext"); |
0 | #!/usr/local/bin/perl -Tw | |
0 | #!/usr/bin/perl | |
1 | 1 | |
2 | 2 | use strict; |
3 | use lib '..','../blib/lib','.','./blib/lib'; | |
3 | use lib '../lib','./lib','./blib/lib'; | |
4 | 4 | |
5 | 5 | my ($i, $j, $test_data); |
6 | 6 | |
45 | 45 | test(2,$i = Crypt::CBC->new(-key => 'a' x $ks, |
46 | 46 | -cipher => 'Rijndael', |
47 | 47 | -iv => 'f' x $bs, |
48 | -literal_key => 1, | |
48 | -pbkdf => 'none', | |
49 | 49 | -header => 'none', |
50 | 50 | -padding => 'rijndael_compat', |
51 | 51 | ), |
0 | #!/usr/local/bin/perl -Tw | |
0 | #!/usr/local/bin/perl | |
1 | 1 | |
2 | use strict; | |
3 | use lib '..','../blib/lib','.','./blib/lib'; | |
2 | use lib '../lib','./lib','./blib/lib'; | |
4 | 3 | |
5 | sub test; | |
4 | # using globals and uninit variables here for convenience | |
5 | no warnings; | |
6 | 6 | |
7 | my (@mods,@pads,@in,$pad,$test_data,$mod,$tnum,$c,$i,$p); | |
8 | ||
9 | @mods = qw/Rijndael | |
10 | Blowfish | |
11 | Blowfish_PP | |
12 | IDEA | |
13 | DES | |
7 | @mods = qw/ | |
8 | Cipher::AES | |
9 | Rijndael | |
10 | Blowfish | |
11 | Blowfish_PP | |
12 | IDEA | |
13 | DES | |
14 | 14 | /; |
15 | 15 | @pads = qw/standard oneandzeroes space null/; |
16 | 16 | |
25 | 25 | |
26 | 26 | # ($#in + 1): number of installed modules |
27 | 27 | # ($#pads + 1): number of padding methods |
28 | # 32: number of per-module, per-pad tests | |
28 | # 64: number of per-module, per-pad tests | |
29 | 29 | # 1: the first test -- loading Crypt::CBC module |
30 | 30 | |
31 | print '1..', ($#in + 1) * ($#pads + 1) * 32 + 1, "\n"; | |
32 | ||
33 | sub test { | |
34 | local($^W) = 0; | |
35 | my($num, $true,$msg) = @_; | |
36 | $$num++; | |
37 | print($true ? "ok $$num\n" : "not ok $$num $msg\n"); | |
38 | } | |
31 | print '1..', ($#in + 1) * ($#pads + 1) * 64 + 1, "\n"; | |
39 | 32 | |
40 | 33 | $tnum = 0; |
41 | 34 | |
56 | 49 | test(\$tnum,$i = Crypt::CBC->new(-key => 'secret', |
57 | 50 | -cipher => $mod, |
58 | 51 | -padding => $pad, |
52 | -pbkdf => 'opensslv2', | |
59 | 53 | ), |
60 | 54 | "Couldn't create new object"); |
61 | 55 | |
62 | 56 | test(\$tnum,$c = $i->encrypt($test_data),"Couldn't encrypt"); |
63 | 57 | test(\$tnum,$p = $i->decrypt($c),"Couldn't decrypt"); |
64 | test(\$tnum,$p eq $test_data,"Decrypted ciphertext doesn't match plaintext"); | |
58 | test(\$tnum,$p eq $test_data,"Decrypted ciphertext doesn't match plaintext with cipher=$mod, pad=$pad and plaintext size=".length $test_data); | |
65 | 59 | |
66 | 60 | # now try various truncations of the whole string. |
67 | 61 | # iteration 3 ends in ' ' so 'space should fail |
82 | 76 | for ($c=0;$c<=18;$c++) { |
83 | 77 | $test_data = 'i' x $c; |
84 | 78 | test(\$tnum,$i->decrypt($i->encrypt($test_data)) eq $test_data); |
79 | } | |
80 | ||
81 | # try adding a "\001" to the end of the string | |
82 | for ($c=0;$c<=31;$c++) { | |
83 | $test_data = 'i' x $c; | |
84 | $test_data .= "\001"; | |
85 | test(\$tnum,$i->decrypt($i->encrypt($test_data)) eq $test_data,"failed to decrypt with cipher=$mod, padding=$pad, and plaintext length=".($c+1)); | |
85 | 86 | } |
86 | 87 | |
87 | 88 | # 'space' should fail. others should succeed. |
105 | 106 | } |
106 | 107 | } |
107 | 108 | } |
109 | ||
110 | sub test { | |
111 | my($num, $true, $msg) = @_; | |
112 | $msg ||= "cipher=$mod, padding=$pad, plaintext length=$c"; | |
113 | $$num++; | |
114 | print($true ? "ok $$num\n" : "not ok $$num $msg\n"); | |
115 | } | |
116 |
0 | #!/usr/local/bin/perl | |
1 | ||
2 | use lib '../lib','./lib','./blib/lib'; | |
3 | ||
4 | my (@mods,@pads,@in,$tnum); | |
5 | ||
6 | @mods = qw/ | |
7 | Cipher::AES | |
8 | Rijndael | |
9 | Blowfish | |
10 | Blowfish_PP | |
11 | IDEA | |
12 | DES | |
13 | /; | |
14 | ||
15 | for $mod (@mods) { | |
16 | eval "use Crypt::$mod(); 1" && push @in,$mod; | |
17 | } | |
18 | ||
19 | unless ($#in > -1) { | |
20 | print "1..0 # Skipped: no cryptographic modules found\n"; | |
21 | exit; | |
22 | } else { | |
23 | print "1..2\n"; | |
24 | } | |
25 | ||
26 | sub test { | |
27 | local($^W) = 0; | |
28 | my($num, $true,$msg) = @_; | |
29 | $$num++; | |
30 | print($true ? "ok $$num\n" : "not ok $$num $msg\n"); | |
31 | } | |
32 | ||
33 | $tnum = 0; | |
34 | ||
35 | eval "use Crypt::CBC"; | |
36 | print STDERR "using Crypt\:\:$in[0] for testing\n"; | |
37 | test(\$tnum,!$@,"Couldn't load module"); | |
38 | ||
39 | my $key = "\x00" x "Crypt::$in[0]"->keysize; | |
40 | my $iv = "\x00" x "Crypt::$in[0]"->blocksize; | |
41 | ||
42 | my $cipher = Crypt::CBC->new( | |
43 | { | |
44 | cipher => $in[0], | |
45 | key => $key, | |
46 | iv => $iv, | |
47 | literal_key => 1, | |
48 | header => 'none', | |
49 | padding => 'none', | |
50 | nodeprecate=>1, | |
51 | } | |
52 | ); | |
53 | my $string = 'A' x "Crypt::$in[0]"->blocksize; | |
54 | ||
55 | test(\$tnum,length $cipher->encrypt($string) == "Crypt::$in[0]"->blocksize,"nopadding not working\n"); | |
56 | ||
57 | exit 0; | |
58 |
0 | #!/usr/bin/perl -Tw | |
0 | #!/usr/bin/perl | |
1 | 1 | |
2 | 2 | use strict; |
3 | use lib '..','../blib/lib','.','./blib/lib'; | |
3 | use lib './lib','./blib/lib'; | |
4 | 4 | |
5 | 5 | sub test; |
6 | 6 | |
7 | 7 | my (@mods,@pads,@in,$pad,$test_data,$mod,$tnum,$c,$i,$p); |
8 | 8 | |
9 | @mods = qw/Rijndael | |
10 | Blowfish | |
11 | Blowfish_PP | |
12 | IDEA | |
13 | DES | |
14 | /; | |
9 | @mods = qw/ | |
10 | Cipher::AES | |
11 | Rijndael | |
12 | Blowfish | |
13 | Blowfish_PP | |
14 | IDEA | |
15 | DES | |
16 | /; | |
15 | 17 | @pads = qw/standard oneandzeroes space null/; |
16 | 18 | |
17 | 19 | for $mod (@mods) { |
42 | 44 | my $cipher = Crypt::CBC->new(-key => 'secret', |
43 | 45 | -cipher => $mod, |
44 | 46 | -padding => $pad, |
47 | -pbkdf => 'opensslv2', | |
45 | 48 | ); |
46 | 49 | for my $length (1..128) { |
47 | 50 | my $test_data = 'a'x$length . '0'; |
0 | #!/usr/local/bin/perl -Tw | |
0 | #!/usr/local/bin/perl | |
1 | 1 | |
2 | use lib '..','../blib/lib','.','./blib/lib'; | |
2 | use lib './lib','./blib/lib'; | |
3 | 3 | |
4 | 4 | my (@mods,@pads,@in,$tnum); |
5 | 5 | |
6 | @mods = qw/Rijndael | |
7 | Blowfish | |
8 | Blowfish_PP | |
9 | IDEA | |
10 | DES | |
6 | @mods = qw/ | |
7 | Cipher::AES | |
8 | Rijndael | |
9 | Blowfish | |
10 | Blowfish_PP | |
11 | IDEA | |
12 | DES | |
11 | 13 | /; |
12 | 14 | |
13 | 15 | for $mod (@mods) { |
36 | 38 | |
37 | 39 | |
38 | 40 | my $cipher = Crypt::CBC->new( |
39 | -key => 'aaab', | |
40 | -cipher => $in[0], | |
41 | -padding => "oneandzeroes", | |
41 | -key => 'aaab', | |
42 | -cipher => $in[0], | |
43 | -padding => "oneandzeroes", | |
44 | -pbkdf => 'opensslv2', | |
42 | 45 | ); |
43 | 46 | my $string = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAX'; |
44 | 47 |
0 | #!/usr/bin/perl -Tw | |
0 | #!/usr/bin/perl | |
1 | 1 | |
2 | 2 | use strict; |
3 | use lib '..','../blib/lib','.','./blib/lib'; | |
4 | ||
5 | sub test ($$$); | |
3 | use lib '../lib','./lib','./blib/lib'; | |
4 | ||
5 | sub test ($$); | |
6 | 6 | |
7 | 7 | my $plaintext = <<END; |
8 | 8 | Mary had a little lamb, |
12 | 12 | END |
13 | 13 | ; |
14 | 14 | |
15 | print "1..63\n"; | |
15 | print "1..82\n"; | |
16 | 16 | |
17 | 17 | eval "use Crypt::CBC"; |
18 | test(1,!$@,"Couldn't load module"); | |
18 | test(!$@,"Couldn't load module"); | |
19 | 19 | |
20 | 20 | my ($crypt,$ciphertext1,$ciphertext2); |
21 | 21 | |
22 | $crypt = eval {Crypt::CBC->new(-cipher => 'Crypt::Crypt8', | |
23 | -key => 'test key') }; | |
24 | test(2,defined $crypt,"$@Can't continue!"); | |
25 | test(3,$crypt->header_mode eq 'salt',"Default header mode is not 'salt'"); | |
22 | # test whether a bad parameter is caught | |
23 | $crypt = eval {Crypt::CBC->new(-bad_parm=>1,-pass=>'test')}; | |
24 | test(!$crypt,"new() accepted an unknown parameter"); | |
25 | test($@ =~ /not a recognized argument/,"bad parameter error message not emitted"); | |
26 | ||
27 | $crypt = eval {Crypt::CBC->new( | |
28 | -cipher => 'Crypt::Crypt8', | |
29 | -key => 'test key', | |
30 | -nodeprecate=>1) | |
31 | }; | |
32 | test(defined $crypt,"$@Can't continue!"); | |
33 | test($crypt->header_mode eq 'salt',"Default header mode is not 'salt'"); | |
26 | 34 | exit 0 unless $crypt; |
27 | 35 | |
28 | 36 | |
29 | 37 | # tests for the salt header |
30 | 38 | $crypt = eval {Crypt::CBC->new(-cipher => 'Crypt::Crypt8', |
31 | 39 | -key => 'test key', |
32 | -header => 'salt') }; | |
33 | test(4,defined $crypt,"$@Can't continue!"); | |
34 | exit 0 unless $crypt; | |
35 | ||
36 | test(5,!defined $crypt->iv, "IV is defined after new() but it shouldn't be"); | |
37 | test(6,!defined $crypt->salt,"salt is defined after new() but it shouldn't be"); | |
38 | test(7,!defined $crypt->key, "key is defined after new() but it shouldn't be"); | |
40 | -header => 'salt', | |
41 | -nodeprecate=>1, | |
42 | ) }; | |
43 | test(defined $crypt,"$@Can't continue!"); | |
44 | exit 0 unless $crypt; | |
45 | ||
46 | test(!defined $crypt->iv, "IV is defined after new() but it shouldn't be"); | |
47 | test(!defined $crypt->salt,"salt is defined after new() but it shouldn't be"); | |
48 | test(!defined $crypt->key, "key is defined after new() but it shouldn't be"); | |
39 | 49 | |
40 | 50 | $ciphertext1 = $crypt->encrypt($plaintext); |
41 | test(8,$ciphertext1 =~ /^Salted__/s,"salted header not present"); | |
42 | test(9, defined $crypt->iv, "IV not defined after encrypt"); | |
43 | test(10,defined $crypt->salt, "salt not defined after encrypt"); | |
44 | test(11,defined $crypt->key, "key not defined after encrypt"); | |
51 | test($ciphertext1 =~ /^Salted__/s,"salted header not present"); | |
52 | test(defined $crypt->iv, "IV not defined after encrypt"); | |
53 | test(defined $crypt->salt, "salt not defined after encrypt"); | |
54 | test(defined $crypt->key, "key not defined after encrypt"); | |
45 | 55 | |
46 | 56 | my ($old_iv,$old_salt,$old_key) = ($crypt->iv,$crypt->salt,$crypt->key); |
47 | 57 | $ciphertext2 = $crypt->encrypt($plaintext); |
48 | test(12,$ciphertext2 =~ /^Salted__/s,"salted header not present"); | |
49 | test(13,$old_iv ne $crypt->iv, "IV didn't change after an encrypt"); | |
50 | test(14,$old_salt ne $crypt->salt, "salt didn't change after an encrypt"); | |
51 | test(15,$old_key ne $crypt->key, "key didn't change after an encrypt"); | |
52 | ||
53 | test(16,$plaintext eq $crypt->decrypt($ciphertext1),"decrypted text doesn't match original"); | |
54 | test(17,$old_iv eq $crypt->iv, "original IV wasn't restored after decryption"); | |
55 | test(18,$old_salt eq $crypt->salt, "original salt wasn't restored after decryption"); | |
56 | test(19,$old_key eq $crypt->key, "original key wasn't restored after decryption"); | |
57 | ||
58 | test(20,$crypt->passphrase eq 'test key',"get passphrase()"); | |
58 | test($ciphertext2 =~ /^Salted__/s,"salted header not present"); | |
59 | test($old_iv ne $crypt->iv, "IV didn't change after an encrypt"); | |
60 | test($old_salt ne $crypt->salt, "salt didn't change after an encrypt"); | |
61 | test($old_key ne $crypt->key, "key didn't change after an encrypt"); | |
62 | ||
63 | test($plaintext eq $crypt->decrypt($ciphertext1),"decrypted text doesn't match original"); | |
64 | test($old_iv eq $crypt->iv, "original IV wasn't restored after decryption"); | |
65 | test($old_salt eq $crypt->salt, "original salt wasn't restored after decryption"); | |
66 | test($old_key eq $crypt->key, "original key wasn't restored after decryption"); | |
67 | ||
68 | test($crypt->passphrase eq 'test key',"get passphrase()"); | |
59 | 69 | $crypt->passphrase('new key'); |
60 | test(21,$crypt->passphrase eq 'new key',"set passphrase()"); | |
61 | ||
62 | test(22,length($crypt->random_bytes(20)) == 20,"get_random_bytes()"); | |
70 | test($crypt->passphrase eq 'new key',"set passphrase()"); | |
71 | ||
72 | test(length($crypt->random_bytes(20)) == 20,"get_random_bytes()"); | |
63 | 73 | |
64 | 74 | # tests for the randomiv header |
65 | 75 | $crypt = eval {Crypt::CBC->new(-cipher => 'Crypt::Crypt8', |
66 | 76 | -key => 'test key', |
67 | -header => 'randomiv') }; | |
68 | test(23,defined $crypt,"$@\nCan't continue!"); | |
69 | exit 0 unless $crypt; | |
70 | ||
71 | test(24,$crypt->header_mode eq 'randomiv',"wrong header mode"); | |
72 | test(25,!defined $crypt->iv, "IV is defined after new() but it shouldn't be"); | |
73 | test(26,!defined $crypt->salt,"salt is defined after new() but it shouldn't be"); | |
74 | test(27,!defined $crypt->key, "key is defined after new() but it shouldn't be"); | |
77 | -header => 'randomiv', | |
78 | -nodeprecate=>1, | |
79 | ) }; | |
80 | test(defined $crypt,"$@\nCan't continue!"); | |
81 | exit 0 unless $crypt; | |
82 | ||
83 | test($crypt->header_mode eq 'randomiv',"wrong header mode"); | |
84 | test($crypt->pbkdf eq 'randomiv',"wrong key derivation mode"); | |
85 | test(!defined $crypt->iv, "IV is defined after new() but it shouldn't be"); | |
86 | test(!defined $crypt->salt,"salt is defined after new() but it shouldn't be"); | |
87 | test(!defined $crypt->key, "key is defined after new() but it shouldn't be"); | |
75 | 88 | |
76 | 89 | $ciphertext1 = $crypt->encrypt($plaintext); |
77 | test(28,$ciphertext1 =~ /^RandomIV/s,"RandomIV header not present"); | |
78 | test(29, defined $crypt->iv, "IV not defined after encrypt"); | |
79 | test(30,!defined $crypt->salt, "salt defined after encrypt"); | |
80 | test(31,defined $crypt->key, "key not defined after encrypt"); | |
90 | test($ciphertext1 =~ /^RandomIV/s,"RandomIV header not present"); | |
91 | test(defined $crypt->iv, "IV not defined after encrypt"); | |
92 | test(!defined $crypt->salt, "there shouldn't be a salt after randomIV encryption"); | |
93 | test(defined $crypt->key, "key not defined after encrypt"); | |
81 | 94 | |
82 | 95 | ($old_iv,$old_salt,$old_key) = ($crypt->iv,$crypt->salt,$crypt->key); |
83 | 96 | $ciphertext2 = $crypt->encrypt($plaintext); |
84 | test(32,$ciphertext2 =~ /^RandomIV/s,"RandomIV header not present"); | |
85 | test(33,$old_iv ne $crypt->iv, "IV didn't change after an encrypt"); | |
86 | test(34,$old_key eq $crypt->key, "key changed after an encrypt"); | |
87 | ||
88 | test(35,$plaintext eq $crypt->decrypt($ciphertext1),"decrypted text doesn't match original"); | |
89 | test(36,$old_iv eq $crypt->iv, "original IV wasn't restored after decryption"); | |
97 | test($ciphertext2 =~ /^RandomIV/s,"RandomIV header not present"); | |
98 | test($old_iv ne $crypt->iv, "IV didn't change after an encrypt"); | |
99 | test($old_key eq $crypt->key, "key changed after an encrypt"); | |
100 | ||
101 | test($plaintext eq $crypt->decrypt($ciphertext1),"decrypted text doesn't match original"); | |
102 | test($old_iv eq $crypt->iv, "original IV wasn't restored after decryption"); | |
90 | 103 | |
91 | 104 | # tests for headerless operation |
92 | 105 | $crypt = eval {Crypt::CBC->new(-cipher => 'Crypt::Crypt8', |
93 | 106 | -key => 'test key', |
94 | 107 | -iv => '01234567', |
108 | -nodeprecate=>1, | |
95 | 109 | -header => 'none') }; |
96 | test(37,defined $crypt,"$@Can't continue!"); | |
97 | exit 0 unless $crypt; | |
98 | test(38,$crypt->header_mode eq 'none',"wrong header mode"); | |
99 | test(39,$crypt->iv eq '01234567', "IV doesn't match settings"); | |
100 | test(40,!defined $crypt->key, "key is defined after new() but it shouldn't be"); | |
110 | test(defined $crypt,"$@Can't continue!"); | |
111 | exit 0 unless $crypt; | |
112 | test($crypt->header_mode eq 'none',"wrong header mode"); | |
113 | test($crypt->iv eq '01234567', "IV doesn't match settings"); | |
114 | test(!defined $crypt->key, "key is defined after new() but it shouldn't be"); | |
101 | 115 | $ciphertext1 = $crypt->encrypt($plaintext); |
102 | test(41,length($ciphertext1) - length($plaintext) <= 8, "ciphertext grew too much"); | |
103 | test(42,$crypt->decrypt($ciphertext1) eq $plaintext,"decrypted ciphertext doesn't match plaintext"); | |
116 | test(length($ciphertext1) - length($plaintext) <= 8, "ciphertext grew too much"); | |
117 | test($crypt->decrypt($ciphertext1) eq $plaintext,"decrypted ciphertext doesn't match plaintext"); | |
104 | 118 | my $crypt2 = Crypt::CBC->new(-cipher => 'Crypt::Crypt8', |
119 | -salt => $crypt->salt, | |
105 | 120 | -key => 'test key', |
106 | 121 | -iv => '01234567', |
122 | -nodeprecate=>1, | |
107 | 123 | -header => 'none'); |
108 | test(43,$crypt2->decrypt($ciphertext1) eq $plaintext,"decrypted ciphertext doesn't match plaintext"); | |
124 | test($crypt2->decrypt($ciphertext1) eq $plaintext,"decrypted ciphertext doesn't match plaintext"); | |
109 | 125 | $crypt2 = Crypt::CBC->new(-cipher => 'Crypt::Crypt8', |
110 | 126 | -key => 'test key', |
111 | 127 | -iv => '76543210', |
128 | -nodeprecate=>1, | |
112 | 129 | -header => 'none'); |
113 | test(44,$crypt2->decrypt($ciphertext1) ne $plaintext,"decrypted ciphertext matches plaintext but shouldn't"); | |
114 | test(45,$crypt->iv eq '01234567',"iv changed and it shouldn't have"); | |
115 | test(46,$crypt2->iv eq '76543210',"iv changed and it shouldn't have"); | |
130 | test($crypt2->decrypt($ciphertext1) ne $plaintext,"decrypted ciphertext matches plaintext but shouldn't"); | |
131 | test($crypt->iv eq '01234567',"iv changed and it shouldn't have"); | |
132 | test($crypt2->iv eq '76543210',"iv changed and it shouldn't have"); | |
116 | 133 | |
117 | 134 | # check various bad combinations of parameters that should cause a fatal error |
118 | 135 | my $good_key = Crypt::CBC->random_bytes(Crypt::Crypt8->keysize); |
119 | 136 | my $bad_key = 'foo'; |
120 | 137 | $crypt = eval {Crypt::CBC->new(-cipher => 'Crypt::Crypt8', |
121 | -header => 'randomiv', | |
122 | 138 | -key => $good_key, |
123 | 139 | -iv => '01234567', |
124 | -literal_key => 1)}; | |
125 | test(47,defined $crypt,"$@Can't continue!"); | |
126 | exit 0 unless $crypt; | |
127 | test(48,$crypt->key eq $good_key,"couldn't set literal key"); | |
128 | test(49, | |
140 | -nodeprecate=>1, | |
141 | -pbkdf => 'none' | |
142 | )}; | |
143 | test(defined $crypt,"$@Can't continue!"); | |
144 | exit 0 unless $crypt; | |
145 | test($crypt->literal_key,"pbkdf 'none' should set literal key flag, but didn't"); | |
146 | test($crypt->key eq $good_key,"couldn't set literal key"); | |
147 | test($crypt->header_mode eq 'none',"-pbkdf=>'none' should set header_mode to 'none', but didn't"); | |
148 | test( | |
129 | 149 | !eval{ |
130 | 150 | Crypt::CBC->new(-cipher => 'Crypt::Crypt8', |
131 | 151 | -header => 'randomiv', |
132 | 152 | -key => $bad_key, |
133 | 153 | -iv => '01234567', |
134 | -literal_key => 1) | |
154 | -nodeprecate=>1, | |
155 | -pbkdf => 'none', | |
156 | ) | |
135 | 157 | }, |
136 | 158 | "module accepted a literal key of invalid size"); |
137 | test(50, | |
159 | test( | |
138 | 160 | !eval{ |
139 | 161 | Crypt::CBC->new(-cipher => 'Crypt::Crypt16', |
140 | 162 | -header => 'randomiv', |
141 | 163 | -key => $good_key, |
142 | 164 | -iv => '01234567', |
143 | -literal_key => 1) | |
165 | -nodeprecate=>1, | |
166 | -pbkdf => 'none', | |
167 | ) | |
144 | 168 | }, |
145 | 169 | "module accepted a literal key of invalid size"); |
146 | test(51, | |
170 | test( | |
147 | 171 | !eval{ |
148 | 172 | Crypt::CBC->new(-cipher => 'Crypt::Crypt8', |
149 | 173 | -header => 'randomiv', |
150 | 174 | -key => $good_key, |
151 | 175 | -iv => '01234567891', |
152 | -literal_key => 1) | |
176 | -nodeprecate=>1, | |
177 | -pbkdf => 'none' | |
178 | ) | |
153 | 179 | }, |
154 | 180 | "module accepted an IV of invalid size"); |
155 | 181 | |
156 | test(52, | |
182 | test( | |
157 | 183 | !eval{ |
158 | 184 | Crypt::CBC->new(-cipher => 'Crypt::Crypt16', |
159 | 185 | -header => 'randomiv', |
186 | -nodeprecate=>1, | |
160 | 187 | -key => 'test key') |
161 | 188 | }, |
162 | 189 | "module allowed randomiv headers with a 16-bit blocksize cipher"); |
163 | 190 | |
164 | $crypt = Crypt::CBC->new(-cipher => 'Crypt::Crypt16', | |
165 | -header => 'randomiv', | |
166 | -key => 'test key', | |
167 | -insecure_legacy_decrypt => 1); | |
168 | test(53,defined $crypt,"module didn't honor the -insecure_legacy_decrypt flag:$@Can't continue!"); | |
169 | exit 0 unless $crypt; | |
170 | ||
171 | test(54,$crypt->decrypt("RandomIV01234567".'a'x256),"module didn't allow legacy decryption"); | |
172 | test(55,!defined eval{$crypt->encrypt('foobar')},"module allowed legacy encryption and shouldn't have"); | |
173 | ||
174 | ||
175 | test(56, | |
191 | if (0) { | |
192 | $crypt = Crypt::CBC->new(-cipher => 'Crypt::Crypt16', | |
193 | -header => 'randomiv', | |
194 | -key => 'test key', | |
195 | -nodeprecate => 1, | |
196 | -insecure_legacy_decrypt => 1); | |
197 | test(defined $crypt,"module didn't honor the -insecure_legacy_decrypt flag:$@Can't continue!"); | |
198 | exit 0 unless $crypt; | |
199 | test($crypt->decrypt("RandomIV01234567".'a'x256),"module didn't allow legacy decryption"); | |
200 | test(!defined eval{$crypt->encrypt('foobar')},"module allowed legacy encryption and shouldn't have"); | |
201 | } else { | |
202 | skip ('-insecure_legacy_decrypt is no longer supported') foreach (53..55); | |
203 | } | |
204 | ||
205 | test( | |
176 | 206 | !defined eval {Crypt::CBC->new(-cipher => 'Crypt::Crypt16', |
177 | 207 | -header => 'salt', |
178 | 208 | -key => 'test key', |
209 | -nodeprecate => 1, | |
179 | 210 | -salt => 'bad bad salt!'); |
180 | 211 | }, |
181 | 212 | "module allowed setting of a bad salt"); |
182 | 213 | |
183 | test(57, | |
214 | test( | |
184 | 215 | defined eval {Crypt::CBC->new(-cipher => 'Crypt::Crypt16', |
185 | 216 | -header => 'salt', |
186 | 217 | -key => 'test key', |
218 | -nodeprecate => 1, | |
187 | 219 | -salt => 'goodsalt'); |
188 | 220 | }, |
189 | 221 | "module did not allow setting of a good salt"); |
190 | 222 | |
191 | test(58, | |
223 | test( | |
192 | 224 | Crypt::CBC->new(-cipher => 'Crypt::Crypt16', |
193 | 225 | -header => 'salt', |
194 | 226 | -key => 'test key', |
227 | -nodeprecate => 1, | |
195 | 228 | -salt => 'goodsalt')->salt eq 'goodsalt', |
196 | 229 | "module did not allow setting and retrieval of a good salt"); |
197 | 230 | |
198 | test(59, | |
231 | test( | |
199 | 232 | !defined eval {Crypt::CBC->new(-cipher => 'Crypt::Crypt16', |
200 | 233 | -header => 'badheadermethod', |
234 | -nodeprecate => 1, | |
201 | 235 | -key => 'test key')}, |
202 | 236 | "module allowed setting of an invalid header method, and shouldn't have"); |
203 | 237 | |
204 | test(60, | |
238 | test( | |
205 | 239 | !defined eval {Crypt::CBC->new(-cipher => 'Crypt::Crypt16', |
206 | 240 | -header => 'none', |
241 | -pbkdf => 'none', | |
207 | 242 | -key => 'a'x16) |
208 | 243 | }, |
209 | "module allowed initialization of header_mode 'none' without an iv"); | |
210 | ||
211 | test(61, | |
244 | "module allowed initialization of pbkdf method 'none' without an iv"); | |
245 | ||
246 | test( | |
212 | 247 | !defined eval {Crypt::CBC->new(-cipher => 'Crypt::Crypt16', |
213 | 248 | -header => 'none', |
249 | -nodeprecate => 1, | |
214 | 250 | -iv => 'a'x16) |
215 | 251 | }, |
216 | 252 | "module allowed initialization of header_mode 'none' without a key"); |
220 | 256 | -header => 'none', |
221 | 257 | -key => 'a'x56, |
222 | 258 | -iv => 'b'x8, |
259 | -nodeprecate => 1, | |
223 | 260 | ) }; |
224 | test(62,defined $crypt,"unable to create a Crypt::CBC object with the -literal_key option: $@"); | |
225 | test(63,$plaintext eq $crypt->decrypt($crypt->encrypt($plaintext)),'cannot decrypt encrypted data using -literal_key'); | |
261 | test(defined $crypt,"unable to create a Crypt::CBC object with the -literal_key option: $@"); | |
262 | test($plaintext eq $crypt->decrypt($crypt->encrypt($plaintext)),'cannot decrypt encrypted data using -literal_key'); | |
263 | test($crypt->passphrase eq '','passphrase should be empty when -literal_key specified'); | |
264 | test($crypt->key eq 'a'x56,'key should match provided -key argument when -literal_key specified'); | |
265 | ||
266 | # test behavior of pbkdf option | |
267 | test($crypt->pbkdf eq 'none','PBKDF should default to "none" when -literal_key provided, but got '.$crypt->pbkdf); | |
268 | ||
269 | $crypt = eval {Crypt::CBC->new(-cipher => 'Crypt::Crypt8',-pass=>'very secret',-nodeprecate=>1)} or warn $@; | |
270 | test($crypt->pbkdf eq 'opensslv1','PBKDF should default to "opensslv1", but got '.$crypt->pbkdf); | |
271 | ||
272 | $crypt = eval {Crypt::CBC->new(-cipher => 'Crypt::Crypt8',-pass=>'very secret',-pbkdf=>'pbkdf2')} or warn $@; | |
273 | test($crypt->pbkdf eq 'pbkdf2','PBKDF not setting properly. Expected "pbkdf2" but got '.$crypt->pbkdf); | |
274 | ||
275 | $crypt = eval {Crypt::CBC->new(-cipher => 'Crypt::Crypt8', | |
276 | -pass=>'very secret', | |
277 | -pbkdf=>'pbkdf2', | |
278 | -hasher=>'HMACSHA3', | |
279 | -iter=>1000)} or warn $@; | |
280 | my $pbkdf = $crypt->pbkdf_obj; | |
281 | test(defined $pbkdf,"PBKDF object not created as expected"); | |
282 | test($pbkdf->{hash_class} eq 'HMACSHA3','pbkdf object hasher not initialized to correct class'); | |
283 | test($pbkdf->{iterations} == 1000,'pbkdf object hasher not initialized to correct number of iterations'); | |
284 | ||
285 | test( !eval {Crypt::CBC->new(-cipher => 'Crypt::Crypt8', | |
286 | -pass=>'very secret', | |
287 | -pbkdf=>'pbkdf2', | |
288 | -iv => 'b'x8, | |
289 | -header=>'randomiv') | |
290 | }, | |
291 | 'module should not allow a header mode of randomiv and a pbkdf not equal to randomiv' | |
292 | ); | |
293 | ||
294 | $crypt = eval {Crypt::CBC->new(-cipher => 'Crypt::Crypt8', | |
295 | -pass=>'very secret', | |
296 | -pbkdf=>'pbkdf2', | |
297 | -iv => 'b'x8, | |
298 | -header=>'none'), | |
299 | } or warn $@; | |
300 | # not sure this test is correct behaviour | |
301 | # test(73,$crypt->pbkdf eq 'none','pbkdf should be set to "none" when header mode of "none" used'); | |
302 | ||
303 | # now test that setting the -salt generates the same key and IV | |
304 | $crypt = eval {Crypt::CBC->new(-cipher => 'Crypt::Crypt8', | |
305 | -pass => 'baby knows me well', | |
306 | -pbkdf => 'pbkdf2', | |
307 | -salt => '01234567')} or warn $@; | |
308 | test($crypt->salt eq '01234567',"can't set salt properly"); | |
309 | $crypt->set_key_and_iv(); # need to do this before there is a key and iv | |
310 | my ($key,$iv) = ($crypt->key,$crypt->iv); | |
311 | $crypt = eval {Crypt::CBC->new(-cipher => 'Crypt::Crypt8', | |
312 | -pass => 'baby knows me well', | |
313 | -pbkdf => 'pbkdf2', | |
314 | -salt => '01234567')} or warn $@; | |
315 | $crypt->set_key_and_iv(); | |
316 | test($crypt->key eq $key,"key changed even when salt was forced"); | |
317 | test($crypt->iv eq $iv,"iv changed even when salt was forced"); | |
318 | $crypt = eval {Crypt::CBC->new(-cipher => 'Crypt::Crypt8', | |
319 | -pass => 'baby knows me well', | |
320 | -pbkdf => 'pbkdf2', | |
321 | -salt => '76543210')} or warn $@; | |
322 | $crypt->set_key_and_iv(); | |
323 | test($crypt->key ne $key,"key didn't change when salt was changed"); | |
324 | $crypt = eval { | |
325 | Crypt::CBC->new(-cipher => 'Crypt::Crypt8', | |
326 | -key => 'xyz', | |
327 | -header => 'salt', | |
328 | -salt => 1); | |
329 | }; | |
330 | test($crypt,"-salt=>1 is generating an exception: $@"); | |
226 | 331 | |
227 | 332 | exit 0; |
228 | 333 | |
229 | sub test ($$$){ | |
334 | my $number = 1; | |
335 | ||
336 | sub test ($$){ | |
230 | 337 | local($^W) = 0; |
231 | my($num, $true,$msg) = @_; | |
232 | print($true ? "ok $num\n" : "not ok $num $msg\n"); | |
338 | my($true,$msg) = @_; | |
339 | $msg =~ s/\n$//; | |
340 | ++$number; | |
341 | print($true ? "ok $number\n" : "not ok $number # $msg\n"); | |
342 | } | |
343 | ||
344 | sub skip { | |
345 | my ($msg) = @_; | |
346 | ++$number; | |
347 | print "ok $number # skip $msg\n"; | |
233 | 348 | } |
234 | 349 | |
235 | 350 | package Crypt::Crypt16; |
0 | #!/usr/local/bin/perl | |
1 | ||
2 | use lib '../blib/lib','../lib','./lib'; | |
3 | use strict; | |
4 | use Test; | |
5 | ||
6 | my $open_ssl_expected; | |
7 | ||
8 | BEGIN { | |
9 | $open_ssl_expected = { | |
10 | opensslv1 => {key => 'DFB4CADC622054E432B94423894DED3FF1CD3887DED9E23EB943C316F57A7901', | |
11 | iv => 'A43CCFB9D40566E759BF1E890833C05D' }, | |
12 | opensslv2 => {key => '429D56D40A7BAEB4462F9024DB29AD7C3F1ABF6DF91A6AA4EB461D76CA238317', | |
13 | iv => '104179D56A0EB898EF3254F3F81901C5' }, | |
14 | pbkdf2 => {iv => '8BD84A68D9F1C640A1530C21D31CAF7C', | |
15 | key=> 'F383A9DF2698C85EF21FCC8C3394182BAA344E733D71A11F65FEE88DC001C01A'}, | |
16 | }; | |
17 | plan tests => keys(%$open_ssl_expected) * 2; | |
18 | } | |
19 | ||
20 | use Crypt::CBC::PBKDF; | |
21 | ||
22 | for my $method (keys %$open_ssl_expected) { | |
23 | my $pb = Crypt::CBC::PBKDF->new($method); | |
24 | my ($key,$iv) = $pb->key_and_iv('12345678','foobar'); | |
25 | ok(uc unpack('H*',$key),$open_ssl_expected->{$method}{key}); | |
26 | ok(uc unpack('H*',$iv),$open_ssl_expected->{$method}{iv}); | |
27 | } | |
28 | ||
29 | exit 0; |
0 | #!/usr/local/bin/perl -Tw | |
0 | #!/usr/local/bin/perl -w | |
1 | 1 | |
2 | 2 | use strict; |
3 | use lib '..','../blib/lib','.','./blib/lib'; | |
3 | use lib './lib','./blib/lib'; | |
4 | 4 | |
5 | 5 | my (@mods,$cipherclass,$i,$c,$p,$test_data); |
6 | 6 | |
7 | @mods = qw/Eksblowfish | |
8 | Rijndael | |
9 | Blowfish | |
10 | Blowfish_PP | |
11 | IDEA | |
12 | DES | |
13 | /; | |
7 | @mods = qw/ | |
8 | Cipher::AES | |
9 | Eksblowfish | |
10 | Rijndael | |
11 | Blowfish | |
12 | Blowfish_PP | |
13 | IDEA | |
14 | DES | |
15 | /; | |
14 | 16 | |
15 | 17 | for my $mod (@mods) { |
16 | 18 | if (eval "use Crypt::$mod(); 1") { |
25 | 27 | exit; |
26 | 28 | } |
27 | 29 | |
28 | print "1..33\n"; | |
30 | print "1..34\n"; | |
29 | 31 | |
30 | 32 | sub test { |
31 | 33 | local($^W) = 0; |
51 | 53 | my $cipher = $cipherclass eq 'Crypt::Eksblowfish' ? $cipherclass->new(8,Crypt::CBC->_get_random_bytes(16),$key) |
52 | 54 | :$cipherclass->new($key); |
53 | 55 | |
54 | test(2,$i = Crypt::CBC->new(-cipher=>$cipher),"Couldn't create new object"); | |
56 | test(2,$i = Crypt::CBC->new(-cipher=>$cipher,-pbkdf=>'opensslv2'),"Couldn't create new object"); | |
55 | 57 | test(3,$c = $i->encrypt($test_data),"Couldn't encrypt"); |
56 | 58 | test(4,$p = $i->decrypt($c),"Couldn't decrypt"); |
57 | 59 | test(5,$p eq $test_data,"Decrypted ciphertext doesn't match plaintext"); |
75 | 77 | |
76 | 78 | $test_data = "This string ends in some spaces "; |
77 | 79 | test (33,$i->decrypt($i->encrypt($test_data)) eq $test_data); |
80 | ||
81 | # test that we can change the hasher | |
82 | if (eval "use Crypt::PBKDF2::Hash::HMACSHA1; 1") { | |
83 | my $hasher = Crypt::PBKDF2::Hash::HMACSHA1->new; | |
84 | $i = Crypt::CBC->new(-cipher => $cipher, | |
85 | -hasher => $hasher, | |
86 | -pbkdf => 'pbkdf2', | |
87 | ); | |
88 | test(34,$i->decrypt($i->encrypt($test_data)) eq $test_data); | |
89 | } else { | |
90 | print "ok 34 # skip Crypt::PBKDF2::Hash::HMACSHA1 not found\n"; | |
91 | } | |
92 | ||
93 |