0

I need to convert code from C# to PHP, with identical results. In C# I finished it pretty quickly, but now need to convert the following code to php:

public static string RsaDecrypt(string privateKey, string src)
{
    CspParameters csp = new CspParameters();
    csp.Flags = CspProviderFlags.UseMachineKeyStore;
    RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(csp);
    rsa.FromXmlString(privateKey);
    return RsaDecrypt(rsa, src);
}

public static string RsaDecrypt(RSACryptoServiceProvider rsa, string src)
{
    byte[] srcData = Convert.FromBase64String(src);
    byte[] destData = rsa.Decrypt(srcData, false);
    return Encoding.UTF8.GetString(destData);
}

I'm trying to hours and I can not, I'm using the phpseclib0.2.1a file and the code:

Pastebin

The Problem in PHP is returning the following error:

Notice: Decryption error in E:\AppServWWW\Request\Flash\Crypt\RSA.php on line 1582

@EDIT: My $_GET["p"] is

cwQPQLSW%2FQ70AUmBzkZ9c7d9MrEAcPAAN1lRG937XZuibDOE304i8894uowlC1OANnWEim6suOxzhEHZl0BR1G1audk4CWG1TUSqAo4MO5FBfVbmcLVMx1KPV9%2FeMzil%2BHM1XwyX3Dm0h%2F0uAxORfpa3waq0iOemkUYBq2lXDEU%3D

neubert
  • 15,947
  • 24
  • 120
  • 212
  • Also, please tell us which line is 1582...... – pattyd Jun 04 '13 at 19:14
  • if ($lHash != $lHash2) { user_error('Decryption error', E_USER_NOTICE); return false; } – Gabriel Oliveira Jun 04 '13 at 19:16
  • 1) You didn't post your encryption code. 2) Setting the second parameter of `Decrypt` to `false` means you're using a bad padding. 3) Consider encrypting the actual data with AES and only encrypting the key with RSA. RSA should only be used to encrypt short data. – CodesInChaos Jun 04 '13 at 21:18

1 Answers1

0

The latest version of phpseclib is 0.3.1 so, first, I'd recommend you upgrade.

Second... phpseclib does OAEP padding by default. C# is probably doing PKCS1 padding by default. So you'd need to do $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1); before doing the actual decryption in PHP.

neubert
  • 15,947
  • 24
  • 120
  • 212
  • Thanks, the code worked as it should. Updated my phpseclib and added your code and it worked =] Thank you very much. – Gabriel Oliveira Jun 04 '13 at 21:39
  • That's exactly the wrong way round. You should use OAEP for both, not PKCS#1v1.5. The older padding scheme is flawed and allows padding-oracle attacks. – CodesInChaos Jun 15 '13 at 20:44