This commit is contained in:
Ingy döt Net 2013-10-27 22:24:23 +00:00
parent 6f050a029e
commit 776bba907c
3887 changed files with 59894 additions and 7280 deletions

View file

@ -9,7 +9,7 @@ my \f = -> \B,\C,\D { (B +& C) +| ((+^B)mod2³² +& D) },
my \K = 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6;
sub sha1-pad(Buf $msg)
sub sha1-pad(Blob $msg)
{
my \bits = 8 * $msg.elems;
my @padded = $msg.list, 0x80, 0x00 xx (-(bits div 8 + 1 + 8) % 64);
@ -29,7 +29,7 @@ sub sha1-block(@H is rw, @M)
@H «=» ($A,$B,$C,$D,$E);
}
sub sha1(Buf $msg)
sub sha1(Blob $msg)
{
my @M = sha1-pad($msg);
my @H = 0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0;
@ -37,7 +37,7 @@ sub sha1(Buf $msg)
@H;
}
say sha1($_.encode('ascii'))».base(16), " $_"
say sha1(.encode('ascii'))».base(16), " $_"
for 'abc',
'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq',
'Rosetta Code',

View file

@ -8,7 +8,7 @@ require 'stringio'
#++
def sha1(string)
# functions and constants
mask = (1 << 32) - 1
mask = (1 << 32) - 1 # ffffffff
s = proc{|n, x| ((x << n) & mask) | (x >> (32 - n))}
f = [
proc {|b, c, d| (b & c) | (b.^(mask) & d)},
@ -30,7 +30,7 @@ def sha1(string)
io.read(64, block) or (
# Work around a bug in Rubinius 1.2.4. At eof,
# MRI and JRuby already replace block with "".
block.replace("")
block.clear
)
# Unpack block into 32-bit words "N".
@ -58,22 +58,19 @@ def sha1(string)
end
# Process block.
(16..79).each {|t|
w[t] = s[1, w[t - 3] ^ w[t - 8] ^ w[t - 14] ^ w[t - 16]]}
(16..79).each {|t| w[t] = s[1, w[t-3] ^ w[t-8] ^ w[t-14] ^ w[t-16]]}
a, b, c, d, e = h[0..4]
a, b, c, d, e = h
t = 0
(0..3).each {|i|
20.times {
4.times do |i|
20.times do
temp = (s[5, a] + f[i][b, c, d] + e + w[t] + k[i]) & mask
e = d; d = c; c = s[30, b]; b = a; a = temp
t += 1}}
a, b, c, d, e = temp, a, s[30, b], c, d
t += 1
end
end
h[0] = (h[0] + a) & mask
h[1] = (h[1] + b) & mask
h[2] = (h[2] + c) & mask
h[3] = (h[3] + d) & mask
h[4] = (h[4] + e) & mask
[a,b,c,d,e].each_with_index {|x,i| h[i] = (h[i] + x) & mask}
end
h.pack("N5")
@ -82,11 +79,8 @@ end
if __FILE__ == $0
# Print some example SHA-1 digests.
# FIPS 180-1 has correct digests for 'abc' and 'abc...opq'.
[
'abc',
[ 'abc',
'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq',
'Rosetta Code',
].each {|s|
printf("%s:\n %s\n", s, *sha1(s).unpack('H*'))
}
].each {|s| printf("%s:\n %s\n", s, *sha1(s).unpack('H*'))}
end