【问题标题】:ProtectedConfigurationProvider using Rsa and x509 certificateProtectedConfigurationProvider 使用 Rsa 和 x509 证书
【发布时间】:2013-06-12 10:22:16
【问题描述】:

我是新手,所以请多多包涵。我正在尝试使用 RsaProtectedConfigurationProvider

加密/解密 .config 部分

如果我错了,请纠正我,但根据我一直在阅读的内容,我需要执行以下操作:

  1. 从该证书中获取证书和公钥

    X509Certificate2 cert = new X509Certificate2(pathToCert, "password");
    RSACryptoServiceProvider rsa = cert.PrivateKey as RSACryptoServiceProvider;
    
  2. 将此信息加载到容器: 不知道怎么做,因为下面的示例不考虑证书

http://msdn.microsoft.com/en-us/library/tswxhw92(en-us,VS.80).aspx

    // Create the CspParameters object and set the key container 
    // name used to store the RSA key pair.
    CspParameters cp = new CspParameters();
    cp.KeyContainerName = "MySuperAwesomeKeyContainer";

    // Create a new instance of RSACryptoServiceProvider that accesses
    // the key container MyKeyContainerName.
    RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cp);
  1. 然后在我的 App.Config 中指定相同的容器名称:
<configProtectedData>
<providers>
 <clear/>
  <add name="MyProvider"
  type="System.Configuration.RsaProtectedConfigurationProvider"
  keyContainerName="MySuperAwesomeKeyContainer"
  useMachineContainer="true" />
</providers>
</configProtectedData>
  1. 然后只需运行将使用该 KeyContainer 的代码并对其进行加密/解密:
....
string provider = "MyProvider";
// Protect the section.
connStrings.SectionInformation.ProtectSection(provider);

这是正确的吗?如果是这样,我该怎么做?不知道如何从证书中获取这些密钥并将它们加载到 KeyContainer 中。

谢谢

【问题讨论】:

    标签: c# asp.net encryption public-key-encryption rsaprotectedconfiguration


    【解决方案1】:

    我是这样做的:

    提供者实现:

    public class X509ProtectedConfigProvider : ProtectedConfigurationProvider
    {
        #region Fields
    
        private X509Certificate2 cert;
    
        #endregion
    
        // Performs provider initialization. 
        #region Public Methods and Operators
    
        public override XmlNode Decrypt(XmlNode encryptedNode)
        {
            // Load config section to encrypt into xmlDocument instance
            XmlDocument doc = encryptedNode.OwnerDocument;
            EncryptedXml eXml = new EncryptedXml(doc);
    
            eXml.DecryptDocument();
            return doc.DocumentElement;
        }
    
        public override XmlNode Encrypt(XmlNode node)
        {
            // Load config section to encrypt into xmlDocument instance
            XmlDocument doc = new XmlDocument { PreserveWhitespace = true };
            doc.LoadXml(node.OuterXml);
    
            // Encrypt it
            EncryptedXml eXml = new EncryptedXml();
            EncryptedData eData = eXml.Encrypt(doc.DocumentElement, this.cert);
            return eData.GetXml();
        }
    
        public override void Initialize(string name, NameValueCollection config)
        {
            base.Initialize(name, config);
    
            string certSubjectDistName = config["CertSubjectDistinguishedName"];
            string certStoreName = config["CertStoreName"];
    
            X509Store certStore = !string.IsNullOrEmpty(certStoreName) ? new X509Store(certStoreName, StoreLocation.LocalMachine) : new X509Store(StoreLocation.LocalMachine);
    
            try
            {
                certStore.Open(OpenFlags.ReadOnly);
                X509Certificate2Collection certs = certStore.Certificates.Find(
                    X509FindType.FindBySubjectName, certSubjectDistName, true);
    
                this.cert = certs.Count > 0 ? certs[0] : null;
            }
            finally
            {
                certStore.Close();
            }
        }
    
        #endregion
    }
    

    助手类:

    public static class Crypto
        {
            // Protect the connectionStrings section. 
            #region Public Methods and Operators
    
            public static bool ProtectConfiguration(string path)
            {
                string provider = "X509ProtectedConfigProvider";
    
                // Get the application configuration file.
                Configuration config = ConfigurationManager.OpenExeConfiguration(path);
    
                // Get the section to protect.
                ConfigurationSection connStrings = config.ConnectionStrings;
    
                if (connStrings != null)
                {
                    if (!connStrings.SectionInformation.IsProtected)
                    {
                        if (!connStrings.ElementInformation.IsLocked)
                        {
                            // Protect the section.
                            connStrings.SectionInformation.ProtectSection(provider);
    
                            connStrings.SectionInformation.ForceSave = true;
                            config.Save(ConfigurationSaveMode.Full);
    
                            return true;
                        }
    
                        return false;
                    }
    
                    return true;
                }
    
                return false;
            }
    
            // Unprotect the connectionStrings section. 
            public static void UnProtectConfiguration(string path)
            {
                // Get the application configuration file.
                Configuration config = ConfigurationManager.OpenExeConfiguration(path);
    
                // Get the section to unprotect.
                ConfigurationSection connStrings = config.ConnectionStrings;
    
                if (connStrings != null)
                {
                    if (connStrings.SectionInformation.IsProtected)
                    {
                        if (!connStrings.ElementInformation.IsLocked)
                        {
                            // Unprotect the section.
                            connStrings.SectionInformation.UnprotectSection();
    
                            connStrings.SectionInformation.ForceSave = true;
                            config.Save(ConfigurationSaveMode.Full);
                        }
                    }
                }
            }
    
            #endregion
        }
    }
    

    App.Config(注意 configProtectedData):

    <?xml version="1.0"?>
    <configuration>
      <configSections>
        <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
      </configSections>
      <connectionStrings>
        <add name="MyDbConnStr" providerName="System.Data.SqlClient" connectionString="Data Source=localhost;Initial Catalog=MyDb;Integrated Security=True;"/>
      </connectionStrings>
      <appSettings>
        <add key="SiteName" value="MyAwesomeSite"/>
      </appSettings> 
    <startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup>
        <configProtectedData>
            <providers>
                <add CertSubjectDistinguishedName="localhost" CertStoreName="MyCertKeyStore" name="X509ProtectedConfigProvider" type="ProtectedConfigProvider.X509ProtectedConfigProvider, X509ProtectedConfigProvider, Version=1.0.0.0, Culture=neutral, PublicKeyToken=098027505e2ed139" />
            </providers>
        </configProtectedData>
    </configuration>
    

    程序(使用):

    ...

    ProtectConfiguration("mysuperawesomeapp.exe);
    
    DatabaseFactory.SetDatabaseProviderFactory(new DatabaseProviderFactory());
    Database db = DatabaseFactory.CreateDatabase("MyDbConnStr");
    

    从 db 读取数据适用于加密的应用程序配置“connectionStrings”部分。 :)

    【讨论】:

      【解决方案2】:

      您可以在此处找到步骤:Walkthrough: Creating and Exporting an RSA Key Container。不需要证书,直接生成密钥容器即可。

      如果您要加密自定义配置部分,有一个技巧可以让它工作:您必须删除 configSection 的声明。我在这里写了详细信息:How to encrypt a custom configuration section in ASP.NET

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-07-17
        • 1970-01-01
        • 2018-08-03
        • 1970-01-01
        • 2010-12-10
        • 1970-01-01
        • 2011-09-02
        • 2018-01-27
        相关资源
        最近更新 更多