Using MD5 Message Digest in Perl

This section provides a tutorial example on how to use MD5 message digest algorithm in Perl. John Allen implemented the entire MD5 algorithm in 8 lines of Perl 5 code.

If you are interested in using MD5 in Perl, you can look a very interesting implementation by John Allen in 8 lines of Perl 5, see http://www.cypherspace.org/adam/rsa/md5.html.

Here is a copy of John's code, stored in PerlMd5In8Lines.pl:

```#!/usr/bin/perl -iH9T4C`>_-JXF8NMS^\$#)4=@<,\$18%"0X4!`L0%P8*#Q4``04``04#!P``
@A=unpack N4C24,unpack u,\$^I;@K=map{int abs 2**32*sin\$_}1..64;sub L{(\$x=pop)
STDIN,\$_,64;\$r++,\$_.="\x80"if\$r<64&&!\$p++;@W=unpack V16,\$_."\0"x7;\$W=\$l*8
if\$r<57;(\$a,\$b,\$c,\$d)=@A;for(0..63){\$a=M\$b+L\$A[4+4*(\$_>>4)+\$_%4],M&{(sub{\$b&\$c
|\$d&~\$b},sub{\$b&\$d|\$c&~\$d},sub{\$b^\$c^\$d},sub{\$c^(\$b|~\$d)})[\$z=\$_/16]}+\$W[(\$A[
20+\$z]+\$A[24+\$z]*(\$_%16))%16]+\$K[\$_]+\$a;(\$a,\$b,\$c,\$d)=(\$d,\$a,\$b,\$c)}\$v=a;for(
@A[0..3]){\$_=M\$_+\${\$v++}}}while\$r>56;print unpack(H32,pack V4,@A),"\n"
```

To test this Perl program on Windows, I did the following in a command window:

```C:\herong>copy con empty.txt
^Z
1 file(s) copied.

C:\herong>perl PerlMd5In8Lines.pl < empty.txt
d41d8cd98f00b204e9800998ecf8427e

C:\herong>copy con abc.txt
abc^Z
1 file(s) copied.

C:\herong>perl PerlMd5In8Lines.pl < abc.txt
900150983cd24fb0d6963f7d28e17f72

C:\herong>copy con a_to_z.txt
abcdefghijklmnopqrstuvwxyz^Z
1 file(s) copied.

C:\herong>perl PerlMd5In8Lines.pl < a_to_z.txt
c3fcd3d76192e4007dfb496cca67e13b
```

The output matches the testing result listed in RFC 1321. This proves that John's program works perfectly. Note that:

• "copy con file_name" command allows me to enter data from keyboard into a new file.
• ^Z stands for (Ctrl-Z). It sends an end-of-file signal to the "copy" command.