jsencrypt是一jquery款字符串加密解密插件。
<h2>第一步:获取公钥</h2>
<button id="getKey">点击获取公钥</button><hr/>
<h2>第二步:将本地数据加密后,在远程进行解密</h2>
<input id="dataText1" placeholder="本地数据"/>
<button id="sendButton">发送</button>
<input id="dataText2" placeholder="远程解密"/>
(function(window) {
'use strict';
var rsa = function(params) {
$.extend(this.params, params);
this._init();
};
rsa.prototype = {
params: {publicKey: '',},
_init: function() {
var that = this;
that.getKeyClick();
that.sendButton();
},
/** * 获取公钥 */
getKeyClick: function() {
var that = this;
$('#getKey').click(function() {
$.get('testrsa.php', {act: 'get'}, function (result) {
result = $.parseJSON(result);
// 保存公钥
that.params.publicKey = result['publicKey'];
});
});
},
/** * 发送测试数据 */
sendButton: function() {
var that = this;
$('#sendButton').click(function() {
var dataText1 = $('#dataText1').val();
// step1:本地加密
var encrypt = new JSEncrypt();
encrypt.setPublicKey(that.params.publicKey);
var encrypted = encrypt.encrypt(dataText1);
console.log(encrypted);
// step2:服务器上私钥解密
$.get('testrsa.php', {act: 'data',dataText: encrypted}, function (result) {
result = $.parseJSON(result);
console.log(result['code']);
console.log(result['decrypted']);
$('#dataText2').val(result['decrypted']);
});
});
}
};
window.rsa = rsa;
})(window);
官方文档 : http://travistidwell.com/jsencrypt/
Github 地址 :https://github.com/travist/jsencrypt
效果演示 : http://travistidwell.com/jsencrypt/demo/index.html