通过 CSharp-easy-RSA-PEM 使用 RSA 时在服务器上出现异常

Getting exception on server when using RSA via CSharp-easy-RSA-PEM

我在我的 mvc 项目中使用 https://github.com/jrnker/CSharp-easy-RSA-PEM 实现 RSA。

它在我的本地机器的 IIS 中工作正常,也通过 visual studio 工作,但是当我在服务器上部署我的应用程序时,出现以下异常。

"System.NullReferenceException: Object reference not set to an instance of an object.\r\n at CoreEntities.Classes.Utility.RSADecrypt(String input)\r\n at WebAPI.Attributes.ApiAuthorizeAttribute.Authorize(HttpActionContext actionContext)"

我的代码是:

public static string RSADecrypt(string input)
{
    try
    {
        string priv = File.ReadAllText(HostingEnvironment.MapPath("~/Certificates/consumer.pem"));
        RSACryptoServiceProvider privc = Crypto.DecodeRsaPrivateKey(priv);
        return Crypto.DecryptString(input, privc);
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

我在 github 上也发布了我的问题@ https://github.com/jrnker/CSharp-easy-RSA-PEM/issues/8

经过多次调试,我发现系统没有创建 RSACryptoServiceProvider

的对象
CspParameters parms = new CspParameters();
parms.Flags = CspProviderFlags.NoFlags;
parms.KeyContainerName = Guid.NewGuid().ToString().ToUpperInvariant();
parms.ProviderType = ((Environment.OSVersion.Version.Major > 5) || ((Environment.OSVersion.Version.Major == 5) && (Environment.OSVersion.Version.Minor >= 1))) ? 0x18 : 1;

// Exception is comping in below line.
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(parms);

RSAParameters rsAparams = new RSAParameters();

异常:- System.Security.Cryptography.CryptographicException: The system cannot find the file specified.\r\n\r\n at CoreEntities.Classes.Utility.RSADecrypt(String input)\r\n at WebAPI.Attributes.ApiAuthorizeAttribute.Authorize(HttpActionContext actionContext) 谁能帮忙...

@Downvoters,敬请关注

我找到了解决这个问题的方法。

此问题主要是由于 windows 服务器 2008 及更高版本中包含的新安全限制所致。

在 windows 服务器 2008 中,将默认创建一个名为 CryptoGraphic Operator 的新用户。

如果您的应用程序正在使用 RSACryptoServiceProvider,并且当您决定在 windows 服务器 2008 IIS7 上托管您的应用程序时,请执行以下步骤

  1. 您创建的虚拟目录的相应应用程序池所在的帐户 运行 应添加到 CryptoGraphic Operator 用户中。
  2. 打开 IIS7 --> ApplicationPools --> YourAppPool -->RighClikck --> Advanced Settings ---> Load User Profile 将此值设置为 true。

这解决了我的问题。

参考:- https://social.msdn.microsoft.com/Forums/vstudio/en-US/ec93922a-fd1e-4225-b5cf-1472ebb3acd1/systemsecuritycryptographycryptographicexception-the-system-cannot-find-the-file-specified?forum=netfxbcl

我通过像下面这样更改流程解决了问题,无需操纵 Web 服务器(IIS、NGINX 或任何其他)。我还在 linux 上测试过,工作正常。

RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(xmlPrivateKey);
string toBeSigned= "string";
byte[] signMain = rsa.SignData(Encoding.UTF8.GetBytes(toBeSigned), new SHA1CryptoServiceProvider());
string signature = Convert.ToBase64String(signMain);