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

时间:2014-05-04 22:38:41

标签: c# php encryption openssl rsa

我试图在C#中加密JSON字符串,使用OpenSSL RSA在PHP中解密它。

以下代码位于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 ...

有谁知道导致此错误的原因是什么?

1 个答案:

答案 0 :(得分:0)

在C#代码中填充匹配OpenSSL.Crypto.RSA.Padding.PKCS1