duanfangbunao36970 2014-01-26 04:25
浏览 777

PHP:使用openSSL加密和解密时出错

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?

  • 写回答

1条回答 默认 最新

  • douzong7283 2018-10-25 09:31
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog