Skip to content
Advertisement

C# RSA Encrpytion -> Laravel phpseclib decrypt()

I’m using a key pair generated by phpseclib and then I use it to encrypt in C# a message and decrypt in PHP.

The public key is:

JavaScript

The conversion to XML is done via https://superdry.apphb.com/tools/online-rsa-key-converter

Here is how the message is encrypted in C#:

JavaScript

What is sent (encrypted message) by C# to PHP (changes everytime):

JavaScript

On the decryption side in PHP:

JavaScript

The output is like this:

JavaScript

What am I missing here?

Advertisement

Answer

In the C# code PKCS#1 v1.5 padding is applied (2nd parameter of Encrypt() is false), phpseclib uses OAEPadding by default (here).

Decryption works if PKCS#1 v1.5 padding is explicitly specified in the PHP code:

JavaScript

Alternatively, OAEPadding could be used in the C# code. But be careful, if in Encrypt() the 2nd parameter is set to true, .NET uses SHA-1 for both digests by default. However, phpseclib applies SHA-256 for both digests by default. Therefore, in the C# code, for compatibility with the PHP code, both digests must be explicitly set to SHA256 (this is not possible with RSACryptoServiceProvider, but with RSACng; also, the overload of Encrypt() is needed, with which the digest can be set explicitly).

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement