【问题标题】:Rsa decryption with private key on PHP failed在 PHP 上使用私钥进行 Rsa 解密失败
【发布时间】:2021-12-05 06:10:13
【问题描述】:

嗨,我在使用 PHP 以上的私钥解密 RSA 时遇到错误,请帮忙 (我尝试在 c# 私钥上解密工作正常)

错误

error:04065072:rsa routines:rsa_ossl_private_decrypt:padding check failed

PHP

  class RSA{
    protected $private;
   public function __construct()
{

 $this->private = @file_get_contents("private.pem");
}
    public function decrypt($data)
{
    if (is_null($data) || empty($data) || is_string($data) === false) {
        throw new RuntimeException('Needless to encrypt.');
    } elseif (is_null($this->private) || empty($this->private)) {
        throw new RuntimeException('You need to set the private key.');
    }
        $key = openssl_get_privatekey($this->private);
        if (!openssl_private_decrypt(base64_decode($data), $result, $key)){
             throw new Exception(openssl_error_string());
        }
        return $result;
  }
}

【问题讨论】:

  • 将此部分分成问题和答案。然后人们就会知道在哪里寻找答案

标签: php rsa


【解决方案1】:

我的问题解决了,不知道为什么,一定是因为我的编码字符串有无效字符所以当我发送GET或POST时它失败所以我的解决方案是使用toHex函数()以Hex形式编码数据并发送,接收到数据时,使用 toStr() 解码回来。

public function toHex($string){
$hex='';
for ($i=0; $i < strlen($string); $i++){
    $hex .= dechex(ord($string[$i]));
}
return $hex;
 }


public function toStr($hex){
$string='';
for ($i=0; $i < strlen($hex)-1; $i+=2){
    $string .= chr(hexdec($hex[$i].$hex[$i+1]));
}
return $string;
}

C#

public static string ToHex(string str)
    {
        var sb = new StringBuilder();

        var bytes = Encoding.UTF8.GetBytes(str);
        foreach (var t in bytes)
        {
            sb.Append(t.ToString("X2"));
        }

        return sb.ToString();
    }
    public static string FromHexString(string hexString)
    {
        var bytes = new byte[hexString.Length / 2];
        for (var i = 0; i < bytes.Length; i++)
        {
            bytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
        }

        return Encoding.UTF8.GetString(bytes);
    }

私钥解密编辑

openssl_private_decrypt(base64_decode($this->toStr($data)), $result, $key)

【讨论】:

  • 发送 ...来自什么?去哪里?
  • @PresidentJamesK.Polk 这里我使用从 c# 客户端发送到 PHP 服务器
  • 但是你的toHex()函数是用php写的!
  • @PresidentJamesK.Polk 您可以查看我编辑的答案并添加了 c# 代码
猜你喜欢
  • 2012-07-13
  • 1970-01-01
  • 2014-10-03
  • 1970-01-01
  • 2018-05-20
  • 1970-01-01
  • 1970-01-01
  • 2020-08-26
  • 1970-01-01
相关资源
最近更新 更多