home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam    

Book HomeJava and XSLTSearch this book

8.57. Digest

The Digest modules (Digest::MD2, Digest::MD5, Digest::SHA1, and Digest::-HMAC) calculate a digest of data that they encounter. These digests are often referred to as "fingerprints," "hashes," or "sums." The Digest modules return a small, fixed-length string, depending on how you've requested your data. If you change your data and regenerate the digest, the digest will be different each time the data itself changes. As of Perl 5.8, the Digest modules are bundled with the Perl source kit.

The Digest modules both a functional interface and an object-oriented interface. If you use the object-oriented inteface, you have the benefit of being able to send data of arbitrary length. You can also tell the Digest module to read files directly.

Digest delivers the hashed data in one of three formats: binary, hex, or base64. The following example uses Digest and calculates an MD5 sum of a string, $text, that represents the data. The data is output in hexadecimal form.

#!/usr/local/bin/perl -w
use Digest;
my $text = 'Be the ball, Danny!';
my $md5 = Digest->MD5;

my $hashed = $md5->hexdigest;

print "The sum of \$text is [$hashed].\n";

This gives you:

The sum of $text is [6eec91414372ad157fc9d3d15b496d93].

Digest implements the following functions for the object-oriented interface. These functions are available to all of the Digest modules.



Alias for new.


add(data, ...)

Appends data to the message for which you calculate the digest. add returns the Digest object itself.



Reads io_handle until end-of-file and, like add, appends the content to the message for which you calculate the digest. addfile returns the Digest object itself.



Same as digest, but returns the digest in base64-encoded form.



Returns the binary digest for the message. Note that digest is a destructive operation, in that the Digest object is reset so it can be used to create another value.



Same as digest, but returns digest in hexadecimal form.

Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.