$ 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
答案 0 :(得分:1)
在PHP 7.x和新版本的 phpseclib (纯PHP RSA实现)中,并使用作曲家安装 phpseclib ,您可以做到这一点:
# Install the phpseclib
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);
答案 1 :(得分:0)
在PHP中使用OpenSSL函数时,必须将公钥封装在X.509证书中。您可以使用CSR创建此项。或者您可以使用phpseclib, a pure PHP RSA implementation,并直接使用原始公钥。例如
<?php
include('Crypt/RSA.php');
$rsa = new Crypt_RSA();
$rsa->loadKey('...'); // public key
$plaintext = '...';
//$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$ciphertext = $rsa->encrypt($plaintext);
答案 2 :(得分:0)
像这样你可以添加密钥并加密文本
$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;
答案 3 :(得分: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);