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