I'm trying to load a OpenSSL public key from a SOAP server through Nusoap into C#, encrypt my data using the public key, then send the data back to the PHP server for decryption using the private key.
My C# looks like this:
static void Main(string[] args)
{
PHPRef.AddService test = new PHPRef.AddService();
var pkey = test.getPublicKey();
//Console.WriteLine(pkey.ToString());
byte[] PublicKey = GetBytes(pkey);
//Values to store encrypted symmetric keys.
byte[] EncryptedSymmetricKey;
byte[] EncryptedSymmetricIV;
//Create a new instance of RSACryptoServiceProvider.
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(2048);
//Get an instance of RSAParameters from ExportParameters function.
RSAParameters RSAKeyInfo = RSA.ExportParameters(false);
//Set RSAKeyInfo to the public key values.
RSAKeyInfo.Modulus = PublicKey;
//Import key parameters into RSA.
RSA.ImportParameters(RSAKeyInfo);
//Create a new instance of the RijndaelManaged class.
RijndaelManaged RM = new RijndaelManaged();
//Encrypt the symmetric key and IV.
EncryptedSymmetricKey = RSA.Encrypt(RM.Key, false);
EncryptedSymmetricIV = RSA.Encrypt(RM.IV, false);
Console.WriteLine("RijndaelManaged Key and IV have been encrypted with RSACryptoServiceProvider.");
byte[] encryptedData = RSA.Encrypt(GetBytes("password"), false);
//byte[] returned = (byte[])(Array)test.getDecrypted((sbyte[])(Array)encryptedData);
//string answer = GetString(returned);
string answer = test.getDecrypted((sbyte[])(Array)encryptedData);
Console.WriteLine(answer);
Console.ReadLine();
}
static byte[] GetBytes(string str)
{
byte[] bytes = Encoding.ASCII.GetBytes(str);
return bytes;
}
static string GetString(byte[] bytes)
{
char[] chars = Encoding.ASCII.GetChars(bytes);
return new string(chars);
}
And my PHP like so:
function getPublicKey()
{
$crt = file_get_contents("public.crt");
// $publickey = str_ireplace("\r", "", $crt);
// $publickey = str_ireplace("\n", "", $publickey);
// $publickey = str_ireplace("-----BEGIN CERTIFICATE-----", "", $publickey);
// $publickey = str_ireplace("-----END CERTIFICATE-----", "", $publickey);
return $crt;
}
function getDecrypted($input)
{
global $privateRSA;
// $privateRSA = str_ireplace("\r", "", $privateRSA);
// $privateRSA = str_ireplace("\n", "", $privateRSA);
// $privateRSA = str_ireplace("-----BEGIN RSA PRIVATE KEY-----", "", $privateRSA);
// $privateRSA = str_ireplace("-----END RSA PRIVATE KEY-----", "", $privateRSA);
if(!openssl_private_decrypt($input, $decrypted, $privateRSA))
return "fail";
else
return "success";
return $decrypted;
}
Needless to say I get "fail" every time. Any suggestions? I'm trying to do this with pure PHP and pure C#, no special libraries. The keys are 2048 bit.