SHA-256: Difference between revisions

Content added Content deleted
(→‎{{header|Perl 6}}: style: having &init return a lazy list as well)
Line 169: Line 169:
<lang Perl 6>say .list».fmt("%02x").join given sha256 "Rosetta code";
<lang Perl 6>say .list».fmt("%02x").join given sha256 "Rosetta code";


constant primes = grep &is-prime, 2 .. *;
constant primes = grep *.is-prime, 2 .. *;
sub init(&f) {
sub init(&f, $n) { map { (($_ - .Int)*2**32).Int }, map &f, primes[^$n] }
map { my $f = $^p.&f; (($f - $f.Int)*2**32).Int }, primes
}


sub infix:<m+> { ($^a + $^b) % 2**32 }
sub infix:<m+> { ($^a + $^b) % 2**32 }
Line 180: Line 182:
}
}
multi sha256(Buf $data) {
multi sha256(Buf $data) {
my \K = init * **(1/3), 64;
my \K = init(* **(1/3))[^64];
my $l = 8 * my @b = $data.list;
my $l = 8 * my @b = $data.list;
push @b, 0x80; push @b, 0 until (8*@b-448) %% 512;
push @b, 0x80; push @b, 0 until (8*@b-448) %% 512;
Line 186: Line 188:
push @b, reverse gather for ^8 { take $l%256; $l div=256 }
push @b, reverse gather for ^8 { take $l%256; $l div=256 }
my @word = gather for @b -> $a, $b, $c, $d {
my @word = gather for @b -> $a, $b, $c, $d {
take reduce * *256 + *, $a, $b, $c, $d;
take reduce * *256 + *, $a, $b, $c, $d;
}
}


my @H = init &sqrt, 8;
my @H = init(&sqrt)[^8];
my @w;
my @w;
loop (my $i = 0; $i < @word.elems; $i += 16) {
loop (my $i = 0; $i < @word.elems; $i += 16) {
my @h = @H;
my @h = @H;
for ^64 -> $j {
for ^64 -> $j {
@w[$j] = $j < 16 ?? @word[$j + $i] // 0 !!
@w[$j] = $j < 16 ?? @word[$j + $i] // 0 !!
[m+]
[m+]
rotr(@w[$j-15], 7) +^ rotr(@w[$j-15], 18) +^ @w[$j-15] +> 3,
rotr(@w[$j-15], 7) +^ rotr(@w[$j-15], 18) +^ @w[$j-15] +> 3,
@w[$j-7],
@w[$j-7],
rotr(@w[$j-2], 17) +^ rotr(@w[$j-2], 19) +^ @w[$j-2] +> 10,
rotr(@w[$j-2], 17) +^ rotr(@w[$j-2], 19) +^ @w[$j-2] +> 10,
@w[$j-16];
@w[$j-16];
my $ch = @h[4] +& @h[5] +^ +^@h[4] % 2**32 +& @h[6];
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 $maj = @h[0] +& @h[2] +^ @h[0] +& @h[1] +^ @h[1] +& @h[2];
my $σ0 = [+^] map { rotr @h[0], $_ }, 2, 13, 22;
my $σ0 = [+^] map { rotr @h[0], $_ }, 2, 13, 22;
my $σ1 = [+^] map { rotr @h[4], $_ }, 6, 11, 25;
my $σ1 = [+^] map { rotr @h[4], $_ }, 6, 11, 25;
my $t1 = [m+] @h[7], $σ1, $ch, K[$j], @w[$j];
my $t1 = [m+] @h[7], $σ1, $ch, K[$j], @w[$j];
my $t2 = $σ0 m+ $maj;
my $t2 = $σ0 m+ $maj;
@h = $t1 m+ $t2, @h[^3], @h[3] m+ $t1, @h[4..6];
@h = $t1 m+ $t2, @h[^3], @h[3] m+ $t1, @h[4..6];
}
}
@H = @H Z[m+] @h;
@H = @H Z[m+] @h;
}
}
return Buf.new: map -> $word is rw {
return Buf.new: map -> $word is rw {
reverse gather for ^4 { take $word % 256; $word div= 256 }
reverse gather for ^4 { take $word % 256; $word div= 256 }
}, @H;
}, @H;
}</lang>
}</lang>