[英]php openssl_public_encrypt(): key parameter is not a valid public key
[英]Get the key parameter is not a valid public key error in openssl_public_encrypt()
$ 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創建了鍵:
生成1024位rsa私鑰,請求密碼加密並保存到文件openssl genrsa -des3 -out / path / to / privatekey 1024
生成私鑰的公鑰並保存到文件
openssl rsa -in / path / to / privatekey -poutout -out / path / to / publickey
在PHP 7.x和新版本的phpseclib ( 純PHP RSA實現 )中並使用composer安裝phpseclib ,您可以這樣做:
# Install the phpseclib from console
composer require phpseclib/phpseclib:~2.0
// In your php script:
use phpseclib\Crypt\RSA;
$rsa = new RSA();
$rsa->loadKey($publicKey); # $publicKey is an string like "QEFAAOCAQ8AMIIBCgKCAQEAoHcbG....."
$plaintext = '...';
$ciphertext = $rsa->encrypt($plaintext);
var_dump($ciphertext);
#to decrypt:
$rsa->loadKey('...'); // private key
echo $rsa->decrypt($ciphertext);```
在PHP中使用OpenSSL函數時,公鑰必須封裝在X.509證書中。 您可以使用CSR創建此項。 或者您可以使用純PHP PHP實現的phpseclib,並直接使用原始公鑰。 例如。
<?php
include('Crypt/RSA.php');
$rsa = new Crypt_RSA();
$rsa->loadKey('...'); // public key
$plaintext = '...';
//$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$ciphertext = $rsa->encrypt($plaintext);
像這樣你可以添加密鑰並加密文本
$data = json_decode(file_get_contents('php://input'), true);
$enctext = $data['enctext'];
$pubkey = '-----BEGIN PUBLIC KEY-----
PUBLIC KEY PLACED HERE
-----END PUBLIC KEY-----';
openssl_public_encrypt($enctext, $crypted, $pubkey);
$data['enctext'] = $enctext;
$data['Encryption_text'] = base64_encode($crypted);
echo json_encode($data);
exit;
或者,您也可以調用公鑰的.cert文件
$fp=fopen("publickey.crt","r");
$pub_key_string=fread($fp,8192);
fclose($fp);
$key_resource = openssl_get_publickey($pub_key_string);
openssl_public_encrypt($enctext, $crypted, $key_resource );
$data['enctext'] = $enctext;
$data['Encryption_text'] = base64_encode($crypted);
echo json_encode($data);
exit;
在我的情況下,我將公鑰分成多行,解決了問題。
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.