<?php
    ini_set('display_errors', 1);

    $config = array(
        "config" => "C:\wamp\bin\apache\Apache2.4.4\conf\openssl.cnf",
        "private_key_bits" => 2048,
        "private_key_type" => OPENSSL_KEYTYPE_RSA,
    );

    // Create the private and public key
    $res = openssl_pkey_new($config);

    if ($res === false) die('Failed to generate key pair.'."\n");

    if (!openssl_pkey_export($res, $privKey, "phrase", $config)) die('Failed to retrieve private key.'."\n");

    // Extract the private key from $res to $privKey
    openssl_pkey_export($res, $privKey, "phrase", $config);

    echo "<br/>";
    echo "Private Key = ".$privKey;
    echo "<br/>";

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

    echo "<br/>";
    echo "Public Key = ".$pubKey;
    echo "<br/>";

    $data = 'plaintext data goes here';

    // Encrypt the data to $encrypted using the public key
    openssl_public_encrypt($data, $encrypted, $pubKey);
    echo "<br/>";
    echo "Encrypted Data = ".$encrypted;
    echo "<br/>";

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

    echo "<br/>";
    echo "Decrypted Data = ".$decrypted;
    echo "<br/>";
?>

LOGS


Encrypted Data = Uš6/ùÅËæÝmL4²G¾'gr¨Ñ­Ä‰ï‚zêbÀ)[îR0s‹yÝ`t™õ°Þe­Ïd>×o¯rß9ÌÔÅAü!-†D·¨ÎVZ¼?¶éžäýöaØT~=‚Fan¢ºq{M”ƒ¹Cû5N3¹.Ð(·#*ÏRƹñß÷õƒ_ò9c-Ÿ% ×óè2Ꙃõ“ÂÐgNÈ-ˆd«…ºt§¼Ô}yŠ"7èPš(¶R¤ßJÚ_h¶ðÞK(Cj“7‘Y ÀŠþrôZƒ4)JU•˜„üˆ k0â§Êë^ÚºGÚªúVKø†ë8ÏLÚó  „Ÿ¦¿¤

( ! ) Warning: openssl_private_decrypt(): key parameter is not a valid private key in C:\wamp\www\android\pki_example.php on line 41
Call Stack
#   Time    Memory  Function    Location
1   0.0020  252696  {main}( )   ..\pki_example.php:0
2   0.2043  258032  openssl_private_decrypt ( ) ..\pki_example.php:41

Decrypted Data =

最佳答案

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

echo "<br/>";
echo "Decrypted Data = ".$decrypted;
echo "<br/>";
openssl_private_decrypt函数能够使用PEM格式的私钥,但是您的 key 已加密,并且该函数没有用于密码的参数。您必须改为使用openssl_pkey_get_private

关于php - 无法解密数据-openssl_private_decrypt(): key parameter is not a valid private key,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29560095/

10-10 10:33