Book HomeJava and XSLTSearch this book

8.58. Digest::MD5

The Digest::MD5 module allows simpler creation of MD5 hashes. MD5 takes as input a message of arbitrary length and creates a 128-bit fingerprint, or digest, of the input. Like the Digest module, Digest::MD5 implements both a functional and object-oriented interface, which offer the same benefits. Digest::MD5 also outputs binary (16 bytes long), hexadecimal (32 characters long), and base64 (22 characters long) data.

To rewrite the example in Section 8.57, "Digest":

#!/usr/local/bin/perl -w
# Yes, functional interface
use Digest::MD5 qw(md5_hex);

my $text = `Be the ball, Danny!';
my $hexed = md5_hex($text);
 
print "The sum of \$text is [$hexed].\n";

You can use the object-oriented interface like so:

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

$md5->add($text);
 
my $sum = $md5->hexdigest;
print "The sum of \$text is [$sum].\n";

Digest::MD5 implements (and exports) the following functions.

new

new()

Constructor. Returns a new Digest::MD5 object. You can add data to $object and retrieve the digest itself. If you can new more than once, it will reset the existing digest and create a new Digest::MD5 object.

reset

reset()

An alias for new.

add

add(data, ...)

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

open(FILE, ...) or ...
while (<FILE>) {
    $md5->add($_);
} close(FILE);
addfile

addfile(io_handle)

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

open(FILE, $file) or ...
print Digest::MD5->new->addfile(*FILE)->hexdigest, " $file\n";
close(FILE);
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.

The following functions are implemented by the functional interface.

md5

md5(data, ...) 

Calculates the MD5 digest of data and returns it in binary form.

md5_base64

md5_base64(data,...)

Same as md5, but returns the digest as a base64-encoded string.

md5_hex

md5_hex(data,...)

Same as md5, but returns the digest in hexadecimal form.



Library Navigation Links

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