jsencrypt加密解密字符串

用jsencrypt的RSA算法加密解密字符串

前言

首先附上源码的github地址:https://github.com/travist/jsencrypt

使用方法

加密

function rsaEncrypt(msg,key){
    var encrypt = new JSEncrypt();
    encrypt.setPublicKey(key);
    var encryptMsg = encrypt.encrypt(msg);
    return encryptMsg;
}

解密

function rsaDecrypt(msg,key){
    var decrypt = new JSEncrypt();
    decrypt.setPrivateKey(key);
    var decryptMsg = decrypt.decrypt(msg);
    return decryptMsg;
}

如果所用的key为128位,则只能加密117bytes,因此,有时候我们需要分段加密解密

分段加密解密

在源码中加入

    /**
     * encrypt long string
     * @param string
     * @returns {*}
     */
     JSEncrypt.prototype.encryptLong = function(string) {
         var k = this.getKey();
         var maxLength = (((k.n.bitLength()+7)>>3)-11);
 
         try {
             var lt = "";
             var ct = "";
 
             if (string.length > maxLength) {
                 lt = string.match(/.{1,50}/g);
                 lt.forEach(function(entry) {
                     var t1 = k.encrypt(entry);
                     ct += t1 ;
                 });
                 return hex2b64(ct);
             }
             var t = k.encrypt(string);
             var y = hex2b64(t);
             return y;
         } catch (ex) {
             return false;
         }
     };

在加密方法中,将encrypt.encrypt改为encrypt.encryptLong即可

你可能感兴趣的:(JavaScript)