I have to call a government API, session key needs to be encrypted using public key provided by them. Following code to encrypt the session key is working fine on windows server using .NET framework, but I need to host the API on aws lambda using .NET core. There is gives following error
System.InvalidCastException: Unable to cast object of type 'System.Security.Cryptography.RSAOpenSsl' to type 'System.Security.Cryptography.RSACryptoServiceProvider
private static string EncryptRsa(byte[] input)
{
string output = string.Empty;
System.Security.Cryptography.X509Certificates.X509Certificate2 cert = new X509Certificate2(@"Cert/server_pub.cer");
using (RSACryptoServiceProvider csp = (RSACryptoServiceProvider)cert.PublicKey.Key)
{
byte[] bytesData = input;
byte[] bytesEncrypted = csp.Encrypt(bytesData, true);
output = Convert.ToBase64String(bytesEncrypted);
}
return output;
}
I changed the code to following, it runs successfully but when I call the API it give an error saying session key decryption error, please encrypt the session key using correct public key.
How to I get similar encryption to RSACryptoServiceProvider
in .net core
private static string EncryptRsa(byte[] input)
{
string output = string.Empty;
System.Security.Cryptography.X509Certificates.X509Certificate2 cert = new X509Certificate2(@"Cert/server_pub.cer");
using (RSA csp = (RSA)cert.PublicKey.Key)
{
byte[] bytesData = input;
byte[] bytesEncrypted = csp.Encrypt(bytesData, RSAEncryptionPadding.Pkcs1);
output = Convert.ToBase64String(bytesEncrypted);
}
return output;
}
Code in answer of other question is not working on .net core, it uses .net framework Casting private key to RSACryptoServiceProvider not working
It worked, in the updated code I was trying, I changed the padding to OaepSHA1, its working now. Thank you
Below is the working code (Tested on AWS Lambda):
private static string EncryptRsa(byte[] input)
{
string output = string.Empty;
System.Security.Cryptography.X509Certificates.X509Certificate2 cert = new X509Certificate2(@"Cert/server_pub.cer");
using (RSA csp = (RSA)cert.PublicKey.Key)
{
byte[] bytesData = input;
byte[] bytesEncrypted = csp.Encrypt(bytesData, RSAEncryptionPadding.OaepSHA1);
output = Convert.ToBase64String(bytesEncrypted);
}
return output;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With