17

我有一个使用 RSACryptoServiceProvider 使用已知私钥(存储在变量中)解密一些数据的应用程序。

当 IIS 应用程序池配置为使用网络服务时,一切运行良好。

但是,当我们配置 IIS 应用程序池以在不同的身份下运行代码时,我们会得到以下信息:

System.Security.Cryptography.CryptographicException:系统找不到指定的文件。

   在 System.Security.Cryptography.Utils.CreateProvHandle(CspParameters 参数,布尔随机密钥容器)
   在 System.Security.Cryptography.RSACryptoServiceProvider.ImportParameters(RSAParameters 参数)
   在 System.Security.Cryptography.RSA.FromXmlString(字符串 xmlString)

代码是这样的:

byte[] input; 
byte[] output; 
string private_key_xml; 

var provider = new System.Cryptography.RSACryptoServiceProvider(this.m_key.Key_Size);
provider.FromXmlString(private_key_xml); // Fails Here when Application Pool Identity != Network Service

ouput = provider.Decrypt(input, false); // False = Use PKCS#1 v1.5 Padding

有一些资源试图通过说明您应该授予用户对机器密钥存储的读取权限来回答它 - 但是没有明确的答案来解决这个问题。

环境:IIS 6.0、Windows Server 2003 R2、.NET 3.5 SP1

4

5 回答 5

37

我通过在应用程序池的高级设置/流程模型部分将“加载用户配置文件”设置为 True(为 False)来解决此问题。

该应用程序在 Server 2003 R2 / IIS 6 上运行良好,当我在新的 2008 R2 服务器上配置它时出现了问题。

有了尝试的想法:

http://social.msdn.microsoft.com/forums/en-US/clr/thread/7ea48fd0-8d6b-43ed-b272-1a0249ae490f/

YMMV

于 2010-04-29T23:14:48.507 回答
12

确实,您需要编写这样的代码

CspParameters _cpsParameter;
RSACryptoServiceProvider RSAProvider;

_cpsParameter = new CspParameters();
_cpsParameter.Flags = CspProviderFlags.UseMachineKeyStore;

RSAProvider = new RSACryptoServiceProvider(1024, _cpsParameter); 

以下用户需要访问该文件夹:C:\Documents and Settings\All Users\Application data\Microsoft\Crypto\RSA\MachineKeys

  1. IIS 用户帐户(匿名)
  2. 您用于在 web.config 设置中模拟您的应用程序的用户帐户。

所以现在它对我来说很好。

于 2009-08-24T19:41:42.783 回答
8

尝试设置

System.Security.Cryptography.RSACryptoServiceProvider.UseMachineKeyStore = true;

编辑: 然后尝试使用

var provider = new System.Security.Cryptography.RSACryptoServiceProvider();

而不是带有整数参数的构造函数。该构造函数尝试生成具有指定密钥长度的密钥,而您可能无法使用您的权限执行此操作。

于 2009-07-09T10:03:15.103 回答
2

我只是想评论一下 Rasmus Faber 的解决方案对我有用(稍作修改):

System.Cryptography.RSACryptoServiceProvider.UseMachineKeyStore = true;
RSACryptoServiceProvider provider = new System.Cryptography.RSACryptoServiceProvider();

我试图让 MailBee.net 使用 DKIM 签署传出消息,并得到与 OP 收到的相同消息。当然,在我的开发机器上一切都很好,但是在上传到我的客户虚拟主机时,我遇到了这个问题。就像我说的,上面的解决方案对我有用,而我在网上找到的其他解决方案(包括上面的 msdn 论坛链接)没有。

(我会投票和评论,但我没有足够的代表这样做。:P)

谢谢拉斯穆斯法伯!

于 2010-08-25T03:27:38.053 回答
0

只有当我添加

标志 = CspProviderFlags.UseMachineKeyStore

问题为我解决了。

{
    string keyName = "Secret***";
    CspParameters parameters = new CspParameters()
    {
        KeyContainerName = keyName,
        Flags = CspProviderFlags.UseMachineKeyStore
    };
}
于 2021-01-19T15:33:38.077 回答