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