RSACryptoServiceProvider CryptographicException系统无法找到ASP.NET下指定的文件

15 .net asp.net cryptography application-pool

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

当IIS应用程序池配置为使用网络服务时,一切运行正常.

但是,当我们将IIS应用程序池配置为在不同的标识下运行代码时,我们会得到以下结果:

System.Security.Cryptography.CryptographicException: The system cannot find the file specified.

   at System.Security.Cryptography.Utils.CreateProvHandle(CspParameters parameters, Boolean randomKeyContainer)
   at System.Security.Cryptography.RSACryptoServiceProvider.ImportParameters(RSAParameters parameters)
   at System.Security.Cryptography.RSA.FromXmlString(String 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
Run Code Online (Sandbox Code Playgroud)

有些资源试图通过声明您应该授予用户对机器密钥库的读取权限来尝试回答它 - 但是没有明确的答案来解决此问题.

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

Tim*_*son 32

我通过在应用程序池的高级设置/过程模型部分中将"加载用户配置文件"设置为True(为False)来修复此问题.

该应用程序在Server 2003 R2/IIS 6上运行完美,问题出现在我在新的2008 R2服务器上进行配置时.

有想法尝试:

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

因人而异


Edu*_*ier 10

确实,您需要使用这样的代码

CspParameters _cpsParameter;
RSACryptoServiceProvider RSAProvider;

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

RSAProvider = new RSACryptoServiceProvider(1024, _cpsParameter); 
Run Code Online (Sandbox Code Playgroud)

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

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

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


Ras*_*ber 8

尝试设置

System.Security.Cryptography.RSACryptoServiceProvider.UseMachineKeyStore = true;
Run Code Online (Sandbox Code Playgroud)

编辑: 然后尝试使用

var provider = new System.Security.Cryptography.RSACryptoServiceProvider();
Run Code Online (Sandbox Code Playgroud)

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

  • 如果您不想全局启用该标志,您似乎也可以调用"new RSACryptoServiceProvider(new CspParameters {Flags = CspProviderFlags.UseMachineKeyStore})". (2认同)