本文实例作者:冀云
本文整理作者:杨红伟
(一)官方地址:
https://github.com/travist/jsencrypt
(二)本站代码
本站代码
https://gitee.com/hongweizhiyuan/ijquery/tree/master/signature
本站测试及调试
http://www.ijquery.cn/plugin/jsencrypt/rsa.html
原理:
(三)最简DEMO
1、HTML
<h2>第一步:获取公钥</h2>
<button id="getKey">点击获取公钥</button>
<hr/>
<h2>第二步:将本地数据加密后,在远程进行解密</h2>
<input id="dataText1" placeholder="本地数据"/>
<button id="sendButton">发送</button>
<input id="dataText2" placeholder="远程解密"/>
2、JS
(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);
3、PHP
<?php
require_once('test.php');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');
$key = array();
$act = $_REQUEST['act'];
$rsa = new Rsa();
session_start();
if ( $act == 'get' ) {
$key = $rsa->getKeys();
$arr = array('code'=>200, 'publicKey'=>$key['publicKey']);
// echo $key['publicKey'];
echo json_encode($arr);
$_SESSION['publickey'] = $key['publicKey'];
$_SESSION['privateKey'] = $key['privateKey'];
} else if ( $act == 'data' ) {
$dataText = $_REQUEST['dataText'];
$decrypted = $rsa->decrypt($dataText, $_SESSION['privateKey']);
$arr = array('code'=>200, 'decrypted'=>$decrypted);
echo json_encode($arr);
}