代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.bootcss.com/jsencrypt/3.0.0-rc.1/jsencrypt.min.js"></script>
<script>
$(document).ready(function(){
$("#tran").click(function(){
$("#content").empty()
var a = new JSEncrypt()
var pubk = $("#pubk").val()
a.setPublicKey(pubk);
var ss = ""
var str = $("#str").val()
$("#strlen").val(str.length)
while(str.length>37){ //RSA一次加密不要超过127字节,前台验证中文字符长度37位内,ascii可更长
var temp = str.substr(0,37)
ss+= '.'+a.encrypt(temp)
str = str.substr(37)
}
ss+= '.'+a.encrypt(str)
ss = ss.substr(1)
$("#content").append(ss)
})
})
</script>
<style>
div{
width: 90%;
margin: 10px auto;
float: left;
}
label{
width: 100px;
}
</style>
</head>
<body>
<div>
<label for="pubk">公钥</label>
<input type="text" id="pubk" style="width:50%">
</div>
<div>
<label for="str">原字符</label>
<input type="text" id="str">
<button id="tran">转化</button>
</div>
<div>
<label for="str">长度</label>
<input type="text" id="strlen">
</div>
<div>
<label for="content">加密后字符</label>
<textarea id="content" rows="5" style="width: 50%;word-break:break-all">
</textarea>
</div>
</body>
</html>
public static String decrypt(String privateKey,String str) throws Exception{
//base64编码的私钥
byte[] decoded = Base64.decodeBase64(privateKey);
RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
//RSA解密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, priKey);
StringBuffer sb = new StringBuffer();
String[] strArr = str.split(".");
for(String content :strArr) {
//64位解码加密后的字符串
byte[] inputByte = Base64.decodeBase64(content.getBytes("UTF-8"));
sb.append(new String(cipher.doFinal(inputByte)));
}
return sb.toString();
}