Decrypting a string in C# 3.5 which was encrypted with openssl in php 5.3.2

Posted by panny on Stack Overflow See other posts from Stack Overflow or by panny
Published on 2010-06-05T06:59:48Z Indexed on 2010/06/05 7:02 UTC
Read the original article Hit count: 274

Filed under:
|
|
|
|

Hi everyone,

maybe someone can clear me up. I have been surfing on this a while now.

I used openssl from console to create a root certificate for me (privatekey.pem, publickey.pem, mycert.pem, mycertprivatekey.pfx). See the end of this text on how.

The problem is still to get a string encrypted on the PHP side to be decrypted on the C# side with RSACryptoServiceProvider. Any ideas?


PHP side

I used the publickey.pem to read it into php:

$server_public_key = openssl_pkey_get_public(file_get_contents("C:\publickey.pem"));
// rsa encrypt
openssl_public_encrypt("123", $encrypted, $server_public_key);

and the privatekey.pem to check if it works:

openssl_private_decrypt($encrypted, $decrypted, openssl_get_privatekey(file_get_contents("C:\privatekey.pem")));

Coming to the conclusion, that encryption/decryption works fine on the php side with these openssl root certificate files.


C# side

In same manner I read the keys into a .net C# console program:

X509Certificate2 myCert2 = new X509Certificate2();
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

try
{
    myCert2 = new X509Certificate2(@"C:\mycertprivatekey.pfx");
    rsa = (RSACryptoServiceProvider)myCert2.PrivateKey;
}
catch (Exception e)
{
}

string t = Convert.ToString(rsa.Decrypt(rsa.Encrypt(test, false), false));

coming to the point, that encryption/decryption works fine on the c# side with these openssl root certificate files.


key generation on unix

1) openssl req -x509 -nodes -days 3650 -newkey rsa:1024 -keyout privatekey.pem -out mycert.pem

2) openssl rsa -in privatekey.pem -pubout -out publickey.pem

3) openssl pkcs12 -export -out mycertprivatekey.pfx -in mycert.pem -inkey privatekey.pem -name "my certificate"

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET