簡體   English   中英

PHP:openssl_private_decrypt():key 參數不是有效的私鑰

[英]PHP: openssl_private_decrypt(): key parameter is not a valid private key

我有這個代碼來創建一個 RSA 4096 公鑰和私鑰來加密和解密一個字符串。

代碼:

<?php
$config = array(
    "config" => "C:/xampp/php/extras/openssl/openssl.cnf",
    "private_key_bits" => 4096,
    "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);

// Extract the public key from $res to $pubKey
$pubKey = openssl_pkey_get_details($res);
$pubKey = $pubKey["key"];

$data = 'Hello, World!';

// Encrypt the data to $encrypted using the public key
openssl_public_encrypt($data, $encrypted, $pubKey);

echo $encrypted;

// Decrypt the data using the private key and store the results in $decrypted
openssl_private_decrypt($encrypted, $decrypted, $privKey);

echo $decrypted;
?>

它創建密鑰,加密data字符串( Hello, World! )但是當嘗試解密encrypted字符串時,會發生錯誤:

警告:openssl_private_decrypt(): key parameter is not a valid private key in C:\\xampp\\htdocs\\rsa\\index.php26

好的,這對我有用:

更改openssl_pkey_export($res, $privKey); openssl_pkey_export($res, $privKey, NULL, $config); .

您不需要像那樣導出密鑰私有,至少在您將其保存在安全的地方之前不需要:

$config = array(
    "private_key_bits" => 4096,
    "private_key_type" => OPENSSL_KEYTYPE_RSA
);

$pki     = openssl_pkey_new($config);
$public  = openssl_pkey_get_public(
    openssl_pkey_get_details($pki)['key']
); // why on earth did they implement it like this? so clunky.
$private = openssl_pkey_get_private($pki);

$data = 'Hello, World!';

openssl_public_encrypt($data, $encrypted, $public);
openssl_private_decrypt($encrypted, $decrypted, $private);

var_dump(
    bin2hex($encrypted),
    $decrypted
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM