近公司要做个项目要用到RSA加密,所以在网上找了一些博客,并下载了一些demo测试了下,但不太乐观。目前网上的绝大部分博客对超长字符串(117位以上)加密不太支持或者支持的不太好。即使是付费的,也请教不少做前端的朋友都比较少接触,只能自己去探索。
1.我目前是用 jsencrypt.js库来解决这个问题
2.生产公私钥 这一步的话,可以直接 在线生成
3.定义方法 这里需要重新定义两个方法:超长加密(encryptLong2)、超长解密(decryptLong2)
4.完整的demo代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<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>
<br/>
<label for="pubkey">公钥</label>
<br/>
<textarea id="pubkey" rows="15" cols="65">MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC8JU1nBDZ5PgRNAxksTC/MlaBX37vjTH84ppzmuEpH7e6G43QXd7Zof8apIJ4efk6Uiw2/OJfkyMGDsAJTv/zWnuKm6UeyBYxtgP5JFGtTMKTBVuGzH8UzYWdPzybIOCmj55Qku3nYEZyro38dGhSFLSPaU3eoY1tblm5ZFJ+8ewIDAQAB</textarea>
<br/>
<label for="input">要加密的字符串:</label>
<br/>
<textarea id="input" name="input" type="text" rows='4' cols='70'>123456789</textarea>
<br/>
<input id="testme" type="button" value="Test Me!!!" />
<br/>
<label for="jiami">加密后的密文:</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>
<script type="text/javascript">
$(function() {
$('#testme').click(function() {
// 进行RSA加密
var encrypt = new JSEncrypt();
//获取公钥
encrypt.setPublicKey($('#pubkey').val());
//公钥加密
var encrypted = encrypt.encryptLong2($('#input').val());
// 加密后的密文
$('#jiami').val(encrypted);
//解密
var decrypt = new JSEncrypt();
//获取私钥
decrypt.setPrivateKey($('#privkey').val());
//解药
var uncrypted = decrypt.decryptLong2(encrypted);
$('#jiemi').val(uncrypted);
});
});
</script>
<script>
// Convert a hex string to a byte array
function hexToBytes(hex) {
for (var bytes = [], c = 0; c < hex.length; c += 2)
bytes.push(parseInt(hex.substr(c, 2), 16));
return bytes;
}
// Convert a byte array to a hex string
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("");
}
//方法一
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;
}
};
</script>
</body>
</html>