【发布时间】:2013-05-27 20:21:17
【问题描述】:
好的,这是我第一次在项目中使用加密。我正在使用我的托管服务提供商进行 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;
?>
这会生成一个 public.key 文件,但会向我提供警告“openssl_pkey_export_to_file(): cannot get key from parameter 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;
这应该回显所有内容,不幸的是我的结果是一个空白的私钥,一个很好的公钥,明文和加密文本,并且在尝试解密时出错:“openssl_private_decrypt(): key parameter is not a valid private钥匙”
显然,我在创建私钥时遇到了问题。尽管我已经实现了似乎对其他人都有效的简单代码,但我已经彻底搜索了互联网并且无法修复它。
提前致谢, Elie Zeitouni
【问题讨论】:
-
你检查过函数的返回值吗?
-
我最近在将项目更新到 PHP 7.3 时遇到了这个问题,结果证明是密钥大小太小 - 小于 512 位不起作用,这导致一些测试用例使用较小的值会失败并显示此消息。
标签: php encryption openssl key private