SHA-256: Difference between revisions

From Rosetta Code
Content added Content deleted
m (→‎{{header|Perl 6}}: correction)
(should be draft for now)
Line 1: Line 1:
{{task}}[[Category:Checksums]]
{{draft task}}[[Category:Checksums]]
'''SHA-256''' is the recommended stronger alternative to [[SHA-1]].
'''SHA-256''' is the recommended stronger alternative to [[SHA-1]].



Revision as of 04:07, 3 November 2012

SHA-256 is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

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

Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf

Perl 6

<lang Perl 6>say .list».fmt("%02x").join given SHA-256 "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) }

multi SHA-256(Str $s) { SHA-256 Buf.new: $s.ords } multi SHA-256(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; for ^64 -> $j {

           @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

Python

Python has a standard module for this: <lang python>>>> import hashlib >>> hashlib.sha256( "Rosetta code" ).hexdigest() '764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf' >>> </lang>