繁体   English   中英

在 PHP 上使用私钥进行 Rsa 解密失败

[英]Rsa decryption with private key on PHP failed

嗨,我在使用 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;
  }
}

我解决了我的问题,我不知道为什么,一定是因为我的编码字符串有无效字符所以当我发送 GET 或 POST 时它失败所以我的解决方案是使用 toHex function () 以十六进制形式编码数据并发送它,并且在接收到数据时,使用 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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM