0

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?

2
  • I know I'm not answering your question but why use the "base64_encode" function twice in your PHP script...? Commented Sep 23, 2022 at 8:19
  • That's a good question. I can't answer this to you because I didn't write the PHP code, I really don't know. The PHP code works as desired though and I have to rewrite it in C#. Commented Sep 23, 2022 at 8:29

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.