欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

RSA加密超长数据 前端js 作为参考

程序员文章站 2024-03-14 14:42:52
...

偏前端 + rsa加解密 + jsencrypt.min.js–(新增超长字符分段加解密)
复制代码

 <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 ]

[官方网站 http://travistidwell.com/jsencrypt/ ]

jq库: " <script src="http://code.jquery.com/jquery-1.8.3.min.js"> </script>"

(注!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回来。
//方法一

JSEncrypt.prototype.encryptLong=function (d){
  var k = this.key;
  var maxLength = (((k.n.bitLength() + 7) >> 3) - 11);

  try {
    var lt = "";
    var ct = "";

    if (d.length > maxLength) {
      lt = d.match(/.{1,117}/g);
      lt.forEach(function (entry) {
        var t1 = k.encrypt(entry);
        ct += t1;
      });
      return hexToBytes(ct);
    }
    var t = k.encrypt(d);
    var y = hexToBytes(t);
    return y;
  } catch (ex) {
    return false;
  }
}

JSEncrypt.prototype.decryptLong = function (string) {
    var k = this.getKey();
    var maxLength = ((k.n.bitLength() + 7) >> 3);
    //var maxLength = 128;
    try {

        var str = bytesToHex(string);
        //var b=hex2Bytes(str);

        var inputLen = str.length;

        var ct = "";
        if (str.length > maxLength) {

            var lt = str.match(/.{1,256}/g);
            lt.forEach(function (entry) {
                var t1 = k.decrypt(entry);
                ct += t1;
            });
            return ct;
        }
        var y = k.decrypt(bytesToHex(string));
        return y;
    } catch (ex) {
        return false;
    }
};

//方法2

JSEncrypt.prototype.encryptLong2 = function (string) {
    var k = this.getKey();
    try {
        var lt = "";
        var ct = "";
        //RSA每次加密117bytes,需要辅助方法判断字符串截取位置
        //1.获取字符串截取点
        var bytes = new Array();
        bytes.push(0);
        var byteNo = 0;
        var len, c;
        len = string.length;
        var temp = 0;
        for (var i = 0; i < len; i++) {
            c = string.charCodeAt(i);
            if (c >= 0x010000 && c <= 0x10FFFF) {
                byteNo += 4;
            } else if (c >= 0x000800 && c <= 0x00FFFF) {
                byteNo += 3;
            } else if (c >= 0x000080 && c <= 0x0007FF) {
                byteNo += 2;
            } else {
                byteNo += 1;
            }
            if ((byteNo % 117) >= 114 || (byteNo % 117) == 0) {
                if (byteNo - temp >= 114) {
                    bytes.push(i);
                    temp = byteNo;
                }
            }
        }
        //2.截取字符串并分段加密
        if (bytes.length > 1) {
            for (var i = 0; i < bytes.length - 1; i++) {
                var str;
                if (i == 0) {
                    str = string.substring(0, bytes[i + 1] + 1);
                } else {
                    str = string.substring(bytes[i] + 1, bytes[i + 1] + 1);
                }
                var t1 = k.encrypt(str);
                ct += t1;
            }
            ;
            if (bytes[bytes.length - 1] != string.length - 1) {
                var lastStr = string.substring(bytes[bytes.length - 1] + 1);
                ct += k.encrypt(lastStr);
            }
            return hexToBytes(ct);
        }
        var t = k.encrypt(string);
        var y = hexToBytes(t);
        return y;
    } catch (ex) {
        return false;
    }
};

JSEncrypt.prototype.decryptLong2 = function (string) {
    var k = this.getKey();
    // var maxLength = ((k.n.bitLength()+7)>>3);
    var MAX_DECRYPT_BLOCK = 128;
    try {
        var ct = "";
        var t1;
        var bufTmp;
        var hexTmp;
        var str = bytesToHex(string);
        var buf = hexToBytes(str);
        var inputLen = buf.length;
        //开始长度
        var offSet = 0;
        //结束长度
        var endOffSet = MAX_DECRYPT_BLOCK;

        //分段加密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                bufTmp = buf.slice(offSet, endOffSet);
                hexTmp = bytesToHex(bufTmp);
                t1 = k.decrypt(hexTmp);
                ct += t1;
                
            } else {
                bufTmp = buf.slice(offSet, inputLen);
                hexTmp = bytesToHex(bufTmp);
                t1 = k.decrypt(hexTmp);
                ct += t1;
             
            }
            offSet += MAX_DECRYPT_BLOCK;
            endOffSet += MAX_DECRYPT_BLOCK;
        }
        return ct;
    } catch (ex) {
        return false;
    }
};

作为参考,希望帮到您

相关标签: 加解密