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; $md5->add($text); 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.
reset |
reset()
Alias for new.
add |
add(data, ...)
Appends data to the message for which you calculate the digest. add returns the Digest object itself.
addfile |
addfile(io_handle)
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.
b64digest |
b64digest()
Same as digest, but returns the digest in base64-encoded form.
digest |
digest()
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.
hexdigest |
hexdigest()
Same as digest, but returns digest in hexadecimal form.
Copyright © 2002 O'Reilly & Associates. All rights reserved.