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

Message Digest - SHA1 Algorithm

Part:   1  2  3  4 

(Continued from previous part...)

If you run this sample program with PHP 5, you should get:

SHA1("") =
   da39a3ee5e6b4b0d3255bfef95601890afd80709

SHA1("abc") =
   a9993e364706816aba3e25717850c26c9cd0d89d

SHA1("abcdefghijklmnopqrstuvwxyz") =
   32d10c7b8cf96570ca04ce37f2a19d84240d3a89

SHA1 Implementation in Perl

If you are interested in using SHA1 in Perl, you can look a very interesting implementation by John Allen in 8 lines of perl5, see http://www.cypherspace.org/adam/rsa/sha.html. Here is a copy of John's code, stored in PerlSha1In8Lines.pl:

#!/usr/bin/perl -iD9T4C`>_-JXF8NMS^$#)4=L/2X?!:@GF9;MGKH8\;O-S*8L'6
@A=unpack"N*",unpack u,$^I;@K=splice@A,5,4;sub M{($x=pop)-($m=1+~0)*int$x/$m};
sub L{$n=pop;($x=pop)<<$n|2**$n-1&$x>>32-$n}@F=(sub{$b&($c^$d)^$d},$S=sub{$b^$c
^$d},sub{($b|$c)&$d|$b&$c},$S);do{$l+=$r=read STDIN,$_,64;$r++,$_.="\x80"if$r<
64&&!$p++;@W=unpack N16,$_."\0"x7;$W[15]=$l*8 if$r<57;for(16..79){push@W,L$W[$_
-3]^$W[$_-8]^$W[$_-14]^$W[$_-16],1}($a,$b,$c,$d,$e)=@A;for(0..79){$t=M&{$F[$_/
20]}+$e+$W[$_]+$K[$_/20]+L$a,5;$e=$d;$d=$c;$c=L$b,30;$b=$a;$a=$t}$v='a';@A=map{
M$_+${$v++}}@A}while$r>56;printf'%.8x'x5 ."\n",@A

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 PerlSha1In8Lines.pl < empty.txt
da39a3ee5e6b4b0d3255bfef95601890afd80709

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

>perl PerlSha1In8Lines.pl < abc.txt
a9993e364706816aba3e25717850c26c9cd0d89d

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

>perl PerlSha1In8Lines.pl < a_to_z.txt
32d10c7b8cf96570ca04ce37f2a19d84240d3a89

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:

  • SHA1 is a message digest algorithm producing 160 bits of data.
  • Most modern programming languages provides SHA1 algorithm as built-in functions.

Part:   1  2  3  4 

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