以编程方式使用RSAProtectedConfigurationProvider加密web.config,提供内部服务器错误105.23

时间:2016-05-31 06:08:42

标签: c# asp.net encryption web-config rsa

我正在尝试通过RSAProtectedConfigurationProvider以编程方式加密web.config文件的各个部分。但是在加密时它到达SAVE();它会引发异常 System.Security.Cryptography.CryptographicException:对象已经存在。

但是如果我使用 DataProtectionConfigurationProvider 对其进行加密,它会加密该部分,但是当我运行应用程序时它会给出 HTTP错误500.23 - 内部服务器错误

它的解决方案是什么?

我在SQLDataSource中正在执行此操作以读取web.config文件中的连接字符串。如果web.config加密了吗?

,这个东西是行不通的吗?

这是我的代码:

 private void ProtectSection(string sectionName, string provider)
 {
     CspParameters cspParams;
     const int PROVIDER_RSA_FULL = 1;
     const string CONTAINER_NAME = "NetFrameworkConfigurationKey";
     cspParams = new CspParameters(PROVIDER_RSA_FULL);
     cspParams.KeyContainerName = CONTAINER_NAME;
     cspParams.Flags = CspProviderFlags.UseMachineKeyStore;
     cspParams.ProviderName = "Microsoft Strong Cryptographic Provider";

     CryptoKeyAccessRule rule = new CryptoKeyAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), CryptoKeyRights.FullControl, AccessControlType.Allow);

     cspParams.CryptoKeySecurity = new CryptoKeySecurity();
     cspParams.CryptoKeySecurity.SetAccessRule(rule);

     Configuration config = WebConfigurationManager.openWebConfiguration(System.Web.HttpContext.Current.Request.ApplicationPath);

     ConfigurationSection section = config.GetSection(sectionName);

     if (section != null && !section.SectionInformation.IsProtected)
     {
        section.SectionInformation.ProtectSection(provider);
        config.Save();
     }
 }

 private void UnProtectSection(string sectionName)
 {
    Configuration config = WebConfigurationManager.openWebConfiguration(System.Web.HttpContext.Current.Request.ApplicationPath);

    ConfigurationSection section = config.GetSection(sectionName);

    if (section != null && section.SectionInformation.IsProtected)
    {
      section.SectionInformation.UnprotectSection();
      config.Save();
    }
 }

非常感谢帮助。提前谢谢。

1 个答案:

答案 0 :(得分:0)

请找到以下链接,要求您提供机器密钥的权利。只需为iisuser / everyone提供访问权限并尝试相同的操作。这很好用。机器密钥文件夹可以在以下任何一个文件夹中找到

•\ ProgramData \微软\加密\ RSA \ MachineKeys的 •\ Users \ All Users \ Microsoft \ Crypto \ RSA \ MachineKeys

谢谢

相关问题