rsatitle

rsa的js加密和php解密
群里的同志需要的前端js加密,后端php解密的实例

开始说明

后面有一个实例

javascript加密

引入相关的js库

jsbn.js ,

prng4.js ,

rng4.js ,

rsa.js ,

base64.js

他们的远程目录为: http://www-cs-students.stanford.edu/~tjw/jsbn/

前端代码:

1
2
3
4
5
<script src="http://www-cs-students.stanford.edu/~tjw/jsbn/jsbn.js"></script>
<script src="http://www-cs-students.stanford.edu/~tjw/jsbn/prng4.js"></script>
<script src="http://www-cs-students.stanford.edu/~tjw/jsbn/rng.js"></script>
<script src="http://www-cs-students.stanford.edu/~tjw/jsbn/rsa.js"></script>
<script src="http://www-cs-students.stanford.edu/~tjw/jsbn/base64.js"></script>

本 blog 也拷贝了这几个库,网址的目录为: http://blog.lopy.win/assets/rsa/ ,将几个文件名加在后面就可以了。

github地址:https://github.com/uljjmhn520/uljjmhn520.github.io/tree/master/assets/rsa

1
2
3
4
5
6
7
8
9
<!-- jquery 方便dom操作 -->
<script src="//cdn.bootcss.com/jquery/2.1.3/jquery.min.js"></script>

<!-- 本blog的js文件 -->
<script src="http://blog.lopy.win/assets/rsa/jsbn.js"></script>
<script src="http://blog.lopy.win/assets/rsa/prng4.js"></script>
<script src="http://blog.lopy.win/assets/rsa/rng.js"></script>
<script src="http://blog.lopy.win/assets/rsa/rsa.js"></script>
<script src="http://blog.lopy.win/assets/rsa/base64.js"></script>

test —————–

test —————– end

js代码第一部分

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//创建一个rsa类,只有一个加密方法,构造函数为公钥中的 n 和 e 也就是模和指数。
var MyRsa = function(module,eVal){
module = module || '';
eVal = eVal || '010001';
var rsaObj = new RSAKey();

//构造函数
var init = function(module,eVal){
if(module){
rsaObj.setPublic(module,eVal);
}
};
init(key,eVal);

//加密
this.encrypt = function(str){
var strEncoded = rsaObj.encrypt(str);
if(!strEncoded){
alert('hello what\'s your name');
return false;
}
return hex2b64(strEncoded);
}
}

js代码第二部分

1
2
3
4
5
6
7
8
9
10
11
12
//n和e为rsa的模和指数,他们的值是从密钥对中获得的,后文会给出php 中获取的方法

var n ="E0F1E67A3E1E54B1820A481F1DFC98545542B85EAEC149627591593C19A25B3B6CDAAA9346D83EF695193FA268E3ED27C9B57DCFB5B6FB873D646FA3947105E4ACF07EDF623D321881D8930E0CFD391191F2EB3B3EB3DF2409F25B96B2BD4C5D2EAF42B43059D2FDDBAF5BE51E7F66E69B617FE319DFC2AD2567A841D765EB0DF5BAB631146EB6FD5688028658A0AEAF1CBD470BF437BCFA6641159E8C2F857B0C7D806326C6D3037DEAD1EC463673E0CA30D51EAF7F70EB7AFD46A765FB5FB4C89791A4CF4C4072E4D29D5DEDE90D75DC2D9669AEB888133F349179264EFF2DF0BCEFDA11FDAC32B57F75E2D2072ADC117DDAC3BEA8F431253228594BF0419B";
var e = '010001';

var myRsa = new MyRsa(n,e);
var encoded = myRsa.encrypt('hello world');
console.log(encoded);

// result,以下为结果之一,每次加密的结果都可能不一样

// XJJeZhc4tYp50OXDAyBS6aK0lWOPNR6IVOM4auccxb+uk0+d5GewFq9ffAWhlBpAiRTuo1IbKm8e23UdU3kbIFs9nNAMCSdj/2FL3C9NrXlW67Jfs6azAMHMHKW3f3rXPCRMTvFGq09KdobwLiy71GidRZtbQYQEaZ8QhHpZC/QYem9EAdu4ULdBX5e1uigIPm3ukzK6RUKRbBYM44ApoL6kNUdbELvC2J6psqs1YxprwAw9D5C8N41tWFRwx7MIPx83TG8aGYDCU/q1E5Xd7fDpXlm4gZxPPXMHwIT4WJBvzDZoCCpxJSEYEzHzfF6HTTWcWo8BBbUeC8qssCHiyA==

