Cryptography Tutorials - Herong's Tutorial Notes
Dr. Herong Yang, Version 4.00

Message Digest - MD5 Algorithm

Part:   1  2  3  4  5 

(Continued from previous part...)

MD5 Implementation in Perl

If you are interested in using MD5 in Perl, you can look a very interesting implementation by John Allen in 8 lines of perl5, 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)
<<($n=pop)|2**$n-1&$x>>32-$n}sub M{($x=pop)-($m=1+~0)*int$x/$m}do{$l+=$r=read
STDIN,$_,64;$r++,$_.="\x80"if$r<64&&!$p++;@W=unpack V16,$_."\0"x7;$W[14]=$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:

>copy con empty.txt
^Z
        1 file(s) copied.

>perl PerlMd5In8Lines.pl < empty.txt
d41d8cd98f00b204e9800998ecf8427e

>copy con abc.txt
abc^Z
        1 file(s) copied.

>perl PerlMd5In8Lines.pl < abc.txt
900150983cd24fb0d6963f7d28e17f72

>copy con a_to_z.txt
abcdefghijklmnopqrstuvwxyz^Z
        1 file(s) copied.

>perl PerlMd5In8Lines.pl < a_to_z.txt
c3fcd3d76192e4007dfb496cca67e13b

The output proves that John's program works perfectly. Note that:

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

Conclusions:

  • MD5 is a message digest algorithm producing 128 bits of data.
  • It uses constants derived to Sines function.
  • It loops through the original message in blocks of 512 bits, with 4 rounds of operations for each block, and 16 operations in each round.
  • Most modern programming languages provides MD5 algorithm as built-in functions.

Part:   1  2  3  4  5 

Dr. Herong Yang, updated in 2007
Cryptography Tutorials - Herong's Tutorial Notes - Message Digest - MD5 Algorithm