使用crypto-js在浏览器上对数据加密签名

重要知识点:

  1. CryptoJS.lib.WordArray  WordArray对象可以理解为byte[]
  2. CryptoJS.enc 提供编码转换,从字符串转为WordArray,或从WordArray转为字符串

MD5加密

var ciphetext = CryptoJS.MD5(plaintext);//获得一个CryptoJS.lib.WordArray对象
ciphetext.toString(CryptoJS.enc.Base64);//转成Base64字符串,也可以用 CryptoJS.enc.Base64.stringify(ciphetext); //ciphetext.toString(); //默认转成BitString格式,与ciphetext.toString(CryptoJS.enc.Hex);效果相同

完整代码

<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/crypto-js.min.js" type="text/javascript"></script>
<title>MD5 加密解密</title>
<script type="text/javascript">
function encryptor() {
var plaintext = $("#plaintext").val();
var displayFormat = $("#displayFormat").val();
var ciphetext = CryptoJS.MD5(plaintext);
switch (displayFormat) {
case "Base64String":
ciphetext = CryptoJS.enc.Base64.stringify(ciphetext);
break;
case "BitString":
ciphetext = CryptoJS.enc.Hex.stringify(ciphetext);
break;
}
$("#ciphetext").val(ciphetext);
}
</script>
<style>
h, div {
margin: 10px 10px;
} input[type=text] {
width: 500px;
} input[type=button] {
margin: 0px 5px;
padding: 10px;
} select {
width: 250px;
} textarea {
width: 500px;
height: 150px;
}
</style>
</head>
<body>
<div>
<div>
<h>MD5 加密解密</h>
</div>
<div>
<label for="plaintext">明文:</label>
<br />
<textarea id="plaintext"></textarea>
</div>
<div>
<label for="plaintext">显示格式:</label>
<br />
<select id="displayFormat">
<option value="Base64String" selected="selected">Base64String</option>
<option value="BitString">BitString</option>
</select>
</div>
<div>
<input type="button" value="加密" onclick="encryptor()" />
</div>
<div>
<label for="ciphetext">密文:</label>
<br />
<textarea id="ciphetext" readonly="readonly" ></textarea>
</div>
</div>
</body>
</html>

HmacSha1 签名

var signtext = '这里是你的签名';
var converttext ='这里是正文,被签名的文本'; signtext = CryptoJS.enc.Utf8.parse(signtext);//得到一个CryptoJS.lib.WordArray对象
converttext = CryptoJS.enc.Utf8.parse(converttext);//得到一个CryptoJS.lib.WordArray对象 var resulttext = CryptoJS.HmacSHA1(converttext, signtext); //得到一个CryptoJS.lib.WordArray对象,这就是你的签名 resulttext=resulttext.toString();//转成BitString格式

完整代码

