php - get the key parameter is not a valid public key 错误在 openssl_public_encrypt()

标签 php encryption openssl public-key-encryption php-openssl

$publicKey = "../ssh/public/pub"; $plaintext = "要加密的字符串";

$pubKey = openssl_pkey_get_public($publicKey);

openssl_public_encrypt($plaintext, $encrypted, $pubKey);

echo $encrypted;   //encrypted string

以上代码产生以下错误

openssl_public_encrypt() [http://php.net/function.openssl-public-encrypt]: key 参数不是有效的公钥 [APP/controllers/supportservice_controller.php,第 144 行]

我使用 openssl 创建了 key :

生成一个 1024 位的 rsa 私钥,要求一个密码来加密它并保存到文件 openssl genrsa -des3 -out/path/to/privatekey 1024

为私钥生成公钥并保存到文件

openssl rsa -in/path/to/privatekey -pubout -out/path/to/publickey

最佳答案

在我的例子中,我将公钥拆分成多行,解决了问题。

PHP 版本 7.1.17

    $publicKey = "-----BEGIN PUBLIC KEY-----\n" . wordwrap($publicKey, 64, "\n", true) . "\n-----END PUBLIC KEY-----";

    $str = "str to be encrypted";

    $opensslPublicEncrypt = openssl_public_encrypt($str, $encrypted, $publicKey);

关于php - get the key parameter is not a valid public key 错误在 openssl_public_encrypt(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18842403/

相关文章:

security - WordPress 登录安全

java - 我的 Cipher 实现出现 NullPointerException

ssh - 使用 OpenSSL 生成私钥,为 SSH 生成公钥 ssh-keygen

php - 通过将 CSS 文件合并到一个文件中来加快网站速度 - Laravel

javascript - 无法使用ajax调用从服务器加载数据

c# - 使用 RSA 公钥解密使用 RSA 私钥加密的字符串

c - 头文件的问题

带有 openssl 1.1.1 : cannot perform post-handshake authentication 的 Apache 2.4.37

javascript - 如何延迟发送 ajax 请求?

php - 仅在特定页面上使用 HTTPS - Htaccess、Apache、OpenSSL