天天看點

.NET資料庫連接配接字元串加密

exe程式(app.config)

使用configProtectionProvider屬性加密connectionStrings節點,具體參見:



Securing Connection Strings






其中提供的加密解密代碼:

static void ToggleConfigEncryption(string exeConfigName)
{
    // Takes the executable file name without the
    // .config extension.
    try
    {
        // Open the configuration file and retrieve 
        // the connectionStrings section.
        Configuration config = ConfigurationManager.
            OpenExeConfiguration(exeConfigName);

        ConnectionStringsSection section =
            config.GetSection("connectionStrings")
            as ConnectionStringsSection;

        if (section.SectionInformation.IsProtected)
        {
            // Remove encryption.
            section.SectionInformation.UnprotectSection();
        }
        else
        {
            // Encrypt the section.
            section.SectionInformation.ProtectSection(
                "DataProtectionConfigurationProvider");
        }
        // Save the current configuration.
        config.Save();

        Console.WriteLine("Protected={0}",
            section.SectionInformation.IsProtected);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}
 




      

ASP.NET (web.config)

asp.net方法和exe的方法相同,但官方提供了一個簡便的加密、解密方法:

How to: Secure Connection Strings When Using Data Source Controls

加密:

aspnet_regiis -pe "connectionStrings" -app "/SampleApplication"

解密:

aspnet_regiis -pd "connectionStrings" -app "/SampleApplication"