Php 获取密钥参数不是openssl_public_encrypt()中的有效公钥错误
$publicKey=“../ssh/public/pub”; $plaintext=“要加密的字符串” 上面的代码生成以下错误 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 为私钥生成公钥并保存到文件Php 获取密钥参数不是openssl_public_encrypt()中的有效公钥错误,php,encryption,openssl,public-key-encryption,php-openssl,Php,Encryption,Openssl,Public Key Encryption,Php Openssl,$publicKey=“../ssh/public/pub”; $plaintext=“要加密的字符串” 上面的代码生成以下错误 openssl_public_encrypt()[http://php.net/function.openssl-public-encrypt]:key参数不是有效的公钥[APP/controllers/supportservice_controller.php,第144行] 我使用openssl创建了密钥,使用: 生成一个1024位rsa私钥,请求密码短语对其进行加
openssl rsa-in/path/to/privatekey-pubout-out/path/to/publickey在PHP中使用openssl函数时,公钥必须封装在X.509证书中。您可以使用CSR创建此项。或者您可以直接使用原始公钥。例如
<?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.x和新版本的phpseclib(纯PHP RSA实现)中,使用composer安装phpseclib,可以执行以下操作:
# Install the phpseclib from console
composer require phpseclib/phpseclib:~2.0
在我的例子中,我将公钥拆分为多行,解决了这个问题
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);
看到这个了吗
// 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);```
$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);