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

本文实例为大家分享了JavaScript SHA-256加密算法,供大家参考,具体内容如下

/*
 * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
 * in FIPS 180-2
 * Version 2.2 Copyright Angel Marin, Paul Johnston 2000 - 2009.
 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
 * Distributed under the BSD License
 * See http://pajhome.org.uk/crypt/md5 for details.
 * Also http://anmar.eu.org/projects/jssha2/
 */

/*
 * Configurable variables. You may need to tweak these to be compatible with
 * the server-side, but the defaults work in most cases.
 */
var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase    */
var b64pad = ""; /* base-64 pad character. "=" for strict RFC compliance  */

/*
 * These are the functions you'll usually want to call
 * They take string arguments and return either hex or base-64 encoded strings
 */
function hex_sha256(s)  { return rstr2hex(rstr_sha256(str2rstr_utf8(s))); }
function b64_sha256(s)  { return rstr2b64(rstr_sha256(str2rstr_utf8(s))); }
function any_sha256(s, e) { return rstr2any(rstr_sha256(str2rstr_utf8(s)), e); }
function hex_hmac_sha256(k, d)
 { return rstr2hex(rstr_hmac_sha256(str2rstr_utf8(k), str2rstr_utf8(d))); }
function b64_hmac_sha256(k, d)
 { return rstr2b64(rstr_hmac_sha256(str2rstr_utf8(k), str2rstr_utf8(d))); }
function any_hmac_sha256(k, d, e)
 { return rstr2any(rstr_hmac_sha256(str2rstr_utf8(k), str2rstr_utf8(d)), e); }

/*
 * Perform a simple self-test to see if the VM is working
 */
function sha256_vm_test()
{
 return hex_sha256("abc").toLowerCase() ==
      "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";
}

/*
 * Calculate the sha256 of a raw string
 */
function rstr_sha256(s)
{
 return binb2rstr(binb_sha256(rstr2binb(s), s.length * 8));
}

/*
 * Calculate the HMAC-sha256 of a key and some data (raw strings)
 */
function rstr_hmac_sha256(key, data)
{
 var bkey = rstr2binb(key);
 if(bkey.length > 16) bkey = binb_sha256(bkey, key.length * 8);

 var ipad = Array(16), opad = Array(16);
 for(var i = 0; i < 16; i++)
 {
  ipad[i] = bkey[i] ^ 0x36363636;
  opad[i] = bkey[i] ^ 0x5C5C5C5C;
 }

 var hash = binb_sha256(ipad.concat(rstr2binb(data)), 512 + data.length * 8);
 return binb2rstr(binb_sha256(opad.concat(hash), 512 + 256));
}

/*
 * Convert a raw string to a hex string
 */
function rstr2hex(input)
{
 try { hexcase } catch(e) { hexcase=0; }
 var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
 var output = "";
 var x;
 for(var i = 0; i < input.length; i++)
 {
  x = input.charCodeAt(i);
  output += hex_tab.charAt((x >>> 4) & 0x0F)
      + hex_tab.charAt( x    & 0x0F);
 }
 return output;
}

/*
 * Convert a raw string to a base-64 string
 */
function rstr2b64(input)
{
 try { b64pad } catch(e) { b64pad=''; }
 var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
 var output = "";
 var len = input.length;
 for(var i = 0; i < len; i += 3)
 {
  var triplet = (input.charCodeAt(i) << 16)
        | (i + 1 < len ? input.charCodeAt(i+1) << 8 : 0)
        | (i + 2 < len ? input.charCodeAt(i+2)   : 0);
  for(var j = 0; j < 4; j++)
  {
   if(i * 8 + j * 6 > input.length * 8) output += b64pad;
   else output += tab.charAt((triplet >>> 6*(3-j)) & 0x3F);
  }
 }
 return output;
}

/*
 * Convert a raw string to an arbitrary string encoding
 */
