加密XML,以便人们无法查看其数据 [英] Encrypt XML so that people can't look at its data
问题描述
您好,我创建了一个名为ClassA的类,我将其内容作为XML文件写入硬盘驱动器:
Hello, I created a class called "ClassA" and I write its content to hard drive as an XML file like this:
static void Write(ClassA cA)
{
var serializer = new XmlSerializer(typeof(ClassA));
using (var stream = new FileStream(System.IO.Path.Combine("C:\\","AFile.XML"), FileMode.Create))
{
serializer.Serialize(stream, cA);
stream.Close();
stream.Dispose();
}
}
我这样看了:
And I read it like this:
static ClassA Load()
{
var serializer = new XmlSerializer(typeof(ClassA));
using (FileStream stream = new FileStream(System.IO.Path.Combine("C:\\","AFile.XML"), FileMode.Open))
{
var container = serializer.Deserialize(stream) as ClassA;
stream.Close();
stream.Dispose();
return container;
}
}
问题是,XML文件显然是纯文本每个人都可以看到并改变它的价值观。如何加密整个XML文件,以便人们无法轻易操作它?如果你一步一步帮我,我会很高兴的。
谢谢。
我尝试了什么:
我试过这个加密,但它一直说密钥长度错误,我实际上并没有得到它是加密整个XML文件还是仅加密值。总的来说,它只是没有用,并一直说错误。
The problem is, the XML file is - obviously - plain text and everyone can see and change its values. How can I encrypt the whole XML file so that people can't easily manipulate it? I would be glad if you help step by step.
Thanks.
What I have tried:
I tried this for encrypting, but it kept saying "Wrong Key length" and I didn't actually get it whether it encrypts whole XML file or just the values. Overall, it just did not work and kept saying the error.
string sKey = //I tried 128, 32 and 256 bytes of string, none worked;
var serializer = new XmlSerializer(obj.GetType());
var stream = new FileStream(path, FileMode.Create);
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
ICryptoTransform desencrypt = DES.CreateEncryptor();
using(CryptoStream cStream = new CryptoStream(stream, desencrypt, CryptoStreamMode.Write)){
serializer.Serialize(cStream, obj);
}
stream.Close ();
示例代码位于以下链接中,您可以在那里找到其他部分(阅读,解密)。
< a href =https://www.reddit.com/r/Unity3D/comments/21jwhq/encrypting_an_xml_file/>加密XML文件:Unity3D [ ^ ]
推荐答案
参见< a href =https://docs.microsoft.com/en-us/dotnet/standard/security/encrypting-data>加密数据Microsoft Docs [ ^ ]。但是,如果您担心保护数据,那么XML不是最佳存储选择。
See Encrypting Data | Microsoft Docs[^]. However, if you are concerned about securing your data then XML is not the best storage choice.
使用LegalKeySizes来发现密钥的合法大小
Use LegalKeySizes to discover the legal size of your key
KeySizes[] sizes = DES.LegalKeySizes;
foreach (var s in sizes)
{
Debug.WriteLine(s.MinSize + " - " + s.MaxSize);
}
对于DES,您会看到这是最小值和最大值64,即它必须是64字节,如果使用ASCII字符构建密钥,则64字节为8个字符,因此密钥长度必须为8个字符。您也不应该为密钥和IV使用相同的字节。
For DES you'll see this is a min and max of 64, ie it has to be 64 bytes, and if you use ASCII characters to build your key then 64 bytes is 8 characters so the key has to be 8 characters in length. You also shouldn't use the same bytes for the key and the IV.
这篇关于加密XML,以便人们无法查看其数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!