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

html部分

<html>
    <head>
        <title>JavaScript RSA Encryptiontitle>
        <meta charset="UTF-8">
        <script src="js/jquery-1.11.3.min.js">script>
        <script src="js/jsencrypt.min.js">script>
    head>
    <body style="text-align: center;">
        <label for="privkey">私钥label>
        <br/>
        <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>
        
        <label for="pubkey">公钥label>
        
        <textarea id="pubkey" rows="15" cols="65">MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC8JU1nBDZ5PgRNAxksTC/MlaBX37vjTH84ppzmuEpH7e6G43QXd7Zof8apIJ4efk6Uiw2/OJfkyMGDsAJTv/zWnuKm6UeyBYxtgP5JFGtTMKTBVuGzH8UzYWdPzybIOCmj55Qku3nYEZyro38dGhSFLSPaU3eoY1tblm5ZFJ+8ewIDAQABtextarea>
        <br/>
        <label for="input">要加密的字符串:label>
        <br/>
        <textarea id="input" name="input" type="text" rows='4' cols='70'>123456789textarea>
        
        <input id="testme" type="button" value="Test Me!!!" />
        <br/>
        <label for="input">加密后的字符串:label>
        <br/>
        <textarea id="jiami" name="jiami" type="text" rows='4' cols='70'>textarea>
        <br/>
        <label for="pubkey">解密后的密文label>
        <br/>
        <textarea id="jiemi" name="jiemi" type="text" rows='4' cols='70'>textarea>
    body>
html>

js部分

<script type="text/javascript">
            $(function() {
                $('#testme').click(function() {
                    // 加密前的原文
                    console.log('这是原文' + $('#input').val())
                    // 进行RSA加密
                    var encrypt = new JSEncrypt();
                    encrypt.setPublicKey($('#pubkey').val());
                    var encrypted = encrypt.encrypt($('#input').val());
                    // 加密后的密文
                    console.log('这是加密之后的' + encrypted);
                    $('#jiami').val(encrypted);
                    
                    //解密
                    var decrypt = new JSEncrypt();
                    decrypt.setPrivateKey($('#privkey').val());
                    var uncrypted = decrypt.decrypt(encrypted);
                    console.log('这是解密后的密文' + uncrypted);
                    $('#jiemi').val(uncrypted);
                });
            });
        </script>

jsencrypt.min.js下载地址:

github主页

官方网站
最终效果:
偏前端 + rsa加解密 + jsencrypt.min.js--(新增超长字符分段加解密)_第1张图片

----新增超长字符分段加解密----
1.首先引入一段转换的js

//十六进制转字节
    function hexToBytes(hex) {
        for (var bytes = [], c = 0; c < hex.length; c += 2)
            bytes.push(parseInt(hex.substr(c, 2), 16));
        return bytes;
    }

// 字节转十六进制
    function bytesToHex(bytes) {
        for (var hex = [], i = 0; i < bytes.length; i++) {
            hex.push((bytes[i] >>> 4).toString(16));
            hex.push((bytes[i] & 0xF).toString(16));
        }
        return hex.join("");
    }

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

你可能感兴趣的:(自用)