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, Lostinet
 * Distributed under the BSD License
 * See http://pajhome.org.uk/crypt/md5 for details.
 * http://www.sharejs.com
 */

/*
 * 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_sha1(s)  { return rstr2hex(rstr_sha1(str2rstr_utf8(s))); }
function b64_sha1(s)  { return rstr2b64(rstr_sha1(str2rstr_utf8(s))); }
function any_sha1(s, e) { return rstr2any(rstr_sha1(str2rstr_utf8(s)), e); }
function hex_hmac_sha1(k, d)
 { return rstr2hex(rstr_hmac_sha1(str2rstr_utf8(k), str2rstr_utf8(d))); }
function b64_hmac_sha1(k, d)
 { return rstr2b64(rstr_hmac_sha1(str2rstr_utf8(k), str2rstr_utf8(d))); }
function any_hmac_sha1(k, d, e)
 { return rstr2any(rstr_hmac_sha1(str2rstr_utf8(k), str2rstr_utf8(d)), e); }

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

/*
 * Calculate the SHA1 of a raw string
 */
function rstr_sha1(s)
{
 return binb2rstr(binb_sha1(rstr2binb(s), s.length * 8));
}

/*
 * Calculate the HMAC-SHA1 of a key and some data (raw strings)
 */
function rstr_hmac_sha1(key, data)
{
 var bkey = rstr2binb(key);
 if(bkey.length > 16) bkey = binb_sha1(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_sha1(ipad.concat(rstr2binb(data)), 512 + data.length * 8);
 return binb2rstr(binb_sha1(opad.concat(hash), 512 + 160));
}

/*
 * 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;
}

/*
 * Calculate the SHA-1 of an array of big-endian words, and a bit length
 */
function binb_sha1(x, len)
{
 /* append padding */
 x[len >> 5] |= 0x80 << (24 - len % 32);
 x[((len + 64 >> 9) << 4) + 15] = len;

 var w = Array(80);
 var a = 1732584193;
 var b = -271733879;
 var c = -1732584194;
 var d = 271733878;
 var e = -1009589776;

 for(var i = 0; i < x.length; i += 16)
 {
  var olda = a;
  var oldb = b;
  var oldc = c;
  var oldd = d;
  var olde = e;

  for(var j = 0; j < 80; j++)
  {
   if(j < 16) w[j] = x[i + j];
   else w[j] = bit_rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1);
   var t = safe_add(safe_add(bit_rol(a, 5), sha1_ft(j, b, c, d)),
            safe_add(safe_add(e, w[j]), sha1_kt(j)));
   e = d;
   d = c;
   c = bit_rol(b, 30);
   b = a;
   a = t;
  }

  a = safe_add(a, olda);
  b = safe_add(b, oldb);
  c = safe_add(c, oldc);
  d = safe_add(d, oldd);
  e = safe_add(e, olde);
 }
 return Array(a, b, c, d, e);

}

/*
 * Perform the appropriate triplet combination function for the current
 * iteration
 */
function sha1_ft(t, b, c, d)
{
 if(t < 20) return (b & c) | ((~b) & d);
 if(t < 40) return b ^ c ^ d;
 if(t < 60) return (b & c) | (b & d) | (c & d);
 return b ^ c ^ d;
}

/*
 * Determine the appropriate additive constant for the current iteration
 */
function sha1_kt(t)
{
 return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 :
     (t < 60) ? -1894007588 : -899497514;
}

/*
 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
 * to work around bugs in some JS interpreters.
 */
function safe_add(x, y)
{
 var lsw = (x & 0xFFFF) + (y & 0xFFFF);
 var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
 return (msw << 16) | (lsw & 0xFFFF);
}

/*
 * Bitwise rotate a 32-bit number to the left.
 */
function bit_rol(num, cnt)
{
 return (num << cnt) | (num >>> (32 - cnt));
}

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

(0)

相关推荐

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

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

  • 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,

  • 详解JavaScript的流程控制语句

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

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

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

  • 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

  • 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

  • 浅谈js算法和流程控制

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

  • 原生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 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实现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实现的SHA-1加密算法完整实例

    本文实例讲述了JavaScript实现的SHA-1加密算法.分享给大家供大家参考,具体如下: /** * * Secure Hash Algorithm (SHA1) * http://www.webtoolkit.info/ * **/ function SHA1 (msg) { function rotate_left(n,s) { var t4 = ( n<<s ) | (n>>>(32-s)); return t4; }; function lsb_hex(val)

  • 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

  • Python md5与sha1加密算法用法分析

    本文实例讲述了Python md5与sha1加密算法.分享给大家供大家参考,具体如下: MD5 MD5的全称是Message-Digest Algorithm 5(信息-摘要算法),在90年代初由MIT Laboratory for Computer Science和RSA Data Security Inc的Ronald L. Rivest开发出来,经MD2.MD3和MD4发展而来.是一种不可逆的加密算法,目前是最牢靠的加密算法之一,尚没有能够逆运算的程序被开发出来,它对应任何字符串都可以加密

  • 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 (

随机推荐