daily pastebin goal
56%
SHARE
TWEET

SHA-256

a guest Dec 15th, 2017 72 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. say sha256 "Rosetta code";
  2.  
  3. sub init(&f) {
  4.     map { my $f = $^p.&f; (($f - $f.Int)*2**32).Int },
  5.     state @ = grep *.is-prime, 2 .. *;
  6. }
  7.  
  8. sub infix:<m+> { ($^a + $^b) % 2**32 }
  9. sub rotr($n, $b) { $n +> $b +| $n +< (32 - $b) }
  10.  
  11. proto sha256($) returns Blob {*}
  12. multi sha256(Str $str where all($str.ords) < 128) {
  13.     sha256 $str.encode: 'ascii'
  14. }
  15. multi sha256(Blob $data) {
  16.     constant K = init(* **(1/3))[^64];
  17.     my @b = flat $data.list, 0x80;
  18.     push @b, 0 until (8 * @b - 448) %% 512;
  19.     push @b, slip reverse (8 * $data).polymod(256 xx 7);
  20.     my @word = :256[@b.shift xx 4] xx @b/4;
  21.  
  22.     my @H = init(&sqrt)[^8];
  23.     my @w;
  24.     loop (my $i = 0; $i < @word; $i += 16) {
  25.         my @h = @H;
  26.         for ^64 -> $j {
  27.             @w[$j] = $j < 16 ?? @word[$j + $i] // 0 !!
  28.             [m+]
  29.             rotr(@w[$j-15], 7) +^ rotr(@w[$j-15], 18) +^ @w[$j-15] +> 3,
  30.             @w[$j-7],
  31.             rotr(@w[$j-2], 17) +^ rotr(@w[$j-2], 19)  +^ @w[$j-2] +> 10,
  32.             @w[$j-16];
  33.             my $ch = @h[4] +& @h[5] +^ +^@h[4] % 2**32 +& @h[6];
  34.             my $maj = @h[0] +& @h[2] +^ @h[0] +& @h[1] +^ @h[1] +& @h[2];
  35.             my0 = [+^] map { rotr @h[0], $_ }, 2, 13, 22;
  36.             my1 = [+^] map { rotr @h[4], $_ }, 6, 11, 25;
  37.             my $t1 = [m+] @h[7],1, $ch, K[$j], @w[$j];
  38.             my $t2 =0 m+ $maj;
  39.             @h = flat $t1 m+ $t2, @h[^3], @h[3] m+ $t1, @h[4..6];
  40.         }
  41.         @H [Z[m+]]= @h;
  42.     }
  43.     return Blob.new: map { |reverse .polymod(256 xx 3) }, @H;
  44. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top