我必须调用政府API, session key 需要使用它们提供的公共(public) key 进行加密。以下代码用于加密 session key ,在使用.NET框架的Windows服务器上可以正常工作,但是我需要使用.NET内核将API托管在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 (RSACryptoServiceProvider csp = (RSACryptoServiceProvider)cert.PublicKey.Key)
    {
        byte[] bytesData = input;
        byte[] bytesEncrypted = csp.Encrypt(bytesData, true);
        output = Convert.ToBase64String(bytesEncrypted);
    }
    return output;
}

我将代码更改为以下代码,它可以成功运行,但是当我调用API时,出现错误,提示 session key 解密错误,请使用正确的公共(public) key 加密 session key 。

如何在.net核心中获得类似于RSACryptoServiceProvider的加密
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;
}

回答其他问题的代码不在.net核心上工作,它使用.net框架
Casting private key to RSACryptoServiceProvider not working

最佳答案

它可以正常工作,在我尝试的更新代码中,我将填充更改为OaepSHA1,现在可以正常工作了。谢谢

以下是工作代码(在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;
}

关于c# - RSACryptoServiceProvider在.net核心中不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57148122/

10-12 12:48
查看更多