php解密

私钥

解密用的私钥,与加密用的公钥为一对。

密钥对用php函数 openssl_pkey_newopenssl_pkey_export 生成;公钥可用已存在的私钥生成,后文中会介绍

以下为某一个私钥

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG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RS/4SzfivYiO6B27u
aon8174Us7cCgYAYDsjOxV9wwtV/JXcfkRheZqGnWlOOCuW+Xp0+b+IdV0w0/TY+
M+iYtmV0n/k3sK8p907ib8ftQ/stXYJ5BBUI61iPZHUSjZUC+dbn3oEDj7i7APfW
FP7zwoeun8ao4J9oPb+BfmVlQ7CRKlND8Srgqq9Dgc2PWWWQr9GayuksjQKBgQCM
Vr2vK+LUPGJxefl+nnkg2c954ZPm7T0IOe1MbVikuHXXtKOALmKBK3ojxSfX3vsG
uD2PdvGKR5LaoxUSEO16KN4J+OwBWXPE3iFUIm+GjhR/Y7z4UBWV2anEAPrZ47gU
G8hxNq9TKUALhy4lPJHGRgIWbr0OzNX0gbMnluaQcQKBgDyQeTvFpPuziNltPVm0
BEbD6mSgHTky1i5w/k2UiR72tUHb3ekx98fPc0YHqczYbc7l8vP7mDO0+ZmtdFmq
JjcixY3ZlvWeVjZ/QlI7wpgCy5hsgSRnxdy94IrLhrA5zlL0dDC0mAVzTPzJltIX
QrbpjdKjcOCrdDny0WUw+OX4
-----END PRIVATE KEY-----

php代码部分

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 上文中的私钥
$privateStr = '<<<privateKey'
xxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxx
privateKey;

$pKey = openssl_pkey_get_private($privateStr);

//encoded 为 上文js加密后的密文
$encoded = base64_decode($encoded);

//解密
openssl_private_decrypt($encoded,$decrypted,$pKey,OPENSSL_PKCS1_PADDING);

echo $decrypted;
//如果一切正常的话,就能解密出结果 hello world

一些说明

官方说明

php的openssl 扩展官网 点击进入

创建密钥对

1
$ssl = openssl_pkey_new([]);

提取私钥

1
2
3
4
5
6
7
8
9
10
11
12
openssl_pkey_export($res, $privKey);


echo $privKey;

//privKey 就为私钥 格式为
// -----BEGIN PRIVATE KEY-----
// xxxxxxxxxx
// xxxxxxxxxx
// xxxxxxxxxx
// xxxxxxxxxx
// -----END PRIVATE KEY-----

获取detail,包括公钥、模、指数等信息

方式一,从密钥对里面提取

1
2
3
4
5
6
7
8
9
10
11
12
13
//获取detail
$detail = openssl_pkey_get_details($ssl);

//公钥
$publicKey = $detail['key'];

//模,值为二进制乱码,转为16进制
$module = $detail['rsa']['n'];
$module = bin2hex($module);

//指数,值为二进制乱码,转为16进制
$exponent = $detail['rsa']['e'];
$exponent = bin2hex($exponent); //一般结果为 010001 (65537)

方式二,从私钥里提取

1
2
3
4
5
//获取detail
$privateKeySource = openssl_get_privatekey($privKey);
$detail = openssl_pkey_get_details($privateKeySource);

//后面取模、指数等信息同 方式一

方式三,从公钥里提取

1
2
3
4
5
6
//$publicKey 为方式一中提取的 publicKey 
$publicKeySource = openssl_get_publickey($publicKey);
$publicKeyDetail = openssl_pkey_get_details($publicKeySource);

//后面取模、指数等信息同方式一
//从公钥里面提取的 detail 的内容较少

解密

1
2
3
4
5
6
7
8
9
10
// $encoded 为已被加密的密文
$encoded = base64_decode($encoded);

//私钥
$pKey = openssl_pkey_get_private($privKey);

//私钥解密
openssl_private_decrypt($encoded,$decoded,$pKey,OPENSSL_PKCS1_PADDING);

echo $decoded;

完整的实例

说明

以下内容基于 phalcon 的 controller ,如果你没有使用phalcon,可能会修改一部分代码

controller里面有三个action

index:html 页面,包括js加密部分

decode:php 解密部分,接收post数据,与页面index 的ajax交互

