偏前端 + rsa加解密 + jsencrypt.min.js--(新增超长字符分段加解密)


 1 <html>
 2     <head>
 3         <title>JavaScript RSA Encryption</title>
 4         <meta charset="UTF-8">
 5         <script src="js/jquery-1.11.3.min.js"></script>
 6         <script src="js/jsencrypt.min.js"></script>
 7     </head>
 8     <body style="text-align: center;">
 9         <label for="privkey">私钥</label>
10         <br/>
11         <textarea id="privkey" rows="15" cols="65">MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALwlTWcENnk+BE0DGSxML8yVoFffu+NMfzimnOa4Skft7objdBd3tmh/xqkgnh5+TpSLDb84l+TIwYOwAlO//Nae4qbpR7IFjG2A/kkUa1MwpMFW4bMfxTNhZ0/PJsg4KaPnlCS7edgRnKujfx0aFIUtI9pTd6hjW1uWblkUn7x7AgMBAAECgYEAsoOaK1Jd9S+YmRGFgvhOqgiV+Ip6FTJxy2iamnblU9Y3aZjKf7HASuphrfsay8f/+wTs6DBkPlkU80O/EYOp+r46UIKq5KChW2ErUVaMyxO4f8l0PW2RFHFYWq54SbRa73DepPeC3o9LRinEaJ7/rk13EHiS6RAPkFr/ZyTOYdECQQD0BNI4Wg4gJqZHC1QCHOQUaF2cDWh5cadWT9FOXKdgRUrP+2W67BJP/RjNPT++/cyP3pdNc8vMCkF8IGgJ7Pk/AkEAxWIwCK3prAxupNrlUhPNT+nfG05Bs0SYIQHSiwUykXkcUZAcAveNk2g8XlhAQ4fEZG9BQ0+MlA246FV90NlRxQJAJEm7QWoTA7D7tUD4A0BsoqRKl3Re/wBp1CoWhEK/GU/0qi1GmZ+VsZN/5rWfDzYK/7Ioafo4amV0C5N+JUu6XQJANbDuxf2guYcsNbXBeWEfkSRZ5xCTeJMpGplnTx+b0Mxz8o/Tvs7d+QH6oeM5n+T3fCZzRz8FS2SsLq7KqZvjzQJADLfcfxaYd3V7e0/Op08ifDyCjpLa3rviNFss/msOR3Mzfg7J05wD3oVHut+g+RVF7+Gnia07pV5YnFVd0WA1UA==</textarea>
12         <!--<br/>-->
13         <label for="pubkey">公钥</label>
14         <!--<br/>-->
15         <textarea id="pubkey" rows="15" cols="65">MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC8JU1nBDZ5PgRNAxksTC/MlaBX37vjTH84ppzmuEpH7e6G43QXd7Zof8apIJ4efk6Uiw2/OJfkyMGDsAJTv/zWnuKm6UeyBYxtgP5JFGtTMKTBVuGzH8UzYWdPzybIOCmj55Qku3nYEZyro38dGhSFLSPaU3eoY1tblm5ZFJ+8ewIDAQAB</textarea>
16         <br/>
17         <label for="input">要加密的字符串:</label>
18         <br/>
19         <textarea id="input" name="input" type="text" rows='4' cols='70'>123456789</textarea>
20         <!--<br/>-->
21         <input id="testme" type="button" value="Test Me!!!" />
22         <br/>
23         <label for="input">加密后的字符串:</label>
24         <br/>
25         <textarea id="jiami" name="jiami" type="text" rows='4' cols='70'></textarea>
26         <br/>
27         <label for="pubkey">解密后的密文</label>
28         <br/>
29         <textarea id="jiemi" name="jiemi" type="text" rows='4' cols='70'></textarea>
30     </body>
31 </html>

js部分:

 1 <script type="text/javascript">
 2             $(function() {
 3                 $('#testme').click(function() {
 4                     // 加密前的原文
 5                     console.log('这是原文' + $('#input').val())
 6                     // 进行RSA加密
 7                     var encrypt = new JSEncrypt();
 8                     encrypt.setPublicKey($('#pubkey').val());
 9                     var encrypted = encrypt.encrypt($('#input').val());
10                     // 加密后的密文
11                     console.log('这是加密之后的' + encrypted);
12                     $('#jiami').val(encrypted);
13                     
14                     //解密
15                     var decrypt = new JSEncrypt();
16                     decrypt.setPrivateKey($('#privkey').val());
17                     var uncrypted = decrypt.decrypt(encrypted);
18                     console.log('这是解密后的密文' + uncrypted);
19                     $('#jiemi').val(uncrypted);
20                 });
21             });
22         </script>

jsencrypt.min.js下载地址:

