【问题标题】:PHP Encrypt/Decrypt using OpenSSL not working for me使用 OpenSSL 的 PHP 加密/解密对我不起作用
【发布时间】:2012-08-16 11:59:01
【问题描述】:

我正在尝试使用 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;

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

【问题讨论】:

  • 首先,检查所有变量的值,确保它们包含您认为它们应该包含的内容:)
  • @Jack Cheers 是的,我认为一切都应该如此。据我所知,它只是拒绝解密数据。我在这里粘贴了一个示例:pastebin.com/HMGg7FSg

标签: php openssl


【解决方案1】:

你忘了这句话吗?

$env_key = $ekeys[0];

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

【讨论】:

  • 是的!信封钥匙,就是这样,非常感谢!我希望有关于该功能描述的更好的文档
猜你喜欢
  • 1970-01-01
  • 2023-04-03
  • 2018-12-04
  • 2019-04-13
  • 2012-09-16
  • 2014-02-24
  • 2022-12-11
  • 2014-02-17
  • 1970-01-01
相关资源
最近更新 更多