Converting openssl_public_encrypt (PHP) in C# code

Viewed 14

So I have to convert some PHP code to C# and my PHP code does following:

    if (null === $date)
        $date = time();
    $plain = "user:{$login};system:{$system};date:{$date};";

    if (!openssl_public_encrypt($plain, $encrypted, $this->key)) {
        throw new \Exception("Error while encoding with message: "  . openssl_error_string());
    }
    
    return base64_encode(base64_encode($encrypted));

And now I wrote following Code in C#:

if (date == null) date = DateTimeOffset.Now;

        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
        RSAParameters rsaParam = rsa.ExportParameters(false);
        rsaParam.Modulus = key;
        rsa.ImportParameters(rsaParam);

        var plain = $"user:{login};system:{system};date:{date.Value.ToUnixTimeSeconds()};";
        var result = rsa.Encrypt(Encoding.UTF8.GetBytes(plain), RSAEncryptionPadding.Pkcs1);

        return Convert.ToBase64String(Encoding.UTF8.GetBytes(Convert.ToBase64String(result)));

Unfortunately, the result looks very different in length and I saw that the C# code misses two "==" at the end, while in the PHP result, there is always "==" at the end. I checked the "plain" text, it's the same in both PHP and C# (beside the date timestamp, but that's because it changes every second). Can anyone help me?

1 Answers

So randomly we came to a solution. We used a converter to convert the PEM public key to XML and used the method "FromXmlString" and then it worked:

var rsa = new RSACryptoServiceProvider(2048);
        rsa.FromXmlString("<RSAKeyValue><Modulus>[...]</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>");

We used this converter: https://raskeyconverter.azurewebsites.net/PemToXml

Hopefully this helps other people.

Related