create:展示了创建密钥对

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
<?php
/**
* @brief
* Created by PhpStorm.
* User: zy&cs
* Date: 17-3-2
* Time: 上午11:47
*/
namespace App\Modules\Tester\Controllers;

class RsaController extends ControllerBase
{

/**
* 内置了几个私钥,用该方法获取一个,
*
* 可以自己用 createAction 自己往后面加,实际操作中用缓存或数据库就能解决了
*
*
* @param bool|int $key 默认取第一个,$key === false 时,取所有
* @return array
*/
private function rsaPrivateKey($key=false)
{
$rsaKeys = [];

$rsaKeys[0] = <<<rsakey
-----BEGIN PRIVATE KEY-----
MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDMYA9a+x7XxFh8
Ihk9EK+6N0xZNq8qhBH5jypFO7zVvOHYPDjr1OAoKXYESDF5Yk+bbivX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akey;

$rsaKeys[5] = <<<rsakey
-----BEGIN PRIVATE KEY-----
MIIBFAIBADANBgkqhkiG9w0BAQEFAASB/zCB/AIBAAIzAVKoys24WgfliPeAh2LH
vhFEQ1KmxEETTrOwjSLtYFgA6opEvcND4Hie61syD3i/g7sBAgMBAAECMwDfbilP
DH+pkhCJaizoSOvnLGhWUVxNqtVSKTXJX/Nri/a5Ye3sr+ZZIaCcxZCeBOejIQIa
AbPKiMN2IzV+WpDMr9zspM1Khz2Hy3y0hKUCGgDG8O8syaInZ7/qdrn2/1TIuZkO
CkE4+KItAhlgyLtlBai+Kai9fegU3a2gNkwg2zbTJFhNAhkyNURnrUu7XjfVWLl+
WNpw/kZegMANPNLRAhoBgZPB6KHFUtqcodgnJvRkyt8wVlUk0Lx6Qg==
-----END PRIVATE KEY-----
rsakey;



if($key === false){
return $rsaKeys;
}

if (!isset($rsaKeys[$key])) {
$key=0;
}

return $rsaKeys[$key];
}

/**
* @param $id
* @return array
*/
private function getDetailFromPKId($id)
{
$key = $this->rsaPrivateKey($id);
$resource = openssl_get_privatekey($key);
return openssl_pkey_get_details($resource);;
}


private function getHtml($keyId,$rsaModule,$rsaExponent)
{

//rsa 的那几个js
$rsaAssets = [
'jsbn.js',
'prng4.js',
'rng.js',
'rsa.js',
'base64.js',
];
$rsaJsPre = 'http://blog.lopy.win/assets/rsa/';
$rsaJs = '';
foreach($rsaAssets as $val){
$rsaJs .= '<script src="' . $rsaJsPre . $val . '"></script>';
}


//切换 privateKey
$switchStr = '';
foreach($this->rsaPrivateKey() as $key=>$val)
{
$switchStr .= '<li><a href="index?key_id=' . $key . '">密钥 - ' . $key . ' </a></li>';
}


//密钥长度
$moduleLength = strlen($rsaModule) * 8 / 2; //为毛要除以2 ,因为 bin2hex 后,长度为两倍

//html 代码
$html = <<<html
<html>
<head>
<script src="//cdn.bootcss.com/jquery/2.1.3/jquery.min.js"></script>

$rsaJs

</head>
<body>
<script>
//class rsa
var MyRsa = function(key,eVal){
key = key || '';
eVal = eVal || '010001';
var rsaObj = new RSAKey();

var init = function(key,eVal){
if(key){
rsaObj.setPublic(key,eVal);
}
};

this.encrypt = function(str){
var strEncoded = rsaObj.encrypt(str);
if(!strEncoded){
alert('hello what\'s your name');
return false;
}
return hex2b64(strEncoded);
}
init(key,eVal);
}
function submitCheck(){
var rsaModule = "$rsaModule";
var rsaExponent = "$rsaExponent";

var myRsa = new MyRsa(rsaModule,rsaExponent);
$("[name=input]").val(myRsa.encrypt($("#input").val()));
var url = "decode";
var data ={
key_id:$("[name=key_id]").val(),
input:$("[name=input]").val(),
};
$.post(url,data,function(json){
if(json.flag ===0){
$('#decoded').val(json.decoded);
}else{
alert(json.msg);
}
});
return false;
}
</script>
<style>
input.full{
width: 100%;
}
</style>

<ul>$switchStr</ul>

<form action="#" method="post">
<ul>
<input type="hidden" name="key_id" value="$keyId">

<li></li>
<li>密钥长度</li>
<li>
<input type="text" readonly value="$moduleLength" class="full">
</li>
<li></li>
<li>模(n)</li>
<li>
<input type="text" readonly value="$rsaModule" class="full">
</li>
<li></li>
<li>指数(e)</li>
<li>
<input type="text" readonly value="$rsaExponent" class="full">
</li>
<li></li>
<li>输入要加密的字符串:</li>
<li>
<input type="text" id="input" class="full">
</li>
<li></li>
<li>js加密后</li>
<li>
<input type="text" name="input" readonly class="full">
</li>

<li></li>
<li>php解密后</li>
<li><input type="text" id="decoded" readonly class="full"></li>
<li></li>
<li>
<button type="submit" onclick="return submitCheck();">encode && decode</button>
</li>
</ul>

</form>
</body>
</html>
html;
return $html;
}

/**
*
* @return bool
*/
public function indexAction()
{
$keyId = $this->request->get('key_id','int',0);
$keyId = $keyId < 0 ? 0 : $keyId;

//取一个私钥 private key
$detail = $this->getDetailFromPKId($keyId);

//取得该密钥对的 模 和指数,也是 n 和 e
$rsaModule = strtoupper(bin2hex($detail['rsa']['n']));

$rsaExponent = bin2hex($detail['rsa']['e']);

//输出html
echo $this->getHtml($keyId, $rsaModule, $rsaExponent);

return false;
}


/**
* @return bool
*/
public function decodeAction()
{
//post 参数
$keyId = $this->request->getPost('key_id', 'int', 0);
$input = $this->request->getPost('input', ['string', 'trim'], '');
$json = [
'flag' => 1,
'msg' => ''
];


if($keyId < 0){
$json['msg'] = 'what\'s your name?';
}else if(!$input){
$json['msg'] = 'how old are you';
}else{
$str = base64_decode($input);

//私钥
$pKey = openssl_pkey_get_private($this->rsaPrivateKey($keyId));

//私钥解密
openssl_private_decrypt($str,$decrypted,$pKey,OPENSSL_PKCS1_PADDING);

//结果
$json['flag'] = 0;
$json['decoded'] = $decrypted;
}

$this->response->setJsonContent($json);
return false;
}


//test
public function createAction()
{
echo '<pre>';
//创建密钥对
//$rsaPair = openssl_pkey_new([]);

$rsaPair = openssl_pkey_new([
'private_key_bits'=>401
]);

//get 私钥
openssl_pkey_export($rsaPair, $privateKey);

var_dump($privateKey);

// get detail of private key
//array(
// bits 位数
// key 公钥
// rsa => array(
// n 模
// 。。。。。。
// )
// type
//)
$privateKeyDetail = openssl_pkey_get_details($rsaPair);

/*
//这样也行,两种方法
$privateKeySource = openssl_get_privatekey($privateKey);
$privateKeyDetail = openssl_pkey_get_details($privateKeySource);
*/

//get 公钥 public key
var_dump($privateKeyDetail['key']);


var_dump('------------------------------------------ private key start ------------------------------------------');
//模 n ,一般用hex 显示
var_dump(strtoupper(bin2hex($privateKeyDetail['rsa']['n'])));
//指数 e

var_dump(bin2hex($privateKeyDetail['rsa']['e']));

var_dump(strtoupper(bin2hex($privateKeyDetail['rsa']['d'])));

var_dump('------ p and q ------');
var_dump((bin2hex($privateKeyDetail['rsa']['p'])));
var_dump((bin2hex($privateKeyDetail['rsa']['q'])));

var_dump('------------------------------------------ private key end ------------------------------------------');
var_dump('');


var_dump('------------------------------------------ public key start ------------------------------------------');
//也可以用public key 获取 detail
//public 的 detail 里面的 rsa 的东西要少些
$publicKeySource = openssl_get_publickey($privateKeyDetail['key']);
$publicKeyDetail = openssl_pkey_get_details($publicKeySource);

var_dump(strtoupper(bin2hex($publicKeyDetail['rsa']['n'])));
var_dump(bin2hex($privateKeyDetail['rsa']['e']));

var_dump('------------------------------------------ public key end ------------------------------------------');
var_dump($publicKeyDetail);


echo '</pre>';
return false;

}
}

引用

0%