过程不复杂, 只是网上结合后端的RSA加解密资料参差不齐, 比较零散, 而且大多博文都是基于最原始的RSA加解密, 当加解密参数过长的时候, 会报[Message too long for RSA]
解决方案, 找了一圈, 都不大完整, 完整的又很复杂, 加了一堆方法, 看着都头疼! 其实加解密的本质都一样的, 无非就是加解的过程问题, 我们知道加密过程, 那解密就是反推的事儿.
在此记录下, 方便自己和有需要的小伙伴能够快速找到! 什么原理什么逻辑就不废话了, 直接上代码!
html
<!DOCTYPE html>
<html>
<head>
<title>aes demo</title>
<meta http-equiv="Content-Type" content="text/html" charset="gbk"/>
<style>
*{margin:0;padding:0}
.demo-wrap{width: 600px;height: 50px;margin: 50px auto auto auto}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js"></script>
<script src="http://passport.cnblogs.com/scripts/jsencrypt.min.js"></script>
</head>
<body>
<div class="demo-wrap">
<div style="padding: 1rem 0">
<button type="button" onclick="rsa_encrypt()">RSA加密</button>
<br/>
加密后的数据:<label id="rsa_encrypted"></label>
</div>
<div>
<button type="button" onclick="rsa_decrypt()">RSA解密</button>
<br/>
解密后的数据:<label id="rsa_decrypted"></label>
</div>
</div>
<script type="text/javascript">
function rsa_encrypt() {
var data = "张三, 你好啊!";
var publicKey = "-----BEGIN PUBLIC KEY-----自己的公钥-----END PUBLIC KEY-----";
var en = new JSEncrypt();
en.setPublicKey(publicKey);
let num = Math.ceil(data.length/117)
let dataArr = [];
for(let i=0;i<num;i++){
if (parseInt(117*(i+1))<=data.length) {
dataArr[i] = data.substring(117*i,117*(i+1));
} else {
dataArr[i] = data.substring(117*i,data.length);
}
dataArr[i] = CryptoJS.enc.Base64.parse(en.encrypt(dataArr[i]));
}
document.getElementById("rsa_encrypted").innerHTML = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Hex.parse(dataArr.join('')));
}
function rsa_decrypt() {
var data = "NdaCEc2HCEgTk1OQoWbfvj0KZwaKTDfn9CSpskkuHYZe2hEW0t72WwmXQOGHoLz9rqSm4uqbYT4uBrCky8WQFZHEdEsIwqk1YK2vatgaRgqb7cW7UxGrxsR8fqtYICTZlfju9TvNWGoTsJVJR+etMiVpEF4kshuKx1V2I9QM8ps=";
data = CryptoJS.enc.Hex.stringify(CryptoJS.enc.Base64.parse(data));
var privateKey = "-----BEGIN RSA PRIVATE KEY-----自己的私钥-----END RSA PRIVATE KEY-----";
var en = new JSEncrypt();
en.setPrivateKey(privateKey);
let num = Math.ceil(data.length/256);
let dataArr = [];
for(let i=0;i<num;i++){
if (parseInt(256*(i+1))<=data.length) {
dataArr[i] = data.substring(256*i,256*(i+1));
} else {
dataArr[i] = data.substring(256*i,data.length);
}
dataArr[i] = en.decrypt(CryptoJS.enc.Base64.stringify(CryptoJS.enc.Hex.parse(dataArr[i])));
}
document.getElementById("rsa_decrypted").innerHTML = dataArr.join('');
}
</script>
</body>
</html>