使用Linq To SQL时加密连接字符串

时间:2010-05-31 04:34:41

标签: asp.net linq-to-sql web-config

使用LINQ TO SQL时,加密web.config文件中的connectionStrings部分的最佳做法是什么?

2 个答案:

答案 0 :(得分:3)

首先,web.config / app.config中的加密部分并不仅限于Linq2Sql。 .Net框架附带了一组特殊的类,可以让你独立地加密/解密web.config / app.config的部分内容。

您可以使用DPAPI提供程序加密web.config的各个部分。您的应用程序中无需更改任何其他内容。你还在继续阅读appsettings和conn。像往常一样。使用以下代码加密/解密部分配置文件。

//call: ProtectSection("connectionStrings","DataProtectionConfigurationProvider"); 
private void ProtectSection(string sectionName, string provider) 
{ 
    Configuration config = 
        WebConfigurationManager. 
            OpenWebConfiguration(Request.ApplicationPath); 

    ConfigurationSection section = config.GetSection(sectionName); 

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

//call: UnProtectSection("connectionStrings"); 
private void UnProtectSection(string sectionName) 
{ 
    Configuration config = 
        WebConfigurationManager. 
            OpenWebConfiguration(Request.ApplicationPath); 

    ConfigurationSection section = config.GetSection(sectionName); 

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

答案 1 :(得分:1)

如果您觉得有必要这样做,您只需加密<connectionStrings>文件的web.config部分 - 这是一个标准的.NET程序,所有.NET代码都可以处理它 - 没有问题:

或谷歌或必应的Bing - 你会得到成千上万的点击.....