<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/crypto-js.min.js" type="text/javascript"></script>
<title>HmacSha1 签名</title> <script type="text/javascript">
$(function () {
$("#buttonSign").bind("click", Sign);
$("#buttonVerifySign").bind("click", VerifySign);
});
</script>
<script type="text/javascript">
function Sign() {
var signtext = $("#signtext").val();
var converttext = $("#converttext").val(); signtext = GetWordArray(signtext);
converttext = CryptoJS.enc.Utf8.parse(converttext); var resulttext = CryptoJS.HmacSHA1(converttext, signtext);
resulttext = resulttext.concat(converttext); $("#resulttext").val(WrodArrayToString(resulttext));
} function VerifySign() {
var signtext = $("#signtext").val();
var converttext = $("#converttext").val(); signtext = GetWordArray(signtext);
converttext = GetWordArray(converttext); var signtext1 = GetSign(converttext);
var resulttext = GetCiphetext(converttext);
var signtext2 = CryptoJS.HmacSHA1(resulttext, signtext) var b = WrodArrayToString(signtext1) == WrodArrayToString(signtext2);
if (b) {
$("#resulttext").val(CryptoJS.enc.Utf8.stringify(resulttext));
} else {
$("#resulttext").val("验证失败");
}
} function GetSign(wordArray) {
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
words = words.slice(0, 5);
return new CryptoJS.lib.WordArray.init(words, 20);
} function GetCiphetext(wordArray) {
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
words = words.slice(5, words.length);
return new CryptoJS.lib.WordArray.init(words, sigBytes - 20);
} /**
function SplitWordArray(wordArray,startIndex,length){
var words = wordArray.words;
var sigBytes = wordArray.sigBytes; var hexChars = [];
for (var i = 0; i < sigBytes; i++) {
var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
hexChars.push((bite >>> 4).toString(16));
hexChars.push((bite & 0x0f).toString(16));
}
hexChars=hexChars.slice(startIndex,startIndex+length);
return new CryptoJS.lib.WordArray.init(hexChars, length);
}
**/ function GetWordArray(value) {
var displayFormat = $("#displayFormat").val();
var wrodArray = {};
switch (displayFormat) {
case "Base64String":
wrodArray = CryptoJS.enc.Base64.parse(value);
break;
case "BitString":
wrodArray = CryptoJS.enc.Hex.parse(value);
break;
}
return wrodArray;
} function WrodArrayToString(wrodArray) {
var displayFormat = $("#displayFormat").val();
var value = "";
switch (displayFormat) {
case "Base64String":
value = CryptoJS.enc.Base64.stringify(wrodArray);
break;
case "BitString":
value = CryptoJS.enc.Hex.stringify(wrodArray);
break;
}
return value;
} </script>
<style>
h, div {
margin: 10px 10px;
} input[type=text] {
width: 500px;
} input[type=button] {
margin: 0px 5px;
padding: 10px;
} select {
width: 250px;
} textarea {
width: 500px;
height: 150px;
}
</style> </head>
<body>
<div>
<div>
<h>HmacSha1 签名</h>
</div>
<div>
<label for="signtext">签名</label>
<br />
<input type="text" id="signtext" />
</div>
<div>
<label for="converttext">待处理文本:</label>
<br />
<textarea id="converttext"></textarea>
</div>
<div>
<label for="displayFormat">编码格式:</label>
<br />
<select id="displayFormat">
<option value="Base64String" selected="selected">Base64String</option>
<option value="BitString">BitString</option>
</select>
</div>
<div>
<input type="button" value="签名" id="buttonSign" />
<input type="button" value="验证" id="buttonVerifySign" />
</div>
<div>
<label for="resulttext">结果:</label>
<br />
<textarea id="resulttext"></textarea>
</div>
</div>
</body>
</html>

AES加密

加密