function rstr2any(input, encoding)
{
 var divisor = encoding.length;
 var remainders = Array();
 var i, q, x, quotient;

 /* Convert to an array of 16-bit big-endian values, forming the dividend */
 var dividend = Array(Math.ceil(input.length / 2));
 for(i = 0; i < dividend.length; i++)
 {
  dividend[i] = (input.charCodeAt(i * 2) << 8) | input.charCodeAt(i * 2 + 1);
 }

 /*
  * Repeatedly perform a long division. The binary array forms the dividend,
  * the length of the encoding is the divisor. Once computed, the quotient
  * forms the dividend for the next step. We stop when the dividend is zero.
  * All remainders are stored for later use.
  */
 while(dividend.length > 0)
 {
  quotient = Array();
  x = 0;
  for(i = 0; i < dividend.length; i++)
  {
   x = (x << 16) + dividend[i];
   q = Math.floor(x / divisor);
   x -= q * divisor;
   if(quotient.length > 0 || q > 0)
    quotient[quotient.length] = q;
  }
  remainders[remainders.length] = x;
  dividend = quotient;
 }

 /* Convert the remainders to the output string */
 var output = "";
 for(i = remainders.length - 1; i >= 0; i--)
  output += encoding.charAt(remainders[i]);

 /* Append leading zero equivalents */
 var full_length = Math.ceil(input.length * 8 /
                  (Math.log(encoding.length) / Math.log(2)))
 for(i = output.length; i < full_length; i++)
  output = encoding[0] + output;

 return output;
}

/*
 * Encode a string as utf-8.
 * For efficiency, this assumes the input is valid utf-16.
 */
function str2rstr_utf8(input)
{
 var output = "";
 var i = -1;
 var x, y;

 while(++i < input.length)
 {
  /* Decode utf-16 surrogate pairs */
  x = input.charCodeAt(i);
  y = i + 1 < input.length ? input.charCodeAt(i + 1) : 0;
  if(0xD800 <= x && x <= 0xDBFF && 0xDC00 <= y && y <= 0xDFFF)
  {
   x = 0x10000 + ((x & 0x03FF) << 10) + (y & 0x03FF);
   i++;
  }

  /* Encode output as utf-8 */
  if(x <= 0x7F)
   output += String.fromCharCode(x);
  else if(x <= 0x7FF)
   output += String.fromCharCode(0xC0 | ((x >>> 6 ) & 0x1F),
                  0x80 | ( x     & 0x3F));
  else if(x <= 0xFFFF)
   output += String.fromCharCode(0xE0 | ((x >>> 12) & 0x0F),
                  0x80 | ((x >>> 6 ) & 0x3F),
                  0x80 | ( x     & 0x3F));
  else if(x <= 0x1FFFFF)
   output += String.fromCharCode(0xF0 | ((x >>> 18) & 0x07),
                  0x80 | ((x >>> 12) & 0x3F),
                  0x80 | ((x >>> 6 ) & 0x3F),
                  0x80 | ( x     & 0x3F));
 }
 return output;
}

/*
 * Encode a string as utf-16
 */
function str2rstr_utf16le(input)
{
 var output = "";
 for(var i = 0; i < input.length; i++)
  output += String.fromCharCode( input.charCodeAt(i)    & 0xFF,
                 (input.charCodeAt(i) >>> 8) & 0xFF);
 return output;
}

function str2rstr_utf16be(input)
{
 var output = "";
 for(var i = 0; i < input.length; i++)
  output += String.fromCharCode((input.charCodeAt(i) >>> 8) & 0xFF,
                  input.charCodeAt(i)    & 0xFF);
 return output;
}

/*
 * Convert a raw string to an array of big-endian words
 * Characters >255 have their high-byte silently ignored.
 */
function rstr2binb(input)
{
 var output = Array(input.length >> 2);
 for(var i = 0; i < output.length; i++)
  output[i] = 0;
 for(var i = 0; i < input.length * 8; i += 8)
  output[i>>5] |= (input.charCodeAt(i / 8) & 0xFF) << (24 - i % 32);
 return output;
}

/*
 * Convert an array of big-endian words to a string
 */
function binb2rstr(input)
{
 var output = "";
 for(var i = 0; i < input.length * 32; i += 8)
  output += String.fromCharCode((input[i>>5] >>> (24 - i % 32)) & 0xFF);
 return output;
}

/*
 * Main sha256 function, with its support functions
 */
