I've been trying to make two PHP pages, one to encrypt and one to decrypt.
The code for the encrypting page:
<form action="encrypt.php" method="post">
<input type="text" name="data">
<input type="submit">
</form>
<?php
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$config = array(
"digest_alg" => "sha512",
"private_key_bits" => 4096,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
);
$keys = openssl_pkey_new($config);
openssl_pkey_export($keys, $privKey);
$pubKey = openssl_pkey_get_details($keys);
$pubKey = $pubKey["key"];
require "openssl.php";
openssl_public_encrypt($_POST["data"],$encrypted, $pubKey);
echo $encrypted;
echo "<br><br>";
echo $privKey;
}
?>
And this is the code for decrypting:
<form action="decrypt.php" method="post">
Encrypted Text: <textarea name="encrypted" rows="10" cols="100"></textarea><br><br>
Key: <textarea name="key" rows="10" cols="100"></textarea><br>
<input type="submit">
</form>
<?php
if($_SERVER["REQUEST_METHOD"] == "POST")
{
openssl_private_decrypt($_POST["encrypted"],$decrypted,$_POST["key"]);
echo $decrypted;
}
?>
It seems to encrypt the data just fine, but when I try to decrypt using the other page, a get an error:
openssl_private_decrypt() [function.openssl-private-decrypt]: key parameter is not a valid private key
I copied and pasted the private key directly from the output of the encrypting file. Why am I getting an error?
It seems to encrypt the data just fine,
First thing to debug: Can you immediately decrypt your encrypted message on the encryption page and get the same plaintext message?
openssl_private_decrypt() [function.openssl-private-decrypt]: key parameter is not a valid private key
Your code contains:
openssl_private_decrypt($_POST["encrypted"],$decrypted,$_POST["key"]);
Try this instead:
$private = openssl_pkey_get_private($_POST['key']);
openssl_private_decrypt($_POST["encrypted"], $decrypted, $private);
A word about security : OpenSSL's default settings for RSA encryption are not secure .
For best results, in any real world applications that need public-key cryptography, consider switching to libsodium and just using the crypto_box_seal
API instead.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.