2 // discuss at: http://phpjs.org/functions/sha1/
3 // original by: Webtoolkit.info (http://www.webtoolkit.info/)
4 // improved by: Michael White (http://getsprink.com)
5 // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
6 // input by: Brett Zamir (http://brett-zamir.me)
7 // example 1: sha1('Kevin van Zonneveld');
8 // returns 1: '54916d2e62f65b3afa6e192e6a601cdbe5cb5897'
10 var rotate_left = function (n, s) {
11 var t4 = (n << s) | (n >>> (32 - s));
15 /*var lsb_hex = function (val) {
16 // Not in use; needed?
22 for ( i=0; i<=6; i+=2 ) {
23 vh = (val>>>(i*4+4))&0x0f;
24 vl = (val>>>(i*4))&0x0f;
25 str += vh.toString(16) + vl.toString(16);
30 var cvt_hex = function (val) {
35 for (i = 7; i >= 0; i--) {
36 v = (val >>> (i * 4)) & 0x0f;
37 str += v.toString(16);
44 var W = new Array(80);
54 str = unescape(encodeURIComponent(str));
55 var str_len = str.length;
58 for (i = 0; i < str_len - 3; i += 4) {
59 j = str.charCodeAt(i) << 24 | str.charCodeAt(i + 1) << 16 | str.charCodeAt(i + 2) << 8 | str.charCodeAt(i + 3);
63 switch (str_len % 4) {
68 i = str.charCodeAt(str_len - 1) << 24 | 0x0800000;
71 i = str.charCodeAt(str_len - 2) << 24 | str.charCodeAt(str_len - 1) << 16 | 0x08000;
74 i = str.charCodeAt(str_len - 3) << 24 | str.charCodeAt(str_len - 2) << 16 | str.charCodeAt(str_len - 1) <<
81 while ((word_array.length % 16) != 14) {
85 word_array.push(str_len >>> 29);
86 word_array.push((str_len << 3) & 0x0ffffffff);
88 for (blockstart = 0; blockstart < word_array.length; blockstart += 16) {
89 for (i = 0; i < 16; i++) {
90 W[i] = word_array[blockstart + i];
92 for (i = 16; i <= 79; i++) {
93 W[i] = rotate_left(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1);
102 for (i = 0; i <= 19; i++) {
103 temp = (rotate_left(A, 5) + ((B & C) | (~B & D)) + E + W[i] + 0x5A827999) & 0x0ffffffff;
106 C = rotate_left(B, 30);
111 for (i = 20; i <= 39; i++) {
112 temp = (rotate_left(A, 5) + (B ^ C ^ D) + E + W[i] + 0x6ED9EBA1) & 0x0ffffffff;
115 C = rotate_left(B, 30);
120 for (i = 40; i <= 59; i++) {
121 temp = (rotate_left(A, 5) + ((B & C) | (B & D) | (C & D)) + E + W[i] + 0x8F1BBCDC) & 0x0ffffffff;
124 C = rotate_left(B, 30);
129 for (i = 60; i <= 79; i++) {
130 temp = (rotate_left(A, 5) + (B ^ C ^ D) + E + W[i] + 0xCA62C1D6) & 0x0ffffffff;
133 C = rotate_left(B, 30);
138 H0 = (H0 + A) & 0x0ffffffff;
139 H1 = (H1 + B) & 0x0ffffffff;
140 H2 = (H2 + C) & 0x0ffffffff;
141 H3 = (H3 + D) & 0x0ffffffff;
142 H4 = (H4 + E) & 0x0ffffffff;
145 temp = cvt_hex(H0) + cvt_hex(H1) + cvt_hex(H2) + cvt_hex(H3) + cvt_hex(H4);
146 return temp.toLowerCase();