使用c#中的公钥加密数据,使用php中的私钥解密数据

本文关键字:数据 使用 私钥 解密 php 公钥加密 | 更新日期: 2023-09-27 18:01:51

我正在尝试加密JSON字符串在c# en解密它在PHP中使用OpenSSL RSA。

下面的代码是用c#编写的:

public static string EncryptData(string data)
{
    string key = @"-----BEGIN PUBLIC KEY-----
    MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC/J/txQvYBm5iOHRRRtgdXd5hq
    DEavxy5OExSiwjJgOgT72A9GX7+E7QYfhUZJTGtf+/J84tuJPx6/Ff1dZa1XRW84
    /n5m7fw93CTVwpfRFi0Owenor44zgk6ABSfMlCzwGfdcS8AFiWCFUBpatKte6PaO
    /WfYK7qz/5faSp3FawIDAQAB
    -----END PUBLIC KEY-----";
    OpenSSL.Crypto.CryptoKey pKey = OpenSSL.Crypto.CryptoKey.FromPublicKey(key, null);
    OpenSSL.Crypto.RSA rsa = pKey.GetRSA();
    byte[] encryptedData = rsa.PublicEncrypt (Encoding.UTF8.GetBytes(data), OpenSSL.Crypto.RSA.Padding.PKCS1);
    rsa.Dispose();
    return Convert.ToBase64String (encryptedData);
}

然后我将编码的encryptedData发送到PHP,并将其放入PrivateKeyDecrypt函数中。

PHP代码:

<?php
// include the lib
//require_once('OpenSSL.php');
$ssl = new OpenSSL();
$ssl->loadPrivateKeyWithoutPath('-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQC+wVuIECnd7dvt7yqoElg4DL8jSKFpUavKfviSBE2Z+5z5YWnf
i4mp/r0P0jVbE+dfqReaIr4UOt//hPvwvioAJ576KPOCTYZiIGehkqafGWS+01wH
nAPSj/C7Xt7F9Mh5McH4CnBR5VN93KKZtQtfNsNPPBdXwQuquONOUgUgTwIDAQAB
AoGAIQkvpvLVrV/CVQS0qIL00FA00hGEEs9YJyuyNOeV4PMYjn/2bAaogs5hQ9ot
72YVDhYkxkb6EFrZ7FDFqT3l2/BpQEsJ6/GQq2gX0rYGfJ5sWrN+KIuSJr4FWSN+
LrvIEr35hKHY6mytiQg9D58b5kSjaB9ea/qhh/hJL2VfWGECQQDlBBJsccR2ZzzH
QN5omwFrUuxnqraY5LyZB8xUnqo9iDULO+GTcW/5eO9TBoWuDf1Ul3Snts9Tb+uD
UYL1y5onAkEA1Ts182anQHCjUtp2hooLjDcOvIK3gi5TchqHW6T4K3tNtnbfOB9P
gMNgcKljjXlQXl3ornvLTYBC483MS4RpmQJAZMiS9whmBhlOpP1GI1C7oih/Auwc
qVJYMRw+bqrYjnWnqkby8XkFZwsyfx4qrDtZ1eVFIB2SRczGHyc688JjFwJBAIxa
lx6J2VlfSwIEbrQMNaGrs/V9jVERMTgQIjy+j+P/G54ZDMEiSvCUqew+cxryWWZk
Jf6D2cQ/wsez9N9YXzECQQDMH6jS9vp7aabI2UKy5RhTqvP6kRmi28/GHb/8QrFx
tldiw2THvc4+4QT9tuv5OA6xRnEO5mt5u3vFHciqeRR7
-----END RSA PRIVATE KEY-----');
public function PrivateKeyDecrypt($raw_data, $base64 = TRUE)
{
    if ($this->privateKey == NULL)
        trigger_error("Private key has not been specified.", E_USER_ERROR);
    if (!openssl_private_decrypt(($base64) ? base64_decode($raw_data) : $raw_data, $decrypted_data, $this->privateKey, $this->padding))
        trigger_error("Unable to decrypt data.", E_USER_ERROR);
    return $decrypted_data;
}
当我调用PrivateKeyDecrypt函数时,我得到的错误是:
FATAL ERROR: unable to decrypt data in ...

有人知道是什么原因导致这个错误吗?

使用c#中的公钥加密数据,使用php中的私钥解密数据

让你的padding匹配OpenSSL.Crypto.RSA.Padding.PKCS1在你的c#代码