【问题标题】:PHP rsa get public key from pem filePHP rsa 从 pem 文件中获取公钥
【发布时间】:2019-12-25 01:26:45
【问题描述】:

如何从基于 rsa 364 创建的 pem 文件中获取公钥。 安装的 crypt(RSA.php) 库仍然低于错误

致命错误:调用 C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\rsa.php 中未定义的方法 Crypt_RSA::loadKey()

$file = "C:\key_file.pem"; 
$keypair = Crypt_RSA_KeyPair::fromPEMString(file_get_contents($file));
$public_key = $keypair->getPublicKey(); 
$rsa_pub_key = Crypt_RSA_Key::fromString($public_key->toString()); 
$rsa_obj = new Crypt_RSA; 
$verify_status = $rsa_obj->validateSign($text,$recieved_signed_sign, $rsa_pub_key) ? 'valid' : 'invalid'; 

得到错误 致命错误:调用 C:\Program Files\xxxx\rsa.php 中未定义的方法 PEAR_Error::getPublicKey()

尝试了同样的事情 openssl_verify。验证返回 0 尝试使用带有 384 rsa 密钥的 base64_encode 验证收到的符号。

**$base64DecodedStr = base64_decode("A1a0o8JzF7q12Sr4gJvYjslhg5XVA2fWy28.JyohJ05uyiZGyBpqazqb");
$status = openssl_verify($msg,$base64DecodedStr,$pub_key);**

请帮我解决这个问题。非常感谢。

【问题讨论】:

    标签: php pear


    【解决方案1】:

    根据Crypt_RSA documentation,Crypt_RSA 类没有 loadKey() 方法。您将公钥作为关联参数数组的一部分传递给构造函数:

    $rsa_obj = new Crypt_RSA(array('public_key' => $publickey));
    

    【讨论】:

    • 感谢大卫,我将代码更改为 $file = "C:\key_file.pem"; $keypair = Crypt_RSA_KeyPair::fromPEMString(file_get_contents($file)); $public_key = $keypair->getPublicKey(); $rsa_pub_key = Crypt_RSA_Key::fromString($public_key->toString()); $rsa_obj = 新的 Crypt_RSA; $verify_status = $rsa_obj->validateSign($text,$recieved_signed_sign, $rsa_pub_key) ? “有效”:“无效”;将错误作为致命错误:调用 C:\Program Files\xxxx\rsa.php 中未定义的方法 PEAR_Error::getPublicKey()
    • @mazheruddin,检查file_get_contents($file) 结果。您的 Crypt_RSA_KeyPair::fromPEMString 无法从 PEMString 获取密钥对,只有在您传递的字符串有问题时才会出现这种情况
    • @Rumm,试过 $fp = fopen($file, "r"); $pem_data = fread($fp, 文件大小($file)); fclose($fp);将 $pem_data 传递给 fromPEMString 函数。仍然可以回显相同的错误 $pem_data
    【解决方案2】:

    我的建议:不要使用 PEAR 的 Crypt_RSA,而是使用 phpseclib 的 Crypt_RSA。

    PEAR 的 Crypt_RSA 不符合 PKCS#1,这意味着用它生成的签名或密文不会与其他语言互操作,它不支持密码私钥,并且多年来一直没有得到积极维护。

    更多关于 phpseclib 的信息:

    http://phpseclib.sourceforge.net/

    【讨论】:

      【解决方案3】:

      这是如何在 php 中加载公钥以及如何知道其加密中使用的位数以及如何加密数据。请记住将数据拆分为最大大小为关键字节大小的块。

      <?php
      
      // Get the public Key 
      $pubKey = file_get_contents("public.key");
      
      //echo $pubKey; echo "<br>";
      
      $res=openssl_get_publickey($pubKey);   //convert pubkey into resource
      $array=openssl_pkey_get_details($res); //read the resource details
      $chunksize= $array['bits'];            //this is the chunk size 4096
      
      
      $data = 'plaintext data goes here, please encrypt and decrypt the following data';
      openssl_public_encrypt($data, $encrypted, $pubKey);
      ?>
      

      【讨论】:

        猜你喜欢
        • 2018-09-24
        • 2011-04-03
        • 1970-01-01
        • 2011-11-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多