Eli*_*uni 6 php encryption openssl private key
好吧,这是我第一次在项目上使用加密.我正在使用我的托管服务提供商进行SSL,但我也想加密敏感数据库的部分内容.为此,我被告知要使用OpenSSL.我在我的localhost(WAMP)上测试它,并安装了OpenSSL并打开了PHP和Apache SSL mods.好的,所以我一直在关注教程,并使用几种建议的方法,能够生成公钥并将其存储为文件.出于某种原因,我似乎无法生成私钥.我将发布我尝试过的两个版本的代码:
// generate private key
$privateKey = openssl_pkey_new(array(
'private_key_bits' => 1024,
'private_key_type' => OPENSSL_KEYTYPE_RSA,
));
// write private key to file
openssl_pkey_export_to_file($privateKey, 'private.key');
// generate public key from private key
$publicKey = openssl_pkey_get_details($privateKey);
// write public key to file
file_put_contents('public.key', $publicKey['key']);
// clear key
echo $privateKey;
?>
Run Code Online (Sandbox Code Playgroud)
这会生成一个public.key文件,但是会向我提供警告"openssl_pkey_export_to_file():无法从参数1获取密钥:"和"openssl_pkey_get_details()期望参数1是资源,布尔值."
我也尝试了另一种方法:
$config = array(
"config" => "E:/wamp/bin/apache/apache2.2.22/conf/openssl.cnf",
"digest_alg" => "sha512",
"private_key_bits" => 1024,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
);
// Create the private and public key
$res = openssl_pkey_new($config);
// Extract the private key from $res to $privKey
openssl_pkey_export($res, $privKey, NULL);
echo "Private Key: ".$privKey;
// Extract the public key from $res to $pubKey
$pubKey = openssl_pkey_get_details($res);
$pubKey = $pubKey["key"];
echo "Public Key: ".$pubKey;
$data = 'plaintext data goes here';
echo "Data: ".$data;
// Encrypt the data to $encrypted using the public key
openssl_public_encrypt($data, $encrypted, $pubKey);
echo "Encrypted: ".$encrypted;
// Decrypt the data using the private key and store the results in $decrypted
openssl_private_decrypt($encrypted, $decrypted, $privKey);
echo "Decrypted: ".$decrypted;
Run Code Online (Sandbox Code Playgroud)
这应该是回应一切,不幸的是我的结果是一个空白的私钥,一个好的公钥,明文和加密的文本,并在尝试解密时出错:"openssl_private_decrypt():key参数不是有效的私钥"
很明显,我在创建私钥时遇到了问题.虽然我已经实现了似乎适用于其他人的简单代码,但我已经彻底搜索了互联网并且无法修复它.
在此先感谢Elie Zeitouni
我知道它已经有一段时间了,你可能已经解决了它,但我认为我的答案可能对其他遇到同样问题的人有所帮助(就像我做的那样).
因此,如果您查看openssl_pkey_export()文档,您会发现它需要四个不同的参数.如果我们看一下你的第二个实现,我们可以看到你只提供了三个.
openssl_pkey_export($ res,$ privKey,NULL);
如果只有您的服务器具有适用于OPENSSL_CONF的环境变量,那么这样就可以了.链接到openssl.cnf文件,该文件在使用XAMPP下载的README-SSL.txt文件中引用,需要使用PHP中的CSR和密钥生成函数.
要使用PHP中的CSR和密钥生成功能,您需要安装openssl.cnf文件.我们在此自述文件旁边包含了一个可用于此目的的示例文件.
出于这个原因,就像你为此所做的那样,openssl_pkey_new($config);你必须创建一个包含config =>'/ path/to/openssl.cnf'的关联数组.像这样:
openssl_pkey_export($res, $privKey, NULL, $config);
Run Code Online (Sandbox Code Playgroud)
我想补充一点,在我的情况下openssl.cnf的路径是在里面:
C:\ XAMPP\PHP \演员\ OpenSSL的\ openssl.cnf中
在这里,您还可以找到README-SSL.txt文件,该文件很好地解释了如何配置OPENSSL.
希望能帮助到你.:)
我认为您可能会更轻松地使用phpseclib(一个纯 PHP RSA 实现)。以下示例将创建一个 1024 位 RSA 私钥/公钥:
<?php
include('Crypt/RSA.php');
$rsa = new Crypt_RSA();
extract($rsa->createKey());
echo $privatekey . '<br/>' . $publickey;
?>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6619 次 |
| 最近记录: |