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.
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));
...phpseclib accepts strings, directly, so there's nothing to convert there... Actually that's an oversimplification, and this I think is likely to cause problems on the php side. My guess is that
_UNICODE
is actually utf16-le, and while decryption should succeed without any problems the plaintext then has to be sensibly interpreted. It all depends what OP wants to do with the plaintext, which of course has not been shared by OP.@PresidentJamesK.Polk - good point. If they want to just output it in a web browser they could just do
header('Content-Type: text/html; charset=utf-16le');
or some such, altho browsers I think sometimes auto detect the character type, ignoring the Content-Type idk lol. phpseclib just gives you the bytes in a string.