Skip to main content
 首页 » 编程设计

c#之加密 SQL 连接字符串

2024年02月06日25kuangbin

我需要加密我的 connectionString - 我尝试使用

运行命令提示符
aspnet_regiis.exe -pef “connectionStrings” C:\Projects\DemoApplication 

它说没用

Cannot determine the location of .Net Framework 32 bit

  <connectionStrings> 
    <add name="DefaultConnection" connectionString="Data Source = |SQL/CE|"/> 
  </connectionStrings> 

而且我找不到其他方法。

有什么想法可以加密我的 connectionString 吗?

我正在使用 VS 2012 和 .NET 4.5

请您参考如下方法:

我目前使用这个自定义类

using System.Configuration; // Requires a reference to assembly System.Configuration 
 
public static class ConfigurationEncryptor { 
    [Flags] 
    public enum ConfigurationSectionType { 
        ConnectionStrings = 1, 
        ApplicationSettings = 2 
    } 
 
    public static bool Encrypt(ConfigurationSectionType section) { 
        bool result = false; 
 
        Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
        if (config == null) 
            throw new Exception("Cannot open the configuration file."); 
 
        if (section.HasFlag(ConfigurationSectionType.ConnectionStrings)) { 
            result = result || EncryptSection(config, "connectionStrings"); 
        } 
 
        if (section.HasFlag(ConfigurationSectionType.ApplicationSettings)) { 
            result = result || EncryptSection(config, "appSettings"); 
        } 
 
        return result; 
    } 
 
    private static bool EncryptSection(Configuration config, string section) { 
        ConfigurationSection currentSection = config.GetSection(section); 
        if (currentSection == null) 
            throw new Exception("Cannot find " + section + " section in configuration file."); 
        if (!currentSection.SectionInformation.IsProtected) { 
            currentSection.SectionInformation.ProtectSection("DataProtectionConfigurationProvider"); 
            config.Save(); 
 
            // Refresh configuration 
            ConfigurationManager.RefreshSection(section); 
 
            return true; 
        } 
        return false; 
    } 
} 

并使用它:

ConfigurationEncryptor.Encrypt( 
    ConfigurationEncryptor.ConfigurationSectionType.ApplicationSettings | 
    ConfigurationEncryptor.ConfigurationSectionType.ConnectionStrings 
    // Or just the app settings, or just the connection strings 
);