[JavaScript] JavaScript SHA-256加密算法详细代码 →→→→→进入此内容的聊天室

来自 , 2020-01-03, 写在 JavaScript, 查看 166 次.
URL http://www.code666.cn/view/7caf5e22
  1. /*
  2.  * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
  3.  * in FIPS 180-2
  4.  * Version 2.2 Copyright Angel Marin, Paul Johnston 2000 - 2009.
  5.  * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
  6.  * Distributed under the BSD License
  7.  * See http://pajhome.org.uk/crypt/md5 for details.
  8.  * Also http://anmar.eu.org/projects/jssha2/
  9.  */
  10.  
  11. /*
  12.  * Configurable variables. You may need to tweak these to be compatible with
  13.  * the server-side, but the defaults work in most cases.
  14.  */
  15. var hexcase = 0;  /* hex output format. 0 - lowercase; 1 - uppercase        */
  16. var b64pad  = ""; /* base-64 pad character. "=" for strict RFC compliance   */
  17.  
  18. /*
  19.  * These are the functions you'll usually want to call
  20.  * They take string arguments and return either hex or base-64 encoded strings
  21.  */
  22. function hex_sha256(s)    { return rstr2hex(rstr_sha256(str2rstr_utf8(s))); }
  23. function b64_sha256(s)    { return rstr2b64(rstr_sha256(str2rstr_utf8(s))); }
  24. function any_sha256(s, e) { return rstr2any(rstr_sha256(str2rstr_utf8(s)), e); }
  25. function hex_hmac_sha256(k, d)
  26.   { return rstr2hex(rstr_hmac_sha256(str2rstr_utf8(k), str2rstr_utf8(d))); }
  27. function b64_hmac_sha256(k, d)
  28.   { return rstr2b64(rstr_hmac_sha256(str2rstr_utf8(k), str2rstr_utf8(d))); }
  29. function any_hmac_sha256(k, d, e)
  30.   { return rstr2any(rstr_hmac_sha256(str2rstr_utf8(k), str2rstr_utf8(d)), e); }
  31.  
  32. /*
  33.  * Perform a simple self-test to see if the VM is working
  34.  */
  35. function sha256_vm_test()
  36. {
  37.   return hex_sha256("abc").toLowerCase() ==
  38.             "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";
  39. }
  40.  
  41. /*
  42.  * Calculate the sha256 of a raw string
  43.  */
  44. function rstr_sha256(s)
  45. {
  46.   return binb2rstr(binb_sha256(rstr2binb(s), s.length * 8));
  47. }
  48.  
  49. /*
  50.  * Calculate the HMAC-sha256 of a key and some data (raw strings)
  51.  */
  52. function rstr_hmac_sha256(key, data)
  53. {
  54.   var bkey = rstr2binb(key);
  55.   if(bkey.length > 16) bkey = binb_sha256(bkey, key.length * 8);
  56.  
  57.   var ipad = Array(16), opad = Array(16);
  58.   for(var i = 0; i < 16; i++)
  59.   {
  60.     ipad[i] = bkey[i] ^ 0x36363636;
  61.     opad[i] = bkey[i] ^ 0x5C5C5C5C;
  62.   }
  63.  
  64.   var hash = binb_sha256(ipad.concat(rstr2binb(data)), 512 + data.length * 8);
  65.   return binb2rstr(binb_sha256(opad.concat(hash), 512 + 256));
  66. }
  67.  
  68. /*
  69.  * Convert a raw string to a hex string
  70.  */
  71. function rstr2hex(input)
  72. {
  73.   try { hexcase } catch(e) { hexcase=0; }
  74.   var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
  75.   var output = "";
  76.   var x;
  77.   for(var i = 0; i < input.length; i++)
  78.   {
  79.     x = input.charCodeAt(i);
  80.     output += hex_tab.charAt((x >>> 4) & 0x0F)
  81.            +  hex_tab.charAt( x        & 0x0F);
  82.   }
  83.   return output;
  84. }
  85.  
  86. /*
  87.  * Convert a raw string to a base-64 string
  88.  */
  89. function rstr2b64(input)
  90. {
  91.   try { b64pad } catch(e) { b64pad=''; }
  92.   var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  93.   var output = "";
  94.   var len = input.length;
  95.   for(var i = 0; i < len; i += 3)
  96.   {
  97.     var triplet = (input.charCodeAt(i) << 16)
  98.                 | (i + 1 < len ? input.charCodeAt(i+1) << 8 : 0)
  99.                 | (i + 2 < len ? input.charCodeAt(i+2)      : 0);
  100.     for(var j = 0; j < 4; j++)
  101.     {
  102.       if(i * 8 + j * 6 > input.length * 8) output += b64pad;
  103.       else output += tab.charAt((triplet >>> 6*(3-j)) & 0x3F);
  104.     }
  105.   }
  106.   return output;
  107. }
  108.  
  109. /*
  110.  * Convert a raw string to an arbitrary string encoding
  111.  */
  112. function rstr2any(input, encoding)
  113. {
  114.   var divisor = encoding.length;
  115.   var remainders = Array();
  116.   var i, q, x, quotient;
  117.  
  118.   /* Convert to an array of 16-bit big-endian values, forming the dividend */
  119.   var dividend = Array(Math.ceil(input.length / 2));
  120.   for(i = 0; i < dividend.length; i++)
  121.   {
  122.     dividend[i] = (input.charCodeAt(i * 2) << 8) | input.charCodeAt(i * 2 + 1);
  123.   }
  124.  
  125.   /*
  126.    * Repeatedly perform a long division. The binary array forms the dividend,
  127.    * the length of the encoding is the divisor. Once computed, the quotient
  128.    * forms the dividend for the next step. We stop when the dividend is zero.
  129.    * All remainders are stored for later use.
  130.    */
  131.   while(dividend.length > 0)
  132.   {
  133.     quotient = Array();
  134.     x = 0;
  135.     for(i = 0; i < dividend.length; i++)
  136.     {
  137.       x = (x << 16) + dividend[i];
  138.       q = Math.floor(x / divisor);
  139.       x -= q * divisor;
  140.       if(quotient.length > 0 || q > 0)
  141.         quotient[quotient.length] = q;
  142.     }
  143.     remainders[remainders.length] = x;
  144.     dividend = quotient;
  145.   }
  146.  
  147.   /* Convert the remainders to the output string */
  148.   var output = "";
  149.   for(i = remainders.length - 1; i >= 0; i--)
  150.     output += encoding.charAt(remainders[i]);
  151.  
  152.   /* Append leading zero equivalents */
  153.   var full_length = Math.ceil(input.length * 8 /
  154.                                     (Math.log(encoding.length) / Math.log(2)))
  155.   for(i = output.length; i < full_length; i++)
  156.     output = encoding[0] + output;
  157.  
  158.   return output;
  159. }
  160.  
  161. /*
  162.  * Encode a string as utf-8.
  163.  * For efficiency, this assumes the input is valid utf-16.
  164.  */
  165. function str2rstr_utf8(input)
  166. {
  167.   var output = "";
  168.   var i = -1;
  169.   var x, y;
  170.  
  171.   while(++i < input.length)
  172.   {
  173.     /* Decode utf-16 surrogate pairs */
  174.     x = input.charCodeAt(i);
  175.     y = i + 1 < input.length ? input.charCodeAt(i + 1) : 0;
  176.     if(0xD800 <= x && x <= 0xDBFF && 0xDC00 <= y && y <= 0xDFFF)
  177.     {
  178.       x = 0x10000 + ((x & 0x03FF) << 10) + (y & 0x03FF);
  179.       i++;
  180.     }
  181.  
  182.     /* Encode output as utf-8 */
  183.     if(x <= 0x7F)
  184.       output += String.fromCharCode(x);
  185.     else if(x <= 0x7FF)
  186.       output += String.fromCharCode(0xC0 | ((x >>> 6 ) & 0x1F),
  187.                                     0x80 | ( x         & 0x3F));
  188.     else if(x <= 0xFFFF)
  189.       output += String.fromCharCode(0xE0 | ((x >>> 12) & 0x0F),
  190.                                     0x80 | ((x >>> 6 ) & 0x3F),
  191.                                     0x80 | ( x         & 0x3F));
  192.     else if(x <= 0x1FFFFF)
  193.       output += String.fromCharCode(0xF0 | ((x >>> 18) & 0x07),
  194.                                     0x80 | ((x >>> 12) & 0x3F),
  195.                                     0x80 | ((x >>> 6 ) & 0x3F),
  196.                                     0x80 | ( x         & 0x3F));
  197.   }
  198.   return output;
  199. }
  200.  
  201. /*
  202.  * Encode a string as utf-16
  203.  */
  204. function str2rstr_utf16le(input)
  205. {
  206.   var output = "";
  207.   for(var i = 0; i < input.length; i++)
  208.     output += String.fromCharCode( input.charCodeAt(i)        & 0xFF,
  209.                                   (input.charCodeAt(i) >>> 8) & 0xFF);
  210.   return output;
  211. }
  212.  
  213. function str2rstr_utf16be(input)
  214. {
  215.   var output = "";
  216.   for(var i = 0; i < input.length; i++)
  217.     output += String.fromCharCode((input.charCodeAt(i) >>> 8) & 0xFF,
  218.                                    input.charCodeAt(i)        & 0xFF);
  219.   return output;
  220. }
  221.  
  222. /*
  223.  * Convert a raw string to an array of big-endian words
  224.  * Characters >255 have their high-byte silently ignored.
  225.  */
  226. function rstr2binb(input)
  227. {
  228.   var output = Array(input.length >> 2);
  229.   for(var i = 0; i < output.length; i++)
  230.     output[i] = 0;
  231.   for(var i = 0; i < input.length * 8; i += 8)
  232.     output[i>>5] |= (input.charCodeAt(i / 8) & 0xFF) << (24 - i % 32);
  233.   return output;
  234. }
  235.  
  236. /*
  237.  * Convert an array of big-endian words to a string
  238.  */
  239. function binb2rstr(input)
  240. {
  241.   var output = "";
  242.   for(var i = 0; i < input.length * 32; i += 8)
  243.     output += String.fromCharCode((input[i>>5] >>> (24 - i % 32)) & 0xFF);
  244.   return output;
  245. }
  246.  
  247. /*
  248.  * Main sha256 function, with its support functions
  249.  */
  250. function sha256_S (X, n) {return ( X >>> n ) | (X << (32 - n));}
  251. function sha256_R (X, n) {return ( X >>> n );}
  252. function sha256_Ch(x, y, z) {return ((x & y) ^ ((~x) & z));}
  253. function sha256_Maj(x, y, z) {return ((x & y) ^ (x & z) ^ (y & z));}
  254. function sha256_Sigma0256(x) {return (sha256_S(x, 2) ^ sha256_S(x, 13) ^ sha256_S(x, 22));}
  255. function sha256_Sigma1256(x) {return (sha256_S(x, 6) ^ sha256_S(x, 11) ^ sha256_S(x, 25));}
  256. function sha256_Gamma0256(x) {return (sha256_S(x, 7) ^ sha256_S(x, 18) ^ sha256_R(x, 3));}
  257. function sha256_Gamma1256(x) {return (sha256_S(x, 17) ^ sha256_S(x, 19) ^ sha256_R(x, 10));}
  258. function sha256_Sigma0512(x) {return (sha256_S(x, 28) ^ sha256_S(x, 34) ^ sha256_S(x, 39));}
  259. function sha256_Sigma1512(x) {return (sha256_S(x, 14) ^ sha256_S(x, 18) ^ sha256_S(x, 41));}
  260. function sha256_Gamma0512(x) {return (sha256_S(x, 1)  ^ sha256_S(x, 8) ^ sha256_R(x, 7));}
  261. function sha256_Gamma1512(x) {return (sha256_S(x, 19) ^ sha256_S(x, 61) ^ sha256_R(x, 6));}
  262.  
  263. var sha256_K = new Array
  264. (
  265.   1116352408, 1899447441, -1245643825, -373957723, 961987163, 1508970993,
  266.   -1841331548, -1424204075, -670586216, 310598401, 607225278, 1426881987,
  267.   1925078388, -2132889090, -1680079193, -1046744716, -459576895, -272742522,
  268.   264347078, 604807628, 770255983, 1249150122, 1555081692, 1996064986,
  269.   -1740746414, -1473132947, -1341970488, -1084653625, -958395405, -710438585,
  270.   113926993, 338241895, 666307205, 773529912, 1294757372, 1396182291,
  271.   1695183700, 1986661051, -2117940946, -1838011259, -1564481375, -1474664885,
  272.   -1035236496, -949202525, -778901479, -694614492, -200395387, 275423344,
  273.   430227734, 506948616, 659060556, 883997877, 958139571, 1322822218,
  274.   1537002063, 1747873779, 1955562222, 2024104815, -2067236844, -1933114872,
  275.   -1866530822, -1538233109, -1090935817, -965641998
  276. );
  277.  
  278. function binb_sha256(m, l)
  279. {
  280.   var HASH = new Array(1779033703, -1150833019, 1013904242, -1521486534,
  281.                        1359893119, -1694144372, 528734635, 1541459225);
  282.   var W = new Array(64);
  283.   var a, b, c, d, e, f, g, h;
  284.   var i, j, T1, T2;
  285.  
  286.   /* append padding */
  287.   m[l >> 5] |= 0x80 << (24 - l % 32);
  288.   m[((l + 64 >> 9) << 4) + 15] = l;
  289.  
  290.   for(i = 0; i < m.length; i += 16)
  291.   {
  292.     a = HASH[0];
  293.     b = HASH[1];
  294.     c = HASH[2];
  295.     d = HASH[3];
  296.     e = HASH[4];
  297.     f = HASH[5];
  298.     g = HASH[6];
  299.     h = HASH[7];
  300.  
  301.     for(j = 0; j < 64; j++)
  302.     {
  303.       if (j < 16) W[j] = m[j + i];
  304.       else W[j] = safe_add(safe_add(safe_add(sha256_Gamma1256(W[j - 2]), W[j - 7]),
  305.                                             sha256_Gamma0256(W[j - 15])), W[j - 16]);
  306.  
  307.       T1 = safe_add(safe_add(safe_add(safe_add(h, sha256_Sigma1256(e)), sha256_Ch(e, f, g)),
  308.                                                           sha256_K[j]), W[j]);
  309.       T2 = safe_add(sha256_Sigma0256(a), sha256_Maj(a, b, c));
  310.       h = g;
  311.       g = f;
  312.       f = e;
  313.       e = safe_add(d, T1);
  314.       d = c;
  315.       c = b;
  316.       b = a;
  317.       a = safe_add(T1, T2);
  318.     }
  319.  
  320.     HASH[0] = safe_add(a, HASH[0]);
  321.     HASH[1] = safe_add(b, HASH[1]);
  322.     HASH[2] = safe_add(c, HASH[2]);
  323.     HASH[3] = safe_add(d, HASH[3]);
  324.     HASH[4] = safe_add(e, HASH[4]);
  325.     HASH[5] = safe_add(f, HASH[5]);
  326.     HASH[6] = safe_add(g, HASH[6]);
  327.     HASH[7] = safe_add(h, HASH[7]);
  328.   }
  329.   return HASH;
  330. }
  331.  
  332. function safe_add (x, y)
  333. {
  334.   var lsw = (x & 0xFFFF) + (y & 0xFFFF);
  335.   var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  336.   return (msw << 16) | (lsw & 0xFFFF);
  337. }
  338. //javascript/8903

回复 "JavaScript SHA-256加密算法详细代码"

这儿你可以回复上面这条便签

captcha