获取密钥参数不是 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]:键参数不是有效的公钥 [APP/控制器/supportservice_controller.php,第 144 行]

我使用openssl创建了密钥:

生成一个 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 7.x 和新版本的 phpseclib(一个纯 PHP RSA 实现)中,并使用 composer 安装 phpseclib,你可以这样做:

    # Install the phpseclib from console
    composer require phpseclib/phpseclib:~2.0
    // In your php script:
    use phpseclibCryptRSA;
    $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);```

像这样,您可以添加密钥并加密文本

  $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中使用OpenSSL的函数时,公钥必须封装在X.509证书中。您可以使用 CSR 创建此内容。或者你可以使用 phpseclib,一个纯 PHP RSA 实现,并直接使用原始公钥。例如。

<?php
include('Crypt/RSA.php');
$rsa = new Crypt_RSA();
$rsa->loadKey('...'); // public key
$plaintext = '...';
//$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$ciphertext = $rsa->encrypt($plaintext);

相关内容

最新更新