开发者

c# encrypt xml file

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 wit开发者_如何学Goh it. Security is not an issue as it is a private tool.


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 :)


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


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


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);
   }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