SHA-256

From Rosetta Code
Revision as of 09:20, 2 November 2012 by Grondilu (talk | contribs) (adding SHA-256 task)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Task
SHA-256
You are encouraged to solve this task according to the task description, using any language you may know.

SHA-256 is the recommended stronger alternative to SHA-1.

Implement the algorithm in your language and show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf

Perl 6

<lang Perl 6> say .list».fmt("%02x").join given sha256 "Rosetta code";

constant K = init * **(1/3), 64; sub init(&f, $n) {

   map { (($_ - .Int)*2**32).Int },
   map &f, (grep *.is-prime, 2 .. *)[^$n]

}

sub infix:<m+> { ($^a + $^b) % 2**32 } sub rotr($n, $b) { $n +> $b +| $n +< (32 - $b) }

proto sha256($) returns Buf {*} multi sha256(Str $s) { sha256 Buf.new: $s.ords } multi sha256(Buf $data) {

   my $l = 8 * my @b = $data.list;
   push @b, 0x80; push @b, 0 until (8*@b-448) %% 512;
   push @b, reverse gather for ^8 { take $l%256; $l div=256 }
   my @word = gather for @b -> $a, $b, $c, $d {

take reduce * *256 + *, $a, $b, $c, $d;

   }
   my @H = init &sqrt, 8;
   my @w;
   loop (my $i = 0; $i < @word.elems; $i += 16) {

my @h = @H; loop (my int $j = 0; $j < 64; $j = $j + 1) { @w[$j] = $j < 16 ?? @word[$j + $i] // 0 !! [m+] rotr(@w[$j-15], 7) +^ rotr(@w[$j-15], 18) +^ @w[$j-15] +> 3, @w[$j-7], rotr(@w[$j-2], 17) +^ rotr(@w[$j-2], 19) +^ @w[$j-2] +> 10, @w[$j-16]; my $ch = @h[4] +& @h[5] +^ +^@h[4] % 2**32 +& @h[6]; my $maj = @h[0] +& @h[2] +^ @h[0] +& @h[1] +^ @h[1] +& @h[2]; my $σ0 = [+^] map { rotr @h[0], $_ }, 2, 13, 22; my $σ1 = [+^] map { rotr @h[4], $_ }, 6, 11, 25; my $t1 = [m+] @h[7], $σ1, $ch, K[$j], @w[$j]; my $t2 = $σ0 m+ $maj; @h = $t1 m+ $t2, @h[^3], @h[3] m+ $t1, @h[4..6]; } @H = @H Z[m+] @h;

   }
   return Buf.new: map -> $word is rw {

reverse gather for ^4 { take $word % 256; $word div= 256 }

   }, @H;

} </lang>

Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf