Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RSACryptoServiceProvider not working in .net core

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

like image 244
Rahul Khanna Avatar asked Jul 22 '19 14:07

Rahul Khanna


1 Answers

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;
}
like image 112
Rahul Khanna Avatar answered Nov 05 '22 05:11

Rahul Khanna