告诉我加密XML文件的最简单方法。这是一个用于某些配置的文件,不希望人们使用它。安全性不是问题,因为它是一个私人工具。c#encrypt xml文件
2
A
回答
6
如果您不关心安全性,只需将文件与散列一起保存。即:
your.xml 和 your.xml.hash
可以使用System.Security.Cryptography.MD5Managed例如。这只是保存xml文件,然后保存文件本身的散列。阅读时,只需计算哈希值,与保存的内容进行比较,然后按常规使用xml文件。
当然,xml文件中的信息没有加密,可以读取,但是如果您编辑该文件,则哈希将不正确,并且您的程序将发现该尝试。保持简单:)
3
如果您只是想使其更难修改,请通过DeflateStream发送。作为一个额外的好处,该文件将更小。
0
我可能只是通过这个包装了DPAPI的类来运行整个文件,然后再读/写它。得到的输出编码,因此它可以写出一个文本文件:
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);
}
}
1
DPAPI是要保护的东西,在Windows系统中最简单的方法 - 看ProtectedData.Protect对于初学者。
如果它是一个私人工具,你试图保护文件的人是谁?自己呢? :P – 2010-10-25 18:17:37
哈哈,好问题。只是为了让人们不要触摸他们不应该做的事情。 – 2010-10-25 18:19:43
你能够使用标准的app.config(或web.config)文件还是必须是单独的XML文件? – 2010-10-25 18:20:29