This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
f809ce3afbcc35a788641f5e541930857deca10f
[perl5.git] / cpan / Digest-SHA / lib / Digest / SHA.pm
1 package Digest::SHA;
2
3 require 5.003000;
4
5 use strict;
6 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK);
7 use Fcntl;
8 use integer;
9
10 $VERSION = '5.61';
11
12 require Exporter;
13 require DynaLoader;
14 @ISA = qw(Exporter DynaLoader);
15 @EXPORT_OK = qw(
16         hmac_sha1       hmac_sha1_base64        hmac_sha1_hex
17         hmac_sha224     hmac_sha224_base64      hmac_sha224_hex
18         hmac_sha256     hmac_sha256_base64      hmac_sha256_hex
19         hmac_sha384     hmac_sha384_base64      hmac_sha384_hex
20         hmac_sha512     hmac_sha512_base64      hmac_sha512_hex
21         hmac_sha512224  hmac_sha512224_base64   hmac_sha512224_hex
22         hmac_sha512256  hmac_sha512256_base64   hmac_sha512256_hex
23         sha1            sha1_base64             sha1_hex
24         sha224          sha224_base64           sha224_hex
25         sha256          sha256_base64           sha256_hex
26         sha384          sha384_base64           sha384_hex
27         sha512          sha512_base64           sha512_hex
28         sha512224       sha512224_base64        sha512224_hex
29         sha512256       sha512256_base64        sha512256_hex);
30
31 # If possible, inherit from Digest::base (which depends on MIME::Base64)
32
33 *addfile = \&Addfile;
34
35 eval {
36         require MIME::Base64;
37         require Digest::base;
38         push(@ISA, 'Digest::base');
39 };
40 if ($@) {
41         *hexdigest = \&Hexdigest;
42         *b64digest = \&B64digest;
43 }
44
45 # The following routines aren't time-critical, so they can be left in Perl
46
47 sub new {
48         my($class, $alg) = @_;
49         $alg =~ s/\D+//g if defined $alg;
50         if (ref($class)) {      # instance method
51                 unless (defined($alg) && ($alg != $class->algorithm)) {
52                         sharewind($$class);
53                         return($class);
54                 }
55                 shaclose($$class) if $$class;
56                 $$class = shaopen($alg) || return;
57                 return($class);
58         }
59         $alg = 1 unless defined $alg;
60         my $state = shaopen($alg) || return;
61         my $self = \$state;
62         bless($self, $class);
63         return($self);
64 }
65
66 sub DESTROY {
67         my $self = shift;
68         shaclose($$self) if $$self;
69 }
70
71 sub clone {
72         my $self = shift;
73         my $state = shadup($$self) || return;
74         my $copy = \$state;
75         bless($copy, ref($self));
76         return($copy);
77 }
78
79 *reset = \&new;
80
81 sub add_bits {
82         my($self, $data, $nbits) = @_;
83         unless (defined $nbits) {
84                 $nbits = length($data);
85                 $data = pack("B*", $data);
86         }
87         shawrite($data, $nbits, $$self);
88         return($self);
89 }
90
91 sub _bail {
92         my $msg = shift;
93
94         require Carp;
95         Carp::croak("$msg: $!");
96 }
97
98 sub _addfile {  # this is "addfile" from Digest::base 1.00
99     my ($self, $handle) = @_;
100
101     my $n;
102     my $buf = "";
103
104     while (($n = read($handle, $buf, 4096))) {
105         $self->add($buf);
106     }
107     _bail("Read failed") unless defined $n;
108
109     $self;
110 }
111
112 sub Addfile {
113         my ($self, $file, $mode) = @_;
114
115         return(_addfile($self, $file)) unless ref(\$file) eq 'SCALAR';
116
117         $mode = defined($mode) ? $mode : "";
118         my ($binary, $portable) = map { $_ eq $mode } ("b", "p");
119
120                 ## Always interpret "-" to mean STDIN; otherwise use
121                 ## sysopen to handle full range of POSIX file names
122         local *FH;
123         $file eq '-' and open(FH, '< -')
124                 or sysopen(FH, $file, O_RDONLY)
125                         or _bail('Open failed');
126         binmode(FH) if $binary || $portable;
127
128         unless ($portable && -T $file) {
129                 $self->_addfile(*FH);
130                 close(FH);
131                 return($self);
132         }
133
134         my ($n1, $n2);
135         my ($buf1, $buf2) = ("", "");
136
137         while (($n1 = read(FH, $buf1, 4096))) {
138                 while (substr($buf1, -1) eq "\015") {
139                         $n2 = read(FH, $buf2, 4096);
140                         _bail("Read failed") unless defined $n2;
141                         last unless $n2;
142                         $buf1 .= $buf2;
143                 }
144                 $buf1 =~ s/\015?\015\012/\012/g;        # DOS/Windows
145                 $buf1 =~ s/\015/\012/g;                 # early MacOS
146                 $self->add($buf1);
147         }
148         _bail("Read failed") unless defined $n1;
149         close(FH);
150
151         $self;
152 }
153
154 sub dump {
155         my $self = shift;
156         my $file = shift || "";
157
158         shadump($file, $$self) || return;
159         return($self);
160 }
161
162 sub load {
163         my $class = shift;
164         my $file = shift || "";
165         if (ref($class)) {      # instance method
166                 shaclose($$class) if $$class;
167                 $$class = shaload($file) || return;
168                 return($class);
169         }
170         my $state = shaload($file) || return;
171         my $self = \$state;
172         bless($self, $class);
173         return($self);
174 }
175
176 Digest::SHA->bootstrap($VERSION);
177
178 1;
179 __END__
180
181 =head1 NAME
182
183 Digest::SHA - Perl extension for SHA-1/224/256/384/512
184
185 =head1 SYNOPSIS
186
187 In programs:
188
189                 # Functional interface
190
191         use Digest::SHA qw(sha1 sha1_hex sha1_base64 ...);
192
193         $digest = sha1($data);
194         $digest = sha1_hex($data);
195         $digest = sha1_base64($data);
196
197         $digest = sha256($data);
198         $digest = sha384_hex($data);
199         $digest = sha512_base64($data);
200
201                 # Object-oriented
202
203         use Digest::SHA;
204
205         $sha = Digest::SHA->new($alg);
206
207         $sha->add($data);               # feed data into stream
208
209         $sha->addfile(*F);
210         $sha->addfile($filename);
211
212         $sha->add_bits($bits);
213         $sha->add_bits($data, $nbits);
214
215         $sha_copy = $sha->clone;        # if needed, make copy of
216         $sha->dump($file);              #       current digest state,
217         $sha->load($file);              #       or save it on disk
218
219         $digest = $sha->digest;         # compute digest
220         $digest = $sha->hexdigest;
221         $digest = $sha->b64digest;
222
223 From the command line:
224
225         $ shasum files
226
227         $ shasum --help
228
229 =head1 SYNOPSIS (HMAC-SHA)
230
231                 # Functional interface only
232
233         use Digest::SHA qw(hmac_sha1 hmac_sha1_hex ...);
234
235         $digest = hmac_sha1($data, $key);
236         $digest = hmac_sha224_hex($data, $key);
237         $digest = hmac_sha256_base64($data, $key);
238
239 =head1 ABSTRACT
240
241 Digest::SHA is a complete implementation of the NIST Secure Hash Standard.
242 It gives Perl programmers a convenient way to calculate SHA-1, SHA-224,
243 SHA-256, SHA-384, SHA-512, SHA-512/224, and SHA-512/256 message digests.
244 The module can handle all types of input, including partial-byte data.
245
246 =head1 DESCRIPTION
247
248 Digest::SHA is written in C for speed.  If your platform lacks a
249 C compiler, you can install the functionally equivalent (but much
250 slower) L<Digest::SHA::PurePerl> module.
251
252 The programming interface is easy to use: it's the same one found
253 in CPAN's L<Digest> module.  So, if your applications currently
254 use L<Digest::MD5> and you'd prefer the stronger security of SHA,
255 it's a simple matter to convert them.
256
257 The interface provides two ways to calculate digests:  all-at-once,
258 or in stages.  To illustrate, the following short program computes
259 the SHA-256 digest of "hello world" using each approach:
260
261         use Digest::SHA qw(sha256_hex);
262
263         $data = "hello world";
264         @frags = split(//, $data);
265
266         # all-at-once (Functional style)
267         $digest1 = sha256_hex($data);
268
269         # in-stages (OOP style)
270         $state = Digest::SHA->new(256);
271         for (@frags) { $state->add($_) }
272         $digest2 = $state->hexdigest;
273
274         print $digest1 eq $digest2 ?
275                 "whew!\n" : "oops!\n";
276
277 To calculate the digest of an n-bit message where I<n> is not a
278 multiple of 8, use the I<add_bits()> method.  For example, consider
279 the 446-bit message consisting of the bit-string "110" repeated
280 148 times, followed by "11".  Here's how to display its SHA-1
281 digest:
282
283         use Digest::SHA;
284         $bits = "110" x 148 . "11";
285         $sha = Digest::SHA->new(1)->add_bits($bits);
286         print $sha->hexdigest, "\n";
287
288 Note that for larger bit-strings, it's more efficient to use the
289 two-argument version I<add_bits($data, $nbits)>, where I<$data> is
290 in the customary packed binary format used for Perl strings.
291
292 The module also lets you save intermediate SHA states to disk, or
293 display them on standard output.  The I<dump()> method generates
294 portable, human-readable text describing the current state of
295 computation.  You can subsequently retrieve the file with I<load()>
296 to resume where the calculation left off.
297
298 To see what a state description looks like, just run the following:
299
300         use Digest::SHA;
301         Digest::SHA->new->add("Shaw" x 1962)->dump;
302
303 As an added convenience, the Digest::SHA module offers routines to
304 calculate keyed hashes using the HMAC-SHA-1/224/256/384/512
305 algorithms.  These services exist in functional form only, and
306 mimic the style and behavior of the I<sha()>, I<sha_hex()>, and
307 I<sha_base64()> functions.
308
309         # Test vector from draft-ietf-ipsec-ciph-sha-256-01.txt
310
311         use Digest::SHA qw(hmac_sha256_hex);
312         print hmac_sha256_hex("Hi There", chr(0x0b) x 32), "\n";
313
314 =head1 NIST STATEMENT ON SHA-1
315
316 I<NIST was recently informed that researchers had discovered a way
317 to "break" the current Federal Information Processing Standard SHA-1
318 algorithm, which has been in effect since 1994. The researchers
319 have not yet published their complete results, so NIST has not
320 confirmed these findings. However, the researchers are a reputable
321 research team with expertise in this area.>
322
323 I<Due to advances in computing power, NIST already planned to phase
324 out SHA-1 in favor of the larger and stronger hash functions (SHA-224,
325 SHA-256, SHA-384 and SHA-512) by 2010. New developments should use
326 the larger and stronger hash functions.>
327
328 ref. L<http://www.csrc.nist.gov/pki/HashWorkshop/NIST%20Statement/Burr_Mar2005.html>
329
330 =head1 PADDING OF BASE64 DIGESTS
331
332 By convention, CPAN Digest modules do B<not> pad their Base64 output.
333 Problems can occur when feeding such digests to other software that
334 expects properly padded Base64 encodings.
335
336 For the time being, any necessary padding must be done by the user.
337 Fortunately, this is a simple operation: if the length of a Base64-encoded
338 digest isn't a multiple of 4, simply append "=" characters to the end
339 of the digest until it is:
340
341         while (length($b64_digest) % 4) {
342                 $b64_digest .= '=';
343         }
344
345 To illustrate, I<sha256_base64("abc")> is computed to be
346
347         ungWv48Bz+pBQUDeXa4iI7ADYaOWF3qctBD/YfIAFa0
348
349 which has a length of 43.  So, the properly padded version is
350
351         ungWv48Bz+pBQUDeXa4iI7ADYaOWF3qctBD/YfIAFa0=
352
353 =head1 EXPORT
354
355 None by default.
356
357 =head1 EXPORTABLE FUNCTIONS
358
359 Provided your C compiler supports a 64-bit type (e.g. the I<long
360 long> of C99, or I<__int64> used by Microsoft C/C++), all of these
361 functions will be available for use.  Otherwise, you won't be able
362 to perform the SHA-384 and SHA-512 transforms, both of which require
363 64-bit operations.
364
365 I<Functional style>
366
367 =over 4
368
369 =item B<sha1($data, ...)>
370
371 =item B<sha224($data, ...)>
372
373 =item B<sha256($data, ...)>
374
375 =item B<sha384($data, ...)>
376
377 =item B<sha512($data, ...)>
378
379 =item B<sha512224($data, ...)>
380
381 =item B<sha512256($data, ...)>
382
383 Logically joins the arguments into a single string, and returns
384 its SHA-1/224/256/384/512 digest encoded as a binary string.
385
386 =item B<sha1_hex($data, ...)>
387
388 =item B<sha224_hex($data, ...)>
389
390 =item B<sha256_hex($data, ...)>
391
392 =item B<sha384_hex($data, ...)>
393
394 =item B<sha512_hex($data, ...)>
395
396 =item B<sha512224_hex($data, ...)>
397
398 =item B<sha512256_hex($data, ...)>
399
400 Logically joins the arguments into a single string, and returns
401 its SHA-1/224/256/384/512 digest encoded as a hexadecimal string.
402
403 =item B<sha1_base64($data, ...)>
404
405 =item B<sha224_base64($data, ...)>
406
407 =item B<sha256_base64($data, ...)>
408
409 =item B<sha384_base64($data, ...)>
410
411 =item B<sha512_base64($data, ...)>
412
413 =item B<sha512224_base64($data, ...)>
414
415 =item B<sha512256_base64($data, ...)>
416
417 Logically joins the arguments into a single string, and returns
418 its SHA-1/224/256/384/512 digest encoded as a Base64 string.
419
420 It's important to note that the resulting string does B<not> contain
421 the padding characters typical of Base64 encodings.  This omission is
422 deliberate, and is done to maintain compatibility with the family of
423 CPAN Digest modules.  See L</"PADDING OF BASE64 DIGESTS"> for details.
424
425 =back
426
427 I<OOP style>
428
429 =over 4
430
431 =item B<new($alg)>
432
433 Returns a new Digest::SHA object.  Allowed values for I<$alg> are 1,
434 224, 256, 384, 512, 512224, or 512256.  It's also possible to use
435 common string representations of the algorithm (e.g. "sha256",
436 "SHA-384").  If the argument is missing, SHA-1 will be used by
437 default.
438
439 Invoking I<new> as an instance method will not create a new object;
440 instead, it will simply reset the object to the initial state
441 associated with I<$alg>.  If the argument is missing, the object
442 will continue using the same algorithm that was selected at creation.
443
444 =item B<reset($alg)>
445
446 This method has exactly the same effect as I<new($alg)>.  In fact,
447 I<reset> is just an alias for I<new>.
448
449 =item B<hashsize>
450
451 Returns the number of digest bits for this object.  The values are
452 160, 224, 256, 384, 512, 224, and 256 for SHA-1, SHA-224, SHA-256,
453 SHA-384, SHA-512, SHA-512/224 and SHA-512/256, respectively.
454
455 =item B<algorithm>
456
457 Returns the digest algorithm for this object.  The values are 1,
458 224, 256, 384, 512, 512224, and 512256 for SHA-1, SHA-224, SHA-256,
459 SHA-384, SHA-512, SHA-512/224, and SHA-512/256, respectively.
460
461 =item B<clone>
462
463 Returns a duplicate copy of the object.
464
465 =item B<add($data, ...)>
466
467 Logically joins the arguments into a single string, and uses it to
468 update the current digest state.  In other words, the following
469 statements have the same effect:
470
471         $sha->add("a"); $sha->add("b"); $sha->add("c");
472         $sha->add("a")->add("b")->add("c");
473         $sha->add("a", "b", "c");
474         $sha->add("abc");
475
476 The return value is the updated object itself.
477
478 =item B<add_bits($data, $nbits)>
479
480 =item B<add_bits($bits)>
481
482 Updates the current digest state by appending bits to it.  The
483 return value is the updated object itself.
484
485 The first form causes the most-significant I<$nbits> of I<$data>
486 to be appended to the stream.  The I<$data> argument is in the
487 customary binary format used for Perl strings.
488
489 The second form takes an ASCII string of "0" and "1" characters as
490 its argument.  It's equivalent to
491
492         $sha->add_bits(pack("B*", $bits), length($bits));
493
494 So, the following two statements do the same thing:
495
496         $sha->add_bits("111100001010");
497         $sha->add_bits("\xF0\xA0", 12);
498
499 =item B<addfile(*FILE)>
500
501 Reads from I<FILE> until EOF, and appends that data to the current
502 state.  The return value is the updated object itself.
503
504 =item B<addfile($filename [, $mode])>
505
506 Reads the contents of I<$filename>, and appends that data to the current
507 state.  The return value is the updated object itself.
508
509 By default, I<$filename> is simply opened and read; no special modes
510 or I/O disciplines are used.  To change this, set the optional I<$mode>
511 argument to one of the following values:
512
513         "b"     read file in binary mode
514
515         "p"     use portable mode
516
517 The "p" mode is handy since it ensures that the digest value of
518 I<$filename> will be the same when computed on different operating
519 systems.  It accomplishes this by internally translating all newlines in
520 text files to UNIX format before calculating the digest.  Binary files
521 are read in raw mode with no translation whatsoever.
522
523 For a fuller discussion of newline formats, refer to CPAN module
524 L<File::LocalizeNewlines>.  Its "universal line separator" regex forms
525 the basis of I<addfile>'s portable mode processing.
526
527 =item B<dump($filename)>
528
529 Provides persistent storage of intermediate SHA states by writing
530 a portable, human-readable representation of the current state to
531 I<$filename>.  If the argument is missing, or equal to the empty
532 string, the state information will be written to STDOUT.
533
534 =item B<load($filename)>
535
536 Returns a Digest::SHA object representing the intermediate SHA
537 state that was previously dumped to I<$filename>.  If called as a
538 class method, a new object is created; if called as an instance
539 method, the object is reset to the state contained in I<$filename>.
540 If the argument is missing, or equal to the empty string, the state
541 information will be read from STDIN.
542
543 =item B<digest>
544
545 Returns the digest encoded as a binary string.
546
547 Note that the I<digest> method is a read-once operation. Once it
548 has been performed, the Digest::SHA object is automatically reset
549 in preparation for calculating another digest value.  Call
550 I<$sha-E<gt>clone-E<gt>digest> if it's necessary to preserve the
551 original digest state.
552
553 =item B<hexdigest>
554
555 Returns the digest encoded as a hexadecimal string.
556
557 Like I<digest>, this method is a read-once operation.  Call
558 I<$sha-E<gt>clone-E<gt>hexdigest> if it's necessary to preserve
559 the original digest state.
560
561 This method is inherited if L<Digest::base> is installed on your
562 system.  Otherwise, a functionally equivalent substitute is used.
563
564 =item B<b64digest>
565
566 Returns the digest encoded as a Base64 string.
567
568 Like I<digest>, this method is a read-once operation.  Call
569 I<$sha-E<gt>clone-E<gt>b64digest> if it's necessary to preserve
570 the original digest state.
571
572 This method is inherited if L<Digest::base> is installed on your
573 system.  Otherwise, a functionally equivalent substitute is used.
574
575 It's important to note that the resulting string does B<not> contain
576 the padding characters typical of Base64 encodings.  This omission is
577 deliberate, and is done to maintain compatibility with the family of
578 CPAN Digest modules.  See L</"PADDING OF BASE64 DIGESTS"> for details.
579
580 =back
581
582 I<HMAC-SHA-1/224/256/384/512>
583
584 =over 4
585
586 =item B<hmac_sha1($data, $key)>
587
588 =item B<hmac_sha224($data, $key)>
589
590 =item B<hmac_sha256($data, $key)>
591
592 =item B<hmac_sha384($data, $key)>
593
594 =item B<hmac_sha512($data, $key)>
595
596 =item B<hmac_sha512224($data, $key)>
597
598 =item B<hmac_sha512256($data, $key)>
599
600 Returns the HMAC-SHA-1/224/256/384/512 digest of I<$data>/I<$key>,
601 with the result encoded as a binary string.  Multiple I<$data>
602 arguments are allowed, provided that I<$key> is the last argument
603 in the list.
604
605 =item B<hmac_sha1_hex($data, $key)>
606
607 =item B<hmac_sha224_hex($data, $key)>
608
609 =item B<hmac_sha256_hex($data, $key)>
610
611 =item B<hmac_sha384_hex($data, $key)>
612
613 =item B<hmac_sha512_hex($data, $key)>
614
615 =item B<hmac_sha512224_hex($data, $key)>
616
617 =item B<hmac_sha512256_hex($data, $key)>
618
619 Returns the HMAC-SHA-1/224/256/384/512 digest of I<$data>/I<$key>,
620 with the result encoded as a hexadecimal string.  Multiple I<$data>
621 arguments are allowed, provided that I<$key> is the last argument
622 in the list.
623
624 =item B<hmac_sha1_base64($data, $key)>
625
626 =item B<hmac_sha224_base64($data, $key)>
627
628 =item B<hmac_sha256_base64($data, $key)>
629
630 =item B<hmac_sha384_base64($data, $key)>
631
632 =item B<hmac_sha512_base64($data, $key)>
633
634 =item B<hmac_sha512224_base64($data, $key)>
635
636 =item B<hmac_sha512256_base64($data, $key)>
637
638 Returns the HMAC-SHA-1/224/256/384/512 digest of I<$data>/I<$key>,
639 with the result encoded as a Base64 string.  Multiple I<$data>
640 arguments are allowed, provided that I<$key> is the last argument
641 in the list.
642
643 It's important to note that the resulting string does B<not> contain
644 the padding characters typical of Base64 encodings.  This omission is
645 deliberate, and is done to maintain compatibility with the family of
646 CPAN Digest modules.  See L</"PADDING OF BASE64 DIGESTS"> for details.
647
648 =back
649
650 =head1 SEE ALSO
651
652 L<Digest>, L<Digest::SHA::PurePerl>
653
654 The Secure Hash Standard (Draft FIPS PUB 180-4) can be found at:
655
656 L<http://csrc.nist.gov/publications/drafts/fips180-4/Draft-FIPS180-4_Feb2011.pdf>
657
658 The Keyed-Hash Message Authentication Code (HMAC):
659
660 L<http://csrc.nist.gov/publications/fips/fips198/fips-198a.pdf>
661
662 =head1 AUTHOR
663
664         Mark Shelor     <mshelor@cpan.org>
665
666 =head1 ACKNOWLEDGMENTS
667
668 The author is particularly grateful to
669
670         Gisle Aas
671         Sean Burke
672         Chris Carey
673         Alexandr Ciornii
674         Jim Doble
675         Julius Duque
676         Jeffrey Friedl
677         Robert Gilmour
678         Brian Gladman
679         Adam Kennedy
680         Andy Lester
681         Alex Muntada
682         Steve Peters
683         Chris Skiscim
684         Martin Thurn
685         Gunnar Wolf
686         Adam Woodbury
687
688 "who by trained skill rescued life from such great billows and such thick
689 darkness and moored it in so perfect a calm and in so brilliant a light"
690 - Lucretius
691
692 =head1 COPYRIGHT AND LICENSE
693
694 Copyright (C) 2003-2011 Mark Shelor
695
696 This library is free software; you can redistribute it and/or modify
697 it under the same terms as Perl itself.
698
699 L<perlartistic>
700
701 =cut