从C#代码加密/解密连接字符串

时间:2011-07-29 07:44:34

标签: c# .net asp.net

有什么方法可以从我的C#代码中实现对连接字符串的加密和解密。

像我们一样

aspnet_regiis -pe“connectionStrings”

aspnet_regiis -pd“connectionStrings”

由于

1 个答案:

答案 0 :(得分:0)

static public void ProtectSection()
{
    // Get the current configuration file.
    System.Configuration.Configuration config =
    ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

    // Get the section.
    UrlsSection section = (UrlsSection)config.GetSection("connectionStrings");

    // Protect (encrypt)the section.
    section.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider");

    // Save the encrypted section.
    section.SectionInformation.ForceSave = true;

    config.Save(ConfigurationSaveMode.Full);

    // Display decrypted configuration 
    // section. Note, the system
    // uses the Rsa provider to decrypt
    // the section transparently.
    string sectionXml =
    section.SectionInformation.GetRawXml();

    Console.WriteLine("Decrypted section:");
    Console.WriteLine(sectionXml);
}