生成私钥:
openssl genrsa --out rsa_private_key.pem --passout pass:moon --des3 4096
用私钥生成公钥:
openssl rsa --in rsa_private_key.pem --passin pass:moon --pubout --out res_public_key.pem
/**
* openssl
*/
public function openssl(Request $request)
{
$data = $request->input();
// $validate = new Verify();
// if (!$validate->scene('openssl')->check($data)) return jsonx(4001, [], $validate->getError());
$data = [
'return_code' => 'SUCCESS',
'return_msg' => 'OK',
'appid' => 'wxed9eef800fde9990',
'mch_id' => '1544098771',
'nonce_str' => 'NZ9kh5d6MCyXgCbN',
'sign' => '734981E567D9C7A2AB0677BF46782816',
'result_code' => 'SUCCESS',
'prepay_id' => 'wx111542305106719db9106da6395fd50000',
'trade_type' => 'JSAPI',
'time' => '123456',
];
$return = openssl_rsa_decrypt(json_encode($data, 256 + 64));
return (!$return) ? jsonx(4001, [], '加密失败!') : jsonx(2000, ['data' => $return]) ;
}
/**
* openssl加密
* @param data 数据信息
* @param crypted 密码学方式 openssl_get_cipher_methods 有效密码方式列表
* @param key key
* @param options OPENSSL_RAW_DATA
* @param iv 非 NULL 的初始化向量。
* @return array
*/
function openssl_rsa_decrypt($data, $crypted = 'AES-256-CBC', $key = 'SanKang&SanHua', $options = 0, $iv = '!@#$%^&**&^%$233') {
if (!$data) return [];
$list = openssl_get_cipher_methods();
$ivlen = openssl_cipher_iv_length($crypted); // 获取密码初始化向量(iv)长度
$iv = openssl_random_pseudo_bytes($ivlen); // 生成一个伪随机字节串
// AES 加密
$open = openssl_encrypt($data, $crypted, $key, $options, $iv);
// RSA 用公钥去加密
$path = base_path().'/rsa/rsa_private_key.pem';
$pub_key = openssl_pkey_get_private(file_get_contents($path), 'moon');
// RSA 用来加密 AES加密后的数据
$rsa_bool = openssl_private_encrypt($open, $memory, $pub_key);
if (!$rsa_bool) return false;
return base64_encode($memory);
}
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
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