7 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK);
13 @ISA = qw(Exporter DynaLoader);
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);
26 # If possible, inherit from Digest::base (which depends on MIME::Base64)
33 push(@ISA, 'Digest::base');
36 *hexdigest = \&Hexdigest;
37 *b64digest = \&B64digest;
40 # The following routines aren't time-critical, so they can be left in Perl
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)) {
50 shaclose($$class) if $$class;
51 $$class = shaopen($alg) || return;
54 $alg = 1 unless defined $alg;
55 my $state = shaopen($alg) || return;
63 shaclose($$self) if $$self;
68 my $state = shadup($$self) || return;
70 bless($copy, ref($self));
77 my($self, $data, $nbits) = @_;
78 unless (defined $nbits) {
79 $nbits = length($data);
80 $data = pack("B*", $data);
82 shawrite($data, $nbits, $$self);
90 Carp::croak("$msg: $!");
93 sub _addfile { # this is "addfile" from Digest::base 1.00
94 my ($self, $handle) = @_;
99 while (($n = read($handle, $buf, 4096))) {
102 _bail("Read failed") unless defined $n;
108 my ($self, $file, $mode) = @_;
110 return(_addfile($self, $file)) unless ref(\$file) eq 'SCALAR';
112 $mode = defined($mode) ? $mode : "";
113 my ($binary, $portable) = map { $_ eq $mode } ("b", "p");
117 open(FH, "<$file") or _bail("Open failed");
118 binmode(FH) if $binary || $portable;
120 unless ($portable && $text) {
121 $self->_addfile(*FH);
127 my ($buf1, $buf2) = ("", "");
129 while (($n1 = read(FH, $buf1, 4096))) {
130 while (substr($buf1, -1) eq "\015") {
131 $n2 = read(FH, $buf2, 4096);
132 _bail("Read failed") unless defined $n2;
136 $buf1 =~ s/\015?\015\012/\012/g; # DOS/Windows
137 $buf1 =~ s/\015/\012/g; # early MacOS
140 _bail("Read failed") unless defined $n1;
148 my $file = shift || "";
150 shadump($file, $$self) || return;
156 my $file = shift || "";
157 if (ref($class)) { # instance method
158 shaclose($$class) if $$class;
159 $$class = shaload($file) || return;
162 my $state = shaload($file) || return;
164 bless($self, $class);
168 Digest::SHA->bootstrap($VERSION);
175 Digest::SHA - Perl extension for SHA-1/224/256/384/512
181 # Functional interface
183 use Digest::SHA qw(sha1 sha1_hex sha1_base64 ...);
185 $digest = sha1($data);
186 $digest = sha1_hex($data);
187 $digest = sha1_base64($data);
189 $digest = sha256($data);
190 $digest = sha384_hex($data);
191 $digest = sha512_base64($data);
197 $sha = Digest::SHA->new($alg);
199 $sha->add($data); # feed data into stream
202 $sha->addfile($filename);
204 $sha->add_bits($bits);
205 $sha->add_bits($data, $nbits);
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
211 $digest = $sha->digest; # compute digest
212 $digest = $sha->hexdigest;
213 $digest = $sha->b64digest;
215 From the command line:
221 =head1 SYNOPSIS (HMAC-SHA)
223 # Functional interface only
225 use Digest::SHA qw(hmac_sha1 hmac_sha1_hex ...);
227 $digest = hmac_sha1($data, $key);
228 $digest = hmac_sha224_hex($data, $key);
229 $digest = hmac_sha256_base64($data, $key);
233 Digest::SHA is a complete implementation of the NIST Secure Hash
234 Standard. It gives Perl programmers a convenient way to calculate
235 SHA-1, SHA-224, SHA-256, SHA-384, and SHA-512 message digests.
236 The module can handle all types of input, including partial-byte
241 Digest::SHA is written in C for speed. If your platform lacks a
242 C compiler, you can install the functionally equivalent (but much
243 slower) L<Digest::SHA::PurePerl> module.
245 The programming interface is easy to use: it's the same one found
246 in CPAN's L<Digest> module. So, if your applications currently
247 use L<Digest::MD5> and you'd prefer the stronger security of SHA,
248 it's a simple matter to convert them.
250 The interface provides two ways to calculate digests: all-at-once,
251 or in stages. To illustrate, the following short program computes
252 the SHA-256 digest of "hello world" using each approach:
254 use Digest::SHA qw(sha256_hex);
256 $data = "hello world";
257 @frags = split(//, $data);
259 # all-at-once (Functional style)
260 $digest1 = sha256_hex($data);
262 # in-stages (OOP style)
263 $state = Digest::SHA->new(256);
264 for (@frags) { $state->add($_) }
265 $digest2 = $state->hexdigest;
267 print $digest1 eq $digest2 ?
268 "whew!\n" : "oops!\n";
270 To calculate the digest of an n-bit message where I<n> is not a
271 multiple of 8, use the I<add_bits()> method. For example, consider
272 the 446-bit message consisting of the bit-string "110" repeated
273 148 times, followed by "11". Here's how to display its SHA-1
277 $bits = "110" x 148 . "11";
278 $sha = Digest::SHA->new(1)->add_bits($bits);
279 print $sha->hexdigest, "\n";
281 Note that for larger bit-strings, it's more efficient to use the
282 two-argument version I<add_bits($data, $nbits)>, where I<$data> is
283 in the customary packed binary format used for Perl strings.
285 The module also lets you save intermediate SHA states to disk, or
286 display them on standard output. The I<dump()> method generates
287 portable, human-readable text describing the current state of
288 computation. You can subsequently retrieve the file with I<load()>
289 to resume where the calculation left off.
291 To see what a state description looks like, just run the following:
294 Digest::SHA->new->add("Shaw" x 1962)->dump;
296 As an added convenience, the Digest::SHA module offers routines to
297 calculate keyed hashes using the HMAC-SHA-1/224/256/384/512
298 algorithms. These services exist in functional form only, and
299 mimic the style and behavior of the I<sha()>, I<sha_hex()>, and
300 I<sha_base64()> functions.
302 # Test vector from draft-ietf-ipsec-ciph-sha-256-01.txt
304 use Digest::SHA qw(hmac_sha256_hex);
305 print hmac_sha256_hex("Hi There", chr(0x0b) x 32), "\n";
307 =head1 NIST STATEMENT ON SHA-1
309 I<NIST was recently informed that researchers had discovered a way
310 to "break" the current Federal Information Processing Standard SHA-1
311 algorithm, which has been in effect since 1994. The researchers
312 have not yet published their complete results, so NIST has not
313 confirmed these findings. However, the researchers are a reputable
314 research team with expertise in this area.>
316 I<Due to advances in computing power, NIST already planned to phase
317 out SHA-1 in favor of the larger and stronger hash functions (SHA-224,
318 SHA-256, SHA-384 and SHA-512) by 2010. New developments should use
319 the larger and stronger hash functions.>
321 ref. L<http://www.csrc.nist.gov/pki/HashWorkshop/NIST%20Statement/Burr_Mar2005.html>
323 =head1 PADDING OF BASE64 DIGESTS
325 By convention, CPAN Digest modules do B<not> pad their Base64 output.
326 Problems can occur when feeding such digests to other software that
327 expects properly padded Base64 encodings.
329 For the time being, any necessary padding must be done by the user.
330 Fortunately, this is a simple operation: if the length of a Base64-encoded
331 digest isn't a multiple of 4, simply append "=" characters to the end
332 of the digest until it is:
334 while (length($b64_digest) % 4) {
338 To illustrate, I<sha256_base64("abc")> is computed to be
340 ungWv48Bz+pBQUDeXa4iI7ADYaOWF3qctBD/YfIAFa0
342 which has a length of 43. So, the properly padded version is
344 ungWv48Bz+pBQUDeXa4iI7ADYaOWF3qctBD/YfIAFa0=
350 =head1 EXPORTABLE FUNCTIONS
352 Provided your C compiler supports a 64-bit type (e.g. the I<long
353 long> of C99, or I<__int64> used by Microsoft C/C++), all of these
354 functions will be available for use. Otherwise, you won't be able
355 to perform the SHA-384 and SHA-512 transforms, both of which require
362 =item B<sha1($data, ...)>
364 =item B<sha224($data, ...)>
366 =item B<sha256($data, ...)>
368 =item B<sha384($data, ...)>
370 =item B<sha512($data, ...)>
372 Logically joins the arguments into a single string, and returns
373 its SHA-1/224/256/384/512 digest encoded as a binary string.
375 =item B<sha1_hex($data, ...)>
377 =item B<sha224_hex($data, ...)>
379 =item B<sha256_hex($data, ...)>
381 =item B<sha384_hex($data, ...)>
383 =item B<sha512_hex($data, ...)>
385 Logically joins the arguments into a single string, and returns
386 its SHA-1/224/256/384/512 digest encoded as a hexadecimal string.
388 =item B<sha1_base64($data, ...)>
390 =item B<sha224_base64($data, ...)>
392 =item B<sha256_base64($data, ...)>
394 =item B<sha384_base64($data, ...)>
396 =item B<sha512_base64($data, ...)>
398 Logically joins the arguments into a single string, and returns
399 its SHA-1/224/256/384/512 digest encoded as a Base64 string.
401 It's important to note that the resulting string does B<not> contain
402 the padding characters typical of Base64 encodings. This omission is
403 deliberate, and is done to maintain compatibility with the family of
404 CPAN Digest modules. See L</"PADDING OF BASE64 DIGESTS"> for details.
414 Returns a new Digest::SHA object. Allowed values for I<$alg> are
415 1, 224, 256, 384, or 512. It's also possible to use common string
416 representations of the algorithm (e.g. "sha256", "SHA-384"). If
417 the argument is missing, SHA-1 will be used by default.
419 Invoking I<new> as an instance method will not create a new object;
420 instead, it will simply reset the object to the initial state
421 associated with I<$alg>. If the argument is missing, the object
422 will continue using the same algorithm that was selected at creation.
426 This method has exactly the same effect as I<new($alg)>. In fact,
427 I<reset> is just an alias for I<new>.
431 Returns the number of digest bits for this object. The values are
432 160, 224, 256, 384, and 512 for SHA-1, SHA-224, SHA-256, SHA-384,
433 and SHA-512, respectively.
437 Returns the digest algorithm for this object. The values are 1,
438 224, 256, 384, and 512 for SHA-1, SHA-224, SHA-256, SHA-384, and
439 SHA-512, respectively.
443 Returns a duplicate copy of the object.
445 =item B<add($data, ...)>
447 Logically joins the arguments into a single string, and uses it to
448 update the current digest state. In other words, the following
449 statements have the same effect:
451 $sha->add("a"); $sha->add("b"); $sha->add("c");
452 $sha->add("a")->add("b")->add("c");
453 $sha->add("a", "b", "c");
456 The return value is the updated object itself.
458 =item B<add_bits($data, $nbits)>
460 =item B<add_bits($bits)>
462 Updates the current digest state by appending bits to it. The
463 return value is the updated object itself.
465 The first form causes the most-significant I<$nbits> of I<$data>
466 to be appended to the stream. The I<$data> argument is in the
467 customary binary format used for Perl strings.
469 The second form takes an ASCII string of "0" and "1" characters as
470 its argument. It's equivalent to
472 $sha->add_bits(pack("B*", $bits), length($bits));
474 So, the following two statements do the same thing:
476 $sha->add_bits("111100001010");
477 $sha->add_bits("\xF0\xA0", 12);
479 =item B<addfile(*FILE)>
481 Reads from I<FILE> until EOF, and appends that data to the current
482 state. The return value is the updated object itself.
484 =item B<addfile($filename [, $mode])>
486 Reads the contents of I<$filename>, and appends that data to the current
487 state. The return value is the updated object itself.
489 By default, I<$filename> is simply opened and read; no special modes
490 or I/O disciplines are used. To change this, set the optional I<$mode>
491 argument to one of the following values:
493 "b" read file in binary mode
495 "p" use portable mode
497 The "p" mode is handy since it ensures that the digest value of
498 I<$filename> will be the same when computed on different operating
499 systems. It accomplishes this by internally translating all newlines
500 in text files to UNIX format before calculating the digest; on the other
501 hand, binary files are read in raw mode with no translation whatsoever.
503 For a fuller discussion of newline formats, refer to CPAN module
504 L<File::LocalizeNewlines>. Its "universal line separator" regex forms
505 the basis of I<addfile>'s portable mode processing.
507 =item B<dump($filename)>
509 Provides persistent storage of intermediate SHA states by writing
510 a portable, human-readable representation of the current state to
511 I<$filename>. If the argument is missing, or equal to the empty
512 string, the state information will be written to STDOUT.
514 =item B<load($filename)>
516 Returns a Digest::SHA object representing the intermediate SHA
517 state that was previously dumped to I<$filename>. If called as a
518 class method, a new object is created; if called as an instance
519 method, the object is reset to the state contained in I<$filename>.
520 If the argument is missing, or equal to the empty string, the state
521 information will be read from STDIN.
525 Returns the digest encoded as a binary string.
527 Note that the I<digest> method is a read-once operation. Once it
528 has been performed, the Digest::SHA object is automatically reset
529 in preparation for calculating another digest value. Call
530 I<$sha-E<gt>clone-E<gt>digest> if it's necessary to preserve the
531 original digest state.
535 Returns the digest encoded as a hexadecimal string.
537 Like I<digest>, this method is a read-once operation. Call
538 I<$sha-E<gt>clone-E<gt>hexdigest> if it's necessary to preserve
539 the original digest state.
541 This method is inherited if L<Digest::base> is installed on your
542 system. Otherwise, a functionally equivalent substitute is used.
546 Returns the digest encoded as a Base64 string.
548 Like I<digest>, this method is a read-once operation. Call
549 I<$sha-E<gt>clone-E<gt>b64digest> if it's necessary to preserve
550 the original digest state.
552 This method is inherited if L<Digest::base> is installed on your
553 system. Otherwise, a functionally equivalent substitute is used.
555 It's important to note that the resulting string does B<not> contain
556 the padding characters typical of Base64 encodings. This omission is
557 deliberate, and is done to maintain compatibility with the family of
558 CPAN Digest modules. See L</"PADDING OF BASE64 DIGESTS"> for details.
562 I<HMAC-SHA-1/224/256/384/512>
566 =item B<hmac_sha1($data, $key)>
568 =item B<hmac_sha224($data, $key)>
570 =item B<hmac_sha256($data, $key)>
572 =item B<hmac_sha384($data, $key)>
574 =item B<hmac_sha512($data, $key)>
576 Returns the HMAC-SHA-1/224/256/384/512 digest of I<$data>/I<$key>,
577 with the result encoded as a binary string. Multiple I<$data>
578 arguments are allowed, provided that I<$key> is the last argument
581 =item B<hmac_sha1_hex($data, $key)>
583 =item B<hmac_sha224_hex($data, $key)>
585 =item B<hmac_sha256_hex($data, $key)>
587 =item B<hmac_sha384_hex($data, $key)>
589 =item B<hmac_sha512_hex($data, $key)>
591 Returns the HMAC-SHA-1/224/256/384/512 digest of I<$data>/I<$key>,
592 with the result encoded as a hexadecimal string. Multiple I<$data>
593 arguments are allowed, provided that I<$key> is the last argument
596 =item B<hmac_sha1_base64($data, $key)>
598 =item B<hmac_sha224_base64($data, $key)>
600 =item B<hmac_sha256_base64($data, $key)>
602 =item B<hmac_sha384_base64($data, $key)>
604 =item B<hmac_sha512_base64($data, $key)>
606 Returns the HMAC-SHA-1/224/256/384/512 digest of I<$data>/I<$key>,
607 with the result encoded as a Base64 string. Multiple I<$data>
608 arguments are allowed, provided that I<$key> is the last argument
611 It's important to note that the resulting string does B<not> contain
612 the padding characters typical of Base64 encodings. This omission is
613 deliberate, and is done to maintain compatibility with the family of
614 CPAN Digest modules. See L</"PADDING OF BASE64 DIGESTS"> for details.
620 L<Digest>, L<Digest::SHA::PurePerl>
622 The Secure Hash Standard (FIPS PUB 180-2) can be found at:
624 L<http://csrc.nist.gov/publications/fips/fips180-2/fips180-2withchangenotice.pdf>
626 The Keyed-Hash Message Authentication Code (HMAC):
628 L<http://csrc.nist.gov/publications/fips/fips198/fips-198a.pdf>
632 Mark Shelor <mshelor@cpan.org>
634 =head1 ACKNOWLEDGMENTS
636 The author is particularly grateful to
654 for their valuable comments and suggestions.
656 =head1 COPYRIGHT AND LICENSE
658 Copyright (C) 2003-2007 Mark Shelor
660 This library is free software; you can redistribute it and/or modify
661 it under the same terms as Perl itself.