-
-
Save monga/2bcf6ca865ce80a118bb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// returns padding bits (in hex) given a bit length | |
function hexpadding(len){ | |
var blen = len.toString(2); | |
len = len % 512; | |
var p='1'; | |
while (p.length + len < 512-64) p += '0'; | |
while (p.length + len < 512-blen.length) p += '0'; | |
p += blen; | |
assert(p.length + len == 512, "Padding errato: " + (p.length+len)); | |
var t = ''; | |
for (var i=0; i<=p.length-4; i += 4){ | |
t += parseInt(p.slice(i,i+4),2).toString(16); | |
} | |
return t; | |
} | |
// RFC 3174, Section 5 | |
function nist_f(t, B, C, D){ | |
if (0 <= t && t <= 19) return (B & C) | (~B & D); | |
if (20 <= t && t <= 39) return B ^ C ^ D; | |
if (40 <= t && t <= 59) return (B & C) | (B & D) | (C & D); | |
if (60 <= t && t <= 79) return B ^ C ^ D; | |
return undefined; | |
} | |
// RFC 3174, Section 5 | |
function nist_K(t){ | |
if (0 <= t && t <= 19) return 0x5A827999; | |
if (20 <= t && t <= 39) return 0x6ED9EBA1; | |
if (40 <= t && t <= 59) return 0x8F1BBCDC; | |
if (60 <= t && t <= 79) return 0xCA62C1D6; | |
return undefined; | |
} | |
function add_mod32(x, y){ | |
return (x+y) % Math.pow(2,32); | |
} | |
// Circular shift: complex due to Javascript number representation | |
// (always 64bit floats) | |
function nist_cshift(n, X){ | |
return ((X << n) | (X >>> (32-n))) >>> 0; | |
} | |
// SHA-1 of a 512 padded bit block | |
function sha1(M, H0, H1, H2, H3, H4) | |
{ | |
assert(M.length == 512, "Blocco di dimensione errata " + M.length); | |
var W = Array(80); | |
var j = 0; | |
for (var i=0; i<16; i++){ | |
W[i] = parseInt(M.slice(j, j+32),2); | |
j += 32; | |
} | |
for (var t=16; t<=79; t++){ | |
W[t] = nist_cshift(1, W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16]); | |
} | |
var A=H0; | |
var B=H1; | |
var C=H2; | |
var D=H3; | |
var E=H4; | |
for (t=0; t<=79; t++){ | |
var tmp = nist_cshift(5, A) + nist_f(t,B,C,D) + E + W[t] + nist_K(t); | |
E = D; | |
D = C; | |
C = nist_cshift(30, B); | |
B = A; | |
A = tmp; | |
} | |
return Array(add_mod32(H0,A), | |
add_mod32(H1,B), | |
add_mod32(H2,C), | |
add_mod32(H3,D), | |
add_mod32(H4,E)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Very simple implementation of SHA-1 core computation: it follows RFC 3174 step by step.