[github主页](https://github.com/travist/jsencrypt  )    

 
jq库:

(注!jquery-2.0以上版本不再支持IE 6/7/8) 并不是最新的版本就最好的,而是根据您项目需求所适合的版本!

 

最终效果:

 

----新增超长字符分段加解密----
1.首先引入一段转换的js
 1 //十六进制转字节
 2     function hexToBytes(hex) {
 3         for (var bytes = [], c = 0; c < hex.length; c += 2)
 4             bytes.push(parseInt(hex.substr(c, 2), 16));
 5         return bytes;
 6     }
 7 
 8 // 字节转十六进制
 9     function bytesToHex(bytes) {
10         for (var hex = [], i = 0; i < bytes.length; i++) {
11             hex.push((bytes[i] >>> 4).toString(16));
12             hex.push((bytes[i] & 0xF).toString(16));
13         }
14         return hex.join("");
15     }

2.在引入分段加解密js(这里有2种方法供选择,建议使用方法2

*:如果与JAVA后台数据交互。某些中文字符可能因为编码原因会乱码,可以加密前先进行  encodeURIComponent(s)。然后解密后在decode回来。

  (方法一):

  

 1 //方法一
 2 JSEncrypt.prototype.encryptLong=function (d){
 3   var k = this.key;
 4   var maxLength = (((k.n.bitLength() + 7) >> 3) - 11);
 5 
 6   try {
 7     var lt = "";
 8     var ct = "";
 9 
10     if (d.length > maxLength) {
11       lt = d.match(/.{1,117}/g);
12       lt.forEach(function (entry) {
13         var t1 = k.encrypt(entry);
14         ct += t1;
15       });
16       return hexToBytes(ct);
17     }
18     var t = k.encrypt(d);
19     var y = hexToBytes(t);
20     return y;
21   } catch (ex) {
22     return false;
23   }
24 }
25 
26 JSEncrypt.prototype.decryptLong = function (string) {
27     var k = this.getKey();
28     var maxLength = ((k.n.bitLength() + 7) >> 3);
29     //var maxLength = 128;
30     try {
31 
32         var str = bytesToHex(string);
33         //var b=hex2Bytes(str);
34 
35         var inputLen = str.length;
36 
37         var ct = "";
38         if (str.length > maxLength) {
39 
40             var lt = str.match(/.{1,256}/g);
41             lt.forEach(function (entry) {
42                 var t1 = k.decrypt(entry);
43                 ct += t1;
44             });
45             return ct;
46         }
47         var y = k.decrypt(bytesToHex(string));
48         return y;
49     } catch (ex) {
50         return false;
51     }
52 };

  方法二:

 1 //方法2
 2 JSEncrypt.prototype.encryptLong2 = function (string) {
 3     var k = this.getKey();
 4     try {
 5         var lt = "";
 6         var ct = "";
 7         //RSA每次加密117bytes,需要辅助方法判断字符串截取位置
 8         //1.获取字符串截取点
 9         var bytes = new Array();
10         bytes.push(0);
11         var byteNo = 0;
12         var len, c;
13         len = string.length;
14         var temp = 0;
15         for (var i = 0; i < len; i++) {
16             c = string.charCodeAt(i);
17             if (c >= 0x010000 && c <= 0x10FFFF) {
18                 byteNo += 4;
19             } else if (c >= 0x000800 && c <= 0x00FFFF) {
20                 byteNo += 3;
21             } else if (c >= 0x000080 && c <= 0x0007FF) {
22                 byteNo += 2;
23             } else {
24                 byteNo += 1;
25             }
26             if ((byteNo % 117) >= 114 || (byteNo % 117) == 0) {
27                 if (byteNo - temp >= 114) {
28                     bytes.push(i);
29                     temp = byteNo;
30                 }
31             }
32         }
33         //2.截取字符串并分段加密
34         if (bytes.length > 1) {
35             for (var i = 0; i < bytes.length - 1; i++) {
36                 var str;
37                 if (i == 0) {
38                     str = string.substring(0, bytes[i + 1] + 1);
39                 } else {
40                     str = string.substring(bytes[i] + 1, bytes[i + 1] + 1);
41                 }
42                 var t1 = k.encrypt(str);
43                 ct += t1;
44             }
45             ;
46             if (bytes[bytes.length - 1] != string.length - 1) {
47                 var lastStr = string.substring(bytes[bytes.length - 1] + 1);
48                 ct += k.encrypt(lastStr);
49             }
50             return hexToBytes(ct);
51         }
52         var t = k.encrypt(string);
53         var y = hexToBytes(t);
54         return y;
55     } catch (ex) {
56         return false;
57     }
58 };
59 
60 JSEncrypt.prototype.decryptLong2 = function (string) {
61     var k = this.getKey();
62     // var maxLength = ((k.n.bitLength()+7)>>3);
63     var MAX_DECRYPT_BLOCK = 128;
64     try {
65         var ct = "";
66         var t1;
67         var bufTmp;
68         var hexTmp;
69         var str = bytesToHex(string);
70         var buf = hexToBytes(str);
71         var inputLen = buf.length;
72         //开始长度
73         var offSet = 0;
74         //结束长度
75         var endOffSet = MAX_DECRYPT_BLOCK;
76 
77         //分段加密
78         while (inputLen - offSet > 0) {
79             if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
80                 bufTmp = buf.slice(offSet, endOffSet);
81                 hexTmp = bytesToHex(bufTmp);
82                 t1 = k.decrypt(hexTmp);
83                 ct += t1;
84                 
85             } else {
86                 bufTmp = buf.slice(offSet, inputLen);
87                 hexTmp = bytesToHex(bufTmp);
88                 t1 = k.decrypt(hexTmp);
89                 ct += t1;
90              
91             }
92             offSet += MAX_DECRYPT_BLOCK;
93             endOffSet += MAX_DECRYPT_BLOCK;
94         }
95         return ct;
96     } catch (ex) {
97         return false;
98     }
99 };

3.再配上前面的html 和 js调用部分,就可以加解密任意长度的字符串啦,这里就不重复写了。

希望大家能够用的上哈,其实这个不推荐分段的,太长的话比较慢!!!一般就是用文章顶部的就足够了,做下登录密码的加解密就行了.

不想粘贴的童鞋到这里下载一个demo看看吧:https://download.csdn.net/download/xfyc002/10872854

    

posted @ 2018-12-21 10:55  睿舞霓裳  阅读(15686)  评论(2编辑  收藏  举报