Skip to content

Instantly share code, notes, and snippets.

@nonkr
Created January 14, 2014 17:12
Show Gist options
  • Save nonkr/8421963 to your computer and use it in GitHub Desktop.
Save nonkr/8421963 to your computer and use it in GitHub Desktop.
SHA in 8 lines of perl5
#!/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
=cut
% echo -n abc | sha1
a9993e364706816aba3e25717850c26c9cd0d89d
output is in hex. (The SHA1 hash of string "abc" is one of the standard test vectors.) As expected the hash of a message differing by only one letter produces an entirely different hash:
% echo -n abd | sha
cb4cc28df0fdbe0ecf9d9662e294b118092a5735
=cut
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment