使用 OpenSSL 的 PHP 加密/解密对我不起作用

标签 php openssl

我正在尝试使用 PHP 和 OpenSSL 使用公钥加密一些数据,然后再次解密。

我使用以下代码生成了 public.key 和 private.key:

// 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
openssl_free_key($privateKey);

我的加密和解密代码基本上直接来自 PHP 文档:

// data to encrypt
$data = "This is a long string or other bit of data that i want to encrypt";

// ==== ENCRYPT ====

// read public key
$publicKey =  file_get_contents("public.key");
$publicKey = openssl_get_publickey($publicKey);

// encrypt data using public key into $sealed
$sealed = '';
openssl_seal($data, $sealed, $ekeys, array($publicKey));
openssl_free_key($publicKey);

// ==== DECRYPT ====

// get private key to decrypt with
$privateKey = file_get_contents("private.key");
$privateKey = openssl_get_privatekey($privateKey);

// decrypt data using private key into $open
$open = '';
openssl_open($sealed, $open, $env_key, $privateKey);
openssl_free_key($privateKey);


// display decrypted data:
echo "<p>Decrypted data: ".$open;

有人知道它为什么不起作用,或者至少有办法找出发生了什么错误吗?

最佳答案

你忘了这句话吗?

$env_key = $ekeys[0];

我通过阅读 openssl_seal() 的示例代码找到了答案。

关于使用 OpenSSL 的 PHP 加密/解密对我不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11986604/

相关文章:

c - 使用 OpenSSL API 以编程方式验证证书链

php - 通过 PHP SDK 的 S3 客户端初始化错误

PHP SOAP 请求

php - 如何在我的历史日志中隐藏 OpenSSL 使用的密码?

c - 为什么未初始化的内存可以安全地用于 OpenSSL 的随机数生成器?

c - 使用管道在 C 中写入 openssl 的 stdio

php - PHP-MYSQL SELECT 查询时间长

php - SQL 值被更改为 1 而不是给定的值

php - 将xml转换为json时出现parsererror

tomcat - 如何将 OpenSSL 的密码列表映射到 Java JSSE