Warm tip: This article is reproduced from serverfault.com, please click

How to convert C# RSA to php?

发布于 2020-12-08 22:31:23

I want to convert this C# to php to use phpseclib RSA encrypt? Here is C#:

public static string Encrypt(string data)
{
    CspParameters cs = new CspParameters();
    RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
    rsa.FromXmlString("Key Goes here");
    var dataToEncrypt = _UNICODE.GetBytes(data);
    var encryptedByteArray = rsa.Encrypt(dataToEncrypt, false).ToArray();
    return Convert.ToBase64String(encryptedByteArray);
}

and I want to convert it to php using phpseclib with RSA as here: http://phpseclib.sourceforge.net/rsa/examples.html#encrypt,enc2

But I don't know C#, and I don't know what to do with _UNICODE.GetBytes(data) and rsa.Encrypt(dataToEncrypt, false).ToArray() converting them to php. Please advise.

Questioner
user6774350
Viewed
0
neubert 2020-12-09 09:11:58

var dataToEncrypt = _UNICODE.GetBytes(data); converts a string to a byte array. phpseclib accepts strings, directly, so there's nothing to convert there.

As for rsa.Encrypt(dataToEncrypt, false).ToArray()... per Encrypt(Byte[], Boolean) the second parameter is fOAEP, which is described thusly:

true to perform direct RSA encryption using OAEP padding (only available on a computer running Windows XP or later); otherwise, false to use PKCS#1 v1.5 padding

It returns a byte array (byte[]) so running the output through .ToArray() seems kinda weird but whatever.

Anyway, based on all that, I think this should do the trick:

$rsa = new RSA;
$rsa->loadKey("Key Goes here");
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
echo base64_encode($rsa->encrypt($data));