tags:

views:

82

answers:

4

Tell me the easiest way to encrypt an XML file. It is a file used for some configurations and don't want people mucking around with it. Security is not an issue as it is a private tool.

+2  A: 

If you just want to make it harder to modify, send it through a DeflateStream. As an added benefit the file will be smaller.

adw
+4  A: 

If you don't care about security, just save the file together with a hash. Ie:

your.xml and your.xml.hash

You can use System.Security.Cryptography.MD5Managed for example. It's just to save the xml file, and then save a hash of the file itself. When reading, just calculate the hash, compare with what's saved, and then use your xml file as regular.

Of course, the information in the xml file isn't encrypted, it's possible to read, but if you edit the file then the hash won't be correct, and your program will discover the attempt. Keep it simple :)

Onkelborg
+1 . This is pretty popular. Usually you'll want to modify the hash a bit in some arbitrary fashion to make it that much trickier to reverse engineer, though.
Brian
Agree, but I made a reservation about that. Most likely, the user that might want to mess things up has no idea how to create a new hash anyway ;) And if the user really has the knowledge, then, well.. Start by disabling write access to the users, why do they have write access to config files? :)
Onkelborg
A: 

I'd probably just run the entire file through this class, which wraps the DPAPI, before reading/writing it. The resulting output is encoded so it can be written out as a text file:

using System;
using System.Security.Cryptography;
using System.Text;

/// <summary>
/// used for encryption and decryption
/// </summary>
public static class DataProtector
{
   private const string EntropyValue = "secret";

   /// <summary>
   /// Encrypts a string using the DPAPI.
   /// </summary>
   /// <param name="stringToEncrypt">The string to encrypt.</param>
   /// <returns>encrypt data</returns>
   public static string EncryptData(string stringToEncrypt)
   {
      byte[] encryptedData = ProtectedData.Protect(Encoding.Unicode.GetBytes(stringToEncrypt), Encoding.Unicode.GetBytes(EntropyValue), DataProtectionScope.LocalMachine);
      return Convert.ToBase64String(encryptedData);
   }

   /// <summary>
   /// Decrypts a string using the DPAPI.
   /// </summary>
   /// <param name="stringToDecrypt">The string to decrypt.</param>
   /// <returns>decrypted data</returns>
  public static string DecryptData(string stringToDecrypt)
   {
      byte[] decryptedData = ProtectedData.Unprotect(Convert.FromBase64String(stringToDecrypt), Encoding.Unicode.GetBytes(EntropyValue), DataProtectionScope.LocalMachine);
      return Encoding.Unicode.GetString(decryptedData);
   }
}
Russell McClure
+1  A: 

DPAPI is the simplest way to protect stuff in Windows systems - see ProtectedData.Protect for starters.

Steve Townsend