function sha256_S (X, n) {return ( X >>> n ) | (X << (32 - n));}
function sha256_R (X, n) {return ( X >>> n );}
function sha256_Ch(x, y, z) {return ((x & y) ^ ((~x) & z));}
function sha256_Maj(x, y, z) {return ((x & y) ^ (x & z) ^ (y & z));}
function sha256_Sigma0256(x) {return (sha256_S(x, 2) ^ sha256_S(x, 13) ^ sha256_S(x, 22));}
function sha256_Sigma1256(x) {return (sha256_S(x, 6) ^ sha256_S(x, 11) ^ sha256_S(x, 25));}
function sha256_Gamma0256(x) {return (sha256_S(x, 7) ^ sha256_S(x, 18) ^ sha256_R(x, 3));}
function sha256_Gamma1256(x) {return (sha256_S(x, 17) ^ sha256_S(x, 19) ^ sha256_R(x, 10));}
function sha256_Sigma0512(x) {return (sha256_S(x, 28) ^ sha256_S(x, 34) ^ sha256_S(x, 39));}
function sha256_Sigma1512(x) {return (sha256_S(x, 14) ^ sha256_S(x, 18) ^ sha256_S(x, 41));}
function sha256_Gamma0512(x) {return (sha256_S(x, 1) ^ sha256_S(x, 8) ^ sha256_R(x, 7));}
function sha256_Gamma1512(x) {return (sha256_S(x, 19) ^ sha256_S(x, 61) ^ sha256_R(x, 6));}

var sha256_K = new Array
(
 1116352408, 1899447441, -1245643825, -373957723, 961987163, 1508970993,
 -1841331548, -1424204075, -670586216, 310598401, 607225278, 1426881987,
 1925078388, -2132889090, -1680079193, -1046744716, -459576895, -272742522,
 264347078, 604807628, 770255983, 1249150122, 1555081692, 1996064986,
 -1740746414, -1473132947, -1341970488, -1084653625, -958395405, -710438585,
 113926993, 338241895, 666307205, 773529912, 1294757372, 1396182291,
 1695183700, 1986661051, -2117940946, -1838011259, -1564481375, -1474664885,
 -1035236496, -949202525, -778901479, -694614492, -200395387, 275423344,
 430227734, 506948616, 659060556, 883997877, 958139571, 1322822218,
 1537002063, 1747873779, 1955562222, 2024104815, -2067236844, -1933114872,
 -1866530822, -1538233109, -1090935817, -965641998
);

function binb_sha256(m, l)
{
 var HASH = new Array(1779033703, -1150833019, 1013904242, -1521486534,
            1359893119, -1694144372, 528734635, 1541459225);
 var W = new Array(64);
 var a, b, c, d, e, f, g, h;
 var i, j, T1, T2;

 /* append padding */
 m[l >> 5] |= 0x80 << (24 - l % 32);
 m[((l + 64 >> 9) << 4) + 15] = l;

 for(i = 0; i < m.length; i += 16)
 {
  a = HASH[0];
  b = HASH[1];
  c = HASH[2];
  d = HASH[3];
  e = HASH[4];
  f = HASH[5];
  g = HASH[6];
  h = HASH[7];

  for(j = 0; j < 64; j++)
  {
   if (j < 16) W[j] = m[j + i];
   else W[j] = safe_add(safe_add(safe_add(sha256_Gamma1256(W[j - 2]), W[j - 7]),
                      sha256_Gamma0256(W[j - 15])), W[j - 16]);

   T1 = safe_add(safe_add(safe_add(safe_add(h, sha256_Sigma1256(e)), sha256_Ch(e, f, g)),
                             sha256_K[j]), W[j]);
   T2 = safe_add(sha256_Sigma0256(a), sha256_Maj(a, b, c));
   h = g;
   g = f;
   f = e;
   e = safe_add(d, T1);
   d = c;
   c = b;
   b = a;
   a = safe_add(T1, T2);
  }

  HASH[0] = safe_add(a, HASH[0]);
  HASH[1] = safe_add(b, HASH[1]);
  HASH[2] = safe_add(c, HASH[2]);
  HASH[3] = safe_add(d, HASH[3]);
  HASH[4] = safe_add(e, HASH[4]);
  HASH[5] = safe_add(f, HASH[5]);
  HASH[6] = safe_add(g, HASH[6]);
  HASH[7] = safe_add(h, HASH[7]);
 }
 return HASH;
}

