Jump to content

MD5/Implementation: Difference between revisions

→‎{{header|Raku}}: create proto and put all subs in the main candidate
(→‎{{header|Raku}}: put tests in a CHECK block)
(→‎{{header|Raku}}: create proto and put all subs in the main candidate)
Line 4,697:
(formerly Perl 6)
{{works with|rakudo|2022-07}}
<syntaxhighlight lang="raku" line>subproto rotlmd5(uint32 $a, UInt $n --> uint32blob8) { ($a +< $n) +| ($a +> (32-$n)) *}
multi md5(Str $str) { samewith $str.encode }
submulti md5(Blob $msg) --> blob8){
constant FGHI = { ($^a +& $^b) +| (+^$a +& $^c) },
sub rotl(uint32 $a, UInt $n --> uint32) { ($^a +&< $^cn) +| ($^ba +&> +^(32-$cn)) },
 
{ $^a +^ $^b +^ $^c },
constant FGHI = { ($^ba +^& ($^ab) +| (+^$a +& $^c) };,
constant FGHI = { ($^a +& $^bc) +| (+$^$ab +& $+^$c) },
constant @S = flat{ < 7$^a 12+^ 17$^b 22+^ 5$^c 9 14 20 4 11 16 23 6 10 15 21 >.rotor(4) X[xx] 4;},
constant { $T^b =+^ (floor(abs(sin($_^a +| 1)+^$^c) * 2**32) for ^64) };
constant @k = flat ( $_ for ^16),
((5*$_ + 1) % 16 for ^16),
((3*$_ + 5) % 16 for ^16),
((7*$_ ) % 16 for ^16);
sub little-endian($w, $n, *@v) { (@v X+> flat ($w X* ^$n)) X% (2 ** $w) }
 
constant @S = flat < 7 12 17 22 5 9 14 20 4 11 16 23 6 10 15 21 >.rotor(4) X[xx] 4;
sub md5-pad(blob8 $msg)
constant @T = ^64 .map: { floor(abs(sin($_ + 1)) * 2**32) }
{
constant @k = flat ( $_ for ^16),
((5*$_ + 1) % 16 for ^16),
((3*$_ + 5) % 16 for ^16),
((7*$_ ) % 16 for ^16);
 
sub little-endian($w, $n, *@v) { (@v X+> flat ($w X* ^$n)) X% (2 ** $w) }
 
sub md5-pad(blob8 $msg)
{
my $bits = 8 * $msg.elems;
(
(flat $msg.list, 0x80, 0x00 xx -($bits div 8 + 1 + 8) % 64)
.map({ :256[$^d,$^c,$^b,$^a] }),
little-endian(32, 2, $bits)
).flat
.rotor(16)
.map({ blob32.new: @$_ })
}
 
sub md5-block(blob32 $H where $H == 4, blob32 $X where $X == 16)
{
blob32.new: $H[] Z+
reduce -> blob32 $b, $i {
blob32.new:
$b[3],
($b[1] + rotl($b[0] + FGHI[$i div 16](|$b[1,2,3]) + $@T[$i] + $X[@k[$i]], @S[$i])),
$b[1],
$b[2]
}, $H, |^64;
}
 
blob8.new: little-endian 8, 4, |
sub md5(Blob $msg --> blob8)
{
blob8.new: little-endian 8, 4, |
reduce &md5-block,
(constant $ = blob32.new: 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476),
|md5-pad $msg;
}
Line 4,757 ⟶ 4,758:
'57edf4a22be3c955ac49da2e2107b67a', '12345678901234567890123456789012345678901234567890123456789012345678901234567890'
-> $expected, $msg {
my $digest = md5($msg.encode).list».fmt('%02x').join;
is($digest, $expected, "$digest is MD5 digest of '$msg'");
}
1,934

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.