//AES加密
//plaintextWordArray 明文,一个CryptoJS.lib.WordArray对象
//keyWordArray 秘钥,一个CryptoJS.lib.WordArray对象
//ivWordArray 偏移量,一个CryptoJS.lib.WordArray对象
//返回一个CryptoJS.lib.WordArray对象
function Encryptor(plaintextWordArray, keyWordArray, ivWordArray) {
var encryptedData = undefined;
//无偏移量加密
if (ivWordArray == null || ivWordArray == undefined) {
encryptedData = CryptoJS.AES.encrypt(plaintextWordArray, keyWordArray, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
} else {
//有偏移量加密
encryptedData = CryptoJS.AES.encrypt(plaintextWordArray, keyWordArray, {
iv: ivWordArray,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
}
if (encryptedData!=null&&encryptedData != undefined) {
return encryptedData.ciphertext;
}
return undefined;
}

解密

// AES 解密
// ciphertextWordArray 密文,一个CryptoJS.lib.WordArray对象
// keyWordArray 秘钥,一个CryptoJS.lib.WordArray对象
// ivWordArray 偏移量,一个CryptoJS.lib.WordArray对象
// 返回一个CryptoJS.lib.WordArray对象
function Decryptor(ciphertextWordArray, keyWordArray, ivWordArray) {
var decryptedData = undefined; //密文必须为Base64格式的字符串
var ciphertext = ciphertextWordArray.toString(CryptoJS.enc.Base64); if (ivWordArray == null || ivWordArray == undefined) {
decryptedData = CryptoJS.AES.decrypt(ciphertext, keyWordArray, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
} else {
decryptedData = CryptoJS.AES.decrypt(ciphertext, keyWordArray, {
iv: ivWordArray,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
}
return decryptedData;
}

完整代码

<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/crypto-js.min.js" type="text/javascript"></script>
<!--<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/aes.js" type="text/javascript"></script>-->
<script type="text/javascript">
//加密
var key = CryptoJS.enc.Base64.parse('5C9ErX8g1qLYA298clMcumQ+V9d46hQXZmJCVb7ZRUw=');
var plaintext = '中文什么的也认识?';
plaintext = CryptoJS.enc.Utf8.parse(plaintext);
var encryptedData = CryptoJS.AES.encrypt(plaintext, key, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
}); var encryptedBase64Str = CryptoJS.enc.Base64.stringify(encryptedData.ciphertext);
console.log(encryptedBase64Str); //解密
var decryptedData = CryptoJS.AES.decrypt(encryptedBase64Str, key, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
var decryptedStr = decryptedData.toString(CryptoJS.enc.Utf8);
console.log(decryptedStr); </script> <script type="text/javascript">
Math.randomByMaxValue = function (maxValue) {
return parseInt(Math.random() * maxValue, 10);
}
</script> <script type="text/javascript"> $(function () {
$("#buttonCreateKey").bind("click", function () {
$("#Key").val(CreateKey());
});
$("#buttonCreateIv").bind("click", function () {
$("#Iv").val(CreateIv());
});
$("#buttonEncryptor").bind("click", function () {
var key = $("#Key").val();
var iv = $("#Iv").val();
var plaintext = $("#transferText").val(); if (key.length == 0) {
showAlert("密钥不能为空!");
return;
} var plaintextWordArray = CryptoJS.enc.Utf8.parse(plaintext);
var keyWordArray = CryptoJS.enc.Utf8.parse(key); var encryptedData = undefined;
if (iv.length > 0) {
var ivWordArray = CryptoJS.enc.Utf8.parse(iv);
encryptedData = Encryptor(plaintextWordArray, keyWordArray, ivWordArray);
}
else {
encryptedData = Encryptor(plaintextWordArray, keyWordArray, undefined);
}
if (encryptedData != null && encryptedData != undefined) {
$("#resultText").val(WordArrayToString(encryptedData));
} else {
$("#resultText").val('加密失败!');
}
});
$("#buttonDecryptor").bind("click", function () {
var key = $("#Key").val();
var iv = $("#Iv").val();
var ciphertext = $("#transferText").val(); if (key.length == 0) {
showAlert("密钥不能为空!");
return;
}
var keyWordArray = CryptoJS.enc.Utf8.parse(key);
var ciphertextWordArray = GetWordArray(ciphertext);
var decryptorData = undefined;
if (iv.length > 0) {
var ivWordArray = CryptoJS.enc.Utf8.parse(iv);
decryptorData = Decryptor(ciphertextWordArray, keyWordArray, ivWordArray);
}
else {
decryptorData = Decryptor(ciphertextWordArray, keyWordArray, undefined);
}
if (decryptorData != null && decryptorData != undefined) {
$("#resultText").val(CryptoJS.enc.Utf8.stringify(decryptorData));
} else {
$("#resultText").val('解密失败!');
}
});
}); </script> <script type="text/javascript">
function GetWordArray(value) {
var displayFormat = $("#displayFormat").val();
var WordArray = {};
switch (displayFormat) {
case "Base64String":
WordArray = CryptoJS.enc.Base64.parse(value);
break;
case "BitString":
WordArray = CryptoJS.enc.Hex.parse(value);
break;
}
return WordArray;
} function WordArrayToString(wordArray) {
var displayFormat = $("#displayFormat").val();
var value = "";
switch (displayFormat) {
case "Base64String":
value = CryptoJS.enc.Base64.stringify(wordArray);
break;
case "BitString":
value = CryptoJS.enc.Hex.stringify(wordArray);
break;
}
return value;
} var constStr='ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; function CreateKey() {
var a = '';
for (var i = 0; i < 32; i++) {
a += constStr[Math.randomByMaxValue(constStr.length)];
}
return a;
} function CreateIv() {
var a = '';
for (var i = 0; i < 32; i++) {
a += constStr[Math.randomByMaxValue(constStr.length)];
}
return a;
} function Encryptor(plaintextWordArray, keyWordArray, ivWordArray) {
var encryptedData = undefined;
if (ivWordArray == null || ivWordArray == undefined) {
encryptedData = CryptoJS.AES.encrypt(plaintextWordArray, keyWordArray, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
} else {
encryptedData = CryptoJS.AES.encrypt(plaintextWordArray, keyWordArray, {
iv: ivWordArray,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
}
if (encryptedData!=null&&encryptedData != undefined) {
return encryptedData.ciphertext;
}
return undefined;
} function Decryptor(ciphertextWordArray, keyWordArray, ivWordArray) {
var decryptedData = undefined; //密文必须为Base64格式的字符串
var ciphertext = ciphertextWordArray.toString(CryptoJS.enc.Base64); if (ivWordArray == null || ivWordArray == undefined) {
decryptedData = CryptoJS.AES.decrypt(ciphertext, keyWordArray, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
} else {
decryptedData = CryptoJS.AES.decrypt(ciphertext, keyWordArray, {
iv: ivWordArray,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
}
return decryptedData;
} function showAlert(message) {
alert(message);
}
</script>
<style>
h, div {
margin: 10px 10px;
} input[type=text] {
width: 500px;
} input[type=button] {
margin: 0px 5px;
padding: 10px;
} select {
width: 250px;
} textarea {
width: 500px;
height: 150px;
}
</style>
</head>
<body>
<div>
<h>AES 加密解密</h>
<div>
<label for="Key">秘钥:</label>
<br />
<input type="text" id="Key" />
</div>
<div>
<label for="Iv">偏移量:</label>
<br />
<input type="text" id="Iv" />
</div>
<div>
<label for="displayFormat">显示格式:</label>
<br />
<select id="displayFormat">
<option value="Base64String" selected="selected">Base64String</option>
<option value="BitString">BitString</option>
</select>
</div>
<div>
<label for="transferText">待处理文本:</label>
<br />
<textarea id="transferText"></textarea>
</div>
<div>
<input type="button" value="创建秘钥" id="buttonCreateKey" />
<input type="button" value="创建偏移量" id="buttonCreateIv" />
<input type="button" value="加密" id="buttonEncryptor" />
<input type="button" value="解密" id="buttonDecryptor" />
</div>
<div>
<label for="resultText">结果:</label>
<br />
<textarea id="resultText" readonly="readonly"></textarea>
</div>
</div>
</body>
</html>

Js加密算法的更多相关文章

  1. Java执行js加密算法

    Java执行js加密算法 今日需求:在后端执行一段加密算法,算法是js写的 明白需求以后疯狂百度.最后发现JDK提供了各种脚本的支持(怪笔者学艺不精,第一次见识到这个库,留下不学无术的泪水),正题开始 ...

  2. 【软件编程】乐易贵宾VIP教程 - JS改写+网页操作系列教程

    JS改写系列教程: 1.MD5加密改写教程(爱拍网登录)2.解密如何快速找到真确的js加密算法3.多重MD5加密改写教程(5173登录)4.DZ论坛登录加密改写5.唯品会手机登录加密改写6.新浪微博密 ...

  3. 如何系统地学习Node.js?

    转载自知乎:http://www.zhihu.com/question/21567720 ------------------------------------------------------- ...

  4. www.sojson.com网站高级JS加密破解

    在网上冲浪,看到了一个网站的JS加密,下面有一句话: 乍一看这句话吓一跳,我去这么猛,然后就很有兴趣想看看究竟是怎样一种加密算法. 对于破解JS加密算法的时候,都是先输入一个简单的语句然后分析加密后语 ...

  5. webqq 获得好友列表hash算法 获得最新hash的方法

    webqq获得好友列表的hash算法,大约每一个月中旬会变动一次.知道怎么获得他就能够了. js文件路径 http://web.qstatic.com/webqqpic/pubapps/0/50/eq ...

  6. 通过winform+模拟登录实现快速一键登录到人才招聘网站

    之前为了便于人事部门招聘登录网站更简洁高效,免去每天频繁输网址.用户名.密码等相关登录信息,特基于winform+HttpWebRequest实现模拟请求登录,最终达到一键登录到招聘网站后台的效果. ...

  7. 一个免费ss网站的数据爬取过程

    一个免费ss网站的数据爬取过程 Apr 14, 2019 引言 爬虫整体概况 主要功能方法 绕过DDOS保护(Cloudflare) post中参数a,b,c的解析 post中参数a,b,c的解析 p ...

  8. nodejs mysql 创建连接池

    用Nodejs连接MySQL 从零开始nodejs系列文章,将介绍如何利Javascript做为服务端脚本,通过Nodejs框架web开发.Nodejs框架是基于V8的引擎,是目前速度最快的Javas ...

  9. 爬虫——控制台抓包和requests.post()发送请求

    控制台抓包 打开方式及常用选项 1.打开浏览器,F12打开控制台,找到Network选项卡 2.控制台常用选项 1.Network: 抓取网络数据包 1.ALL: 抓取所有的网络数据包 2.XHR:抓 ...

随机推荐

  1. VR

  2. [leetcode]250. Count Univalue Subtrees统计节点值相同的子树

    Given a binary tree, count the number of uni-value subtrees. A Uni-value subtree means all nodes of ...

  3. mysql非主键自增长

    mysql并非只有主键才能自增长,而是设为键的列就可以设置自增长.   如下: CREATE TABLE t1 ( id INT, col1 INT auto_increment NOT NULL ) ...

  4. spring框架之AspectJ的XML方式完成AOP的开发

    1. 步骤一:创建JavaWEB项目,引入具体的开发的jar包 * 先引入Spring框架开发的基本开发包 * 再引入Spring框架的AOP的开发包 * spring的传统AOP的开发的包 * sp ...

  5. 嵌入式的SQL程序设计

    嵌入式的SQL程序设计 sql语句大全之嵌入式SQL 2017-01-18 16:00 来源:未知   嵌入式SQL 为了更好的理解嵌入式SQL,本节利用一个具体例子来说明.嵌入式SQL允许程序连接数 ...

  6. Codeforces 677C. Vanya and Label 位操作

    C. Vanya and Label time limit per test:1 second memory limit per test:256 megabytes input:standard i ...

  7. hdu - 1072(dfs剪枝或bfs)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1072 思路:深搜每一个节点,并且进行剪枝,记录每一步上一次的s1,s2:如果之前走过的时间小于这一次, ...

  8. maven随笔

    1.在我们项目顶层的POM文件中,我们会看到dependencyManagement元素.通过它元素来管理jar包的版本,让子项目中引用一个依赖而不用显示的列出版本号.Maven会沿着父子层次向上走, ...

  9. js获取年月日时分秒星期

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  10. 百度上传插件 WebUploader初始使用

    引入资源 使用Web Uploader文件上传需要引入三种资源:JS, CSS, SWF. <!--引入CSS--> <link rel="stylesheet" ...