复制代码
1 <?php
2 /**
3 * Created by PhpStorm.
4 * User: hanks
5 * Date: 6/2/2017
6 * Time: 6:03 PM
7 /
8 //使用php函数生成密钥对
9 //openssl模块提供了很多openssl相关的函数,参考手册 生成密钥对的方法如下:
10 $privateKey = openssl_pkey_new([
11 'private_key_bits' => 2048, // private key的大小
12 'private_key_type' => OPENSSL_KEYTYPE_RSA,
13 ]);
14
15 openssl_pkey_export_to_file($privateKey, 'php-private.key');
16 $key = openssl_pkey_get_details($privateKey);
17 file_put_contents('php-public.key', $key['key']);
18
19 openssl_free_key($privateKey); // 释放资源
复制代码
复制代码
1 <?php
2 /*
3 * Created by PhpStorm.
4 * User: hanks
5 * Date: 6/8/2017
6 * Time: 12:20 PM
7 /
8 //使用密钥对加密数据
9 //使用第一步的php函数生成的公钥对一段明文进行分段(chunk)再分段加密,(实际使用中也可以直接全部文本加密):
10 //$plain = 'this is a 测试的数据';
11 $plain = [
12 0=>[
13 '0'=>'sd',
14 '1'=>'使得'
15 ],
16 1=>[
17 '0'=>'sd2',
18 '1'=>'使得2'
19 ],
20 ];
21 echo 'plian text: ' . json_encode($plain,true);
22 $plain = gzcompress(json_encode($plain,true)); // compress data
23 $pubkeyStr = file_get_contents('./php-public.key');
24 $publicKey = openssl_pkey_get_public($pubkeyStr);
25
26 $p_key = openssl_pkey_get_details($publicKey);
27 $chunkSize = ceil($p_key['bits'] / 8) -11; // 这里不知道为什么要-11,后面追加解释
28
29 $output = '';
30
31 while ($plain) {
32 $chunk = substr($plain, 0, $chunkSize);
33 $plain = substr($plain, $chunkSize);
34
35 $encrypted = '';
36 if ( !openssl_public_encrypt($chunk, $encrypted, $publicKey)) {
37 die("failed to encrypt data");
38 }
39 $output .= $encrypted;
40 }
41 openssl_free_key($publicKey);
42 $output = base64_encode($output);
43 echo 'encrypted: ' . ($output);
44 file_put_contents('./enc.data', $output);
复制代码
复制代码
1 <?php
2 /*
3 * Created by PhpStorm.
4 * User: hanks
5 * Date: 6/8/2017
6 * Time: 12:22 PM
7 */
8 //解密数据
9 //使用私钥对数据进行解密:
10 $keyStr = file_get_contents('./php-private.key');
11 if (!$privateKey = openssl_pkey_get_private($keyStr)) {
12 die('get private key failed');
13 }
14
15 $encrypted = file_get_contents('./enc.data');
16 echo 'encrypted data: ' . $encrypted;
17
18 $encrypted = base64_decode($encrypted);
19
20 $p_key = openssl_pkey_get_details($privateKey);
21 $chunkSize = ceil($p_key['bits'] / 8);
22 $output = '';
23
24 while ($encrypted) {
25 $chunk = substr($encrypted, 0, $chunkSize);
26 $encrypted = substr($encrypted, $chunkSize);
27 $decryptd = '';
28 if (!openssl_private_decrypt($chunk, $decryptd, $privateKey)) {
29 die('failed to decrypt data');
30 }
31 $output .= $decryptd;
32 }
33 openssl_free_key($privateKey);
34 $output = gzuncompress($output);
35 echo "
decrypted data: ";
36 var_dump(json_decode($output,true));