C# Encrypt Text Output

前端 未结 9 1276
没有蜡笔的小新
没有蜡笔的小新 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.

    0 讨论(0)
  • 2020-12-14 14:23

    You can add a checksum or hash to the file - if the file contents doesn't agree with the checksum, you know it was tampered with.

    If it is important that users can't read the contents of the file, you can encrypt it.

    I don't believe you can make a file that can't be tampered with (a savvy user could use a hex editor and change it, for example) - the best you can do is detect such tampering.

    0 讨论(0)
  • 2020-12-14 14:28

    You should call ProtectedData.Protect to encrypt the data using a per-user key.

    Note that it wouldn't be very hard for a skilled user to decrypt and modify the data.
    Anything that your program does on the user's machine can be done by the user too.

    0 讨论(0)
提交回复
热议问题