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