function safe_add (x, y)
{
 var lsw = (x & 0xFFFF) + (y & 0xFFFF);
 var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
 return (msw << 16) | (lsw & 0xFFFF);
}

以上就是本文的全部内容,希望对大家有所帮助,希望大家继续关注我们的最新内容。

(0)

相关推荐

  • 原生js的RSA和AES加密解密算法

    本文实例为大家分享了js中RSA和AES加密解密详细代码,供大家参考,具体内容如下 <!doctype html> <html> <head> <meta charset='UTF-8'> </head> <body> <div class='test'></div> <script type="text/javascript"> function encrypt(data, k

  • JavaScript SHA512加密算法详细代码

    本文实例为大家分享了JavaScript SHA512加密算法,供大家参考,具体内容如下 /* * A JavaScript implementation of the Secure Hash Algorithm, SHA-512, as defined * in FIPS 180-2 * Version 2.2 Copyright Anonymous Contributor, Paul Johnston 2000 - 2009. * Other contributors: Greg Holt,

  • 浅谈js算法和流程控制

    代码整体结构是执行速度的决定因素之一. 代码量少不一定运行速度快, 代码量多也不一定运行速度慢. 性能损失与代码组织方式和具体问题解决办法直接相关. 倒序循环可以提高性能,如: for (var i=items.length; i--; ){ process(items[i]); } 控制件与 true 值进行比较,任何非零数字自动强制转换为 true,而零等同于 false.实际上,控制条件已经从两次比较(迭代少于总数吗?它等于 true 吗?)减少到一次比较(它等于 true 吗?).将每个

  • JavaScript SHA1加密算法实现详细代码

    本文实例为大家介绍了JavaScript SHA1加密算法吗,供大家参考,具体内容如下 /* * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined * in FIPS 180-1 * Version 2.2 Copyright Paul Johnston 2000 - 2009. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Los

  • 整理Javascript流程控制语句学习笔记

    1.做判断(if语句) if语句是基于条件成立才执行相应代码时使用的语句. 语法: if(条件){ 条件成立时执行代码 } 例子:假设你应聘web前端技术开发岗位,如果你会HTML技术,你面试成功,欢迎加入公司. <script type="text/javascript"> var mycarrer = "HTML"; if (mycarrer == "HTML"){ document.write("你面试成功,欢迎加入公

  • JavaScript程序中的流程控制语句用法总结

    条件判断语句 1.if语句 if (condition) statement1 else statement2 其中的condition条件可以是任意表达式,而且对这个表达式的求值结果不一定是布尔值.ECMAScript会自动调用Boolean()转换函数将这个表达式的结果转换为一个布尔值.如果对condition求值的结果为true,则执行statement1,如果对condition求值结果为false,则执行statement2.这两个语句既可以是一行代码,也可以是一个代码块(推荐). i

  • 详解JavaScript的流程控制语句

    JS的核心ECMAScript规定的流程控制语句和其他的程序设计语言还是蛮相似的.我们选择一些实用的例子来看 一下这些语句.顺序结构我们在这里就不再提到,直接说条件和循环以及其他语句. 一.条件选择结构        条件选择语句用于基于不同的条件来执行不同的动作,通常在写代码时,总是需要为不同的决定来执行不同的 动作,可以在代码中使用条件语句来完成该任务.        在JavaScript中,我们可使用以下条件语句: if 语句:只有当指定条件为true时,使用该语句来执行代码 <!DOC

  • JS实现的几个常用算法

    (1)数组去重 原理:定义一个对象obj,然后把数组元素作为obj的属性名,利用属性名是否重复进行判重 var unique = function(arr){ let obj = {}; let newArr = []; arr.forEach(function(x){ if(!obj[x]){ //如果对象中没有该元素对应的属性 obj[x] = true; newArr.push(x); } }); return newArr; } (2)使用快速排序算法对数组进行排序 这里面包括两种效果,

  • javascript轮播图算法

    轮播图,是网站首页中常见的一种图片切换特效,作为前端开发者,我相信很多开发者都直接调用了Jquery中的封装好的方法实现图片轮播,省事简单.所以我想介绍一下javascript纯代码实现的图片轮播. HTML <div id="content_img1"> <ul id="img1"> <li><img src="img/5.jpg"/></li> <li><img s

  • JavaScript SHA-256加密算法详细代码

    本文实例为大家分享了JavaScript SHA-256加密算法,供大家参考,具体内容如下 /* * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined * in FIPS 180-2 * Version 2.2 Copyright Angel Marin, Paul Johnston 2000 - 2009. * Other contributors: Greg Holt, Andrew K

  • JavaScript SHA512&SHA256加密算法详解

    JavaScript SHA512加密算法详细代码 /* * A JavaScript implementation of the Secure Hash Algorithm, SHA-512, as defined * in FIPS 180-2 * Version 2.2 Copyright Anonymous Contributor, Paul Johnston 2000 - 2009. * Other contributors: Greg Holt, Andrew Kepert, Ydn

  • JavaScript实现星座查询功能 附详细代码

    目录 一.题目 二.代码 三.结果 四.总结 一.题目 在文本框中输入一个生日值,点击按钮,可以显示此生日的对应星座.定义一个函数,该函数用来接收一个生日值(月日组成的4位字符串,比如"0210","1225"等),并根据该生日值提示属于的星座. 二.代码 <!doctype html> <html> <head> <meta charset="utf-8"> <title>星座查询&l

  • JavaScript+CSS相册特效实例代码

    嗯 就是这样一个例子,视频学到的一个特效,实际用处并不大,但是可以帮助理解JS语言和熟悉CSS3样式. 设计: 观察一张图片的变化,发现: 1.图片缩放(随机,并且不是同时运动) 1.从大到小 2.从小到大,透明度从1到0(在第一步运动完成后立马开始) 2.图片旋转(随机,并且不是同时运动的.需要在全部运动走完以后开始) 3. 因为每张图片是随机开始变换的,所以起始时间是不同的,这里可设置一个延迟器setTimeout,时间用random随机生成即可. 4. 中间需要用到自执行函数,因为setT

  • Vue.js实现实例搜索应用功能详细代码

    实例搜索应用 实现效果: 实现代码与注释: <!DOCTYPE html> <html> <head> <title>实例搜索</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style type=&q

  • JavaScript实现SHA-1加密算法的方法

    本文实例讲述了JavaScript实现SHA-1加密算法的方法.分享给大家供大家参考.具体实现方法如下: 调用方法:hex_sha1即可. 复制代码 代码如下: /*  *  * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined  * in FIPS PUB 180-1  *  * By lizq  *  * 2006-11-11  *  */ /*  *  * Configurable var

  • Javascript 判断客户端浏览器类型代码

    复制代码 代码如下: <script type="text/javascript"> /*详细方法1*/ function CheckBrowser() { var app=navigator.appName; var verStr=navigator.appVersion; //火狐浏览器 if (app.indexOf('Netscape') != -1) { alert("你使用的是Netscape浏览器或火狐浏览器."); } else if (

  • Java语言实现Blowfish加密算法完整代码分享

    前几天网上突然出现流言:某东发生数据泄露12G,最终某东在一篇声明中没有否认,还算是勉强承认了吧,这件事对于一般人有什么影响.应该怎么做已经有一堆人说了,所以就不凑热闹了,咱来点对程序猿来说实际点的,说一个个人认为目前比较安全的加密算法:Blowfish. 上代码之前,先说几点Blowfish加密算法的特点: 1. 对称加密,即加密的密钥和解密的密钥是相同的: 2. 每次加密之后的结果是不同的(这也是老夫比较欣赏的一点): 3. 可逆的,和老夫之前的文章介绍的md5等摘要算法不一样,他是可逆的:

  • Ajax引擎 ajax请求步骤详细代码

    说起AJAX,可能是很多同学在很多地方都看到过,各大招聘网站上对于WEB前端和PHP程序员的技能要求清单中也是必不可少的一项.但是,ajax请求步骤详细代码以及说明却比较少见到 什么是AJAX引擎? AJAX引擎其实是一个JavaScript对象,全写是 window.XMLHttpRequest对象,由于浏览器的版本不同,特别是老版本的IE浏览器,虽然也支持AJAX引擎,但是写法上有区别,在IE低版本中通常用 ActiveXObject对象来创建AJAX引擎. AJAX 来自英文"Asynch

随机推荐