C# Encrypt Text Output

前端 未结 9 1274
没有蜡笔的小新
没有蜡笔的小新 2020-12-14 13:37

I have created a few little programs that export data to a text file using StreamWriter and then I read them back in using StreamReader. This works great and does what I nee

9条回答
  •  时光说笑
    2020-12-14 14:17

    While you could base64 encode or even fully encrypt your configuration data (with SHA1 or MD5) as already suggested, I think good practice would be to work with the framework classes dealing with configuration data (Configuration under the System.Configuration namespace) and it's built in ability to encrypt data (via the ProtectSection method of the ConfigurationSection class).

    First of all you should declare and initialize an instance:

    using System.Configuration;
    ...
    static void Main(string[] args)
        {
            Configuration config;
    
            config = ConfigurationManager.OpenExeConfiguration(/*path to config file*/); //Use ConfigurationManager.OpenMachineConfiguration(/*path to config file*/) when opening machine configuration
    ...
    

    After that you need to define a custom configuration section that defines your configuration (msdn example)

    Once you've done that you just need to initialize an instance of your custom configuration section and add it to the configuration file using this code:

    isTicked = config.Sections.Add("isTicked", customSection);
    

    To encrypt the section you just added use this code (with further examples in both VB.NET and C# found here):

    config.Sections["isTicked"].SectionInformation.ProtectSection("protection provider");
    

    The "DPAPIProtectedConfigurationProvider" and "RSAProtectedConfigurationProvider" are built in by default.

    Once you want to decrypt the section use this code:

    config.Sections["isTicked"].SectionInformation.UnprotectSection();
    

    To stress a point - encryption and decryption both take effect only after you save the configuration file

    To save the file, use the code:

    config.Save(); //config.SaveAs("string") is also available
    

    Further information about the relevant classes and methods can be found in the msdn, starting with the Configuration class page linked above.

提交回复
热议问题