我正在尝试创建一个许可证文件,我需要加密它。
我有License
对象和List<License>licenses
。我需要在将流保存到xml文件之前对其进行加密,以便它不能轻易读取。
我发现了这个帖子:MSDN代码:将类数据写入XML文件(Visual c#)
public class Book
{
public string title;
static void Main()
{
Book introToVCS = new Book();
introToVCS.title = "Intro to Visual CSharp";
System.Xml.Serialization.XmlSerializer writer =
new System.Xml.Serialization.XmlSerializer(introToVCS.GetType());
System.IO.StreamWriter file =
new System.IO.StreamWriter("c:\IntroToVCS.xml");
writer.Serialize(file, introToVCS);
file.Close();
}
}
和这篇文章:CodeProject:在c#中使用CryptoStream
写入xml文件:
FileStream stream = new FileStream(�C:\test.txt�,
FileMode.OpenOrCreate,FileAccess.Write);
DESCryptoServiceProvider cryptic = new DESCryptoServiceProvider();
cryptic.Key = ASCIIEncoding.ASCII.GetBytes(�ABCDEFGH�);
cryptic.IV = ASCIIEncoding.ASCII.GetBytes(�ABCDEFGH�);
CryptoStream crStream = new CryptoStream(stream,
cryptic.CreateEncryptor(),CryptoStreamMode.Write);
byte[] data = ASCIIEncoding.ASCII.GetBytes(�Hello World!�);
crStream.Write(data,0,data.Length);
crStream.Close();
stream.Close();
读取xml文件:
FileStream stream = new FileStream(�C:\test.txt�,
FileMode.Open,FileAccess.Read);
DESCryptoServiceProvider cryptic = new DESCryptoServiceProvider();
cryptic.Key = ASCIIEncoding.ASCII.GetBytes(�ABCDEFGH�);
cryptic.IV = ASCIIEncoding.ASCII.GetBytes(�ABCDEFGH�);
CryptoStream crStream = new CryptoStream(stream,
cryptic.CreateDecryptor(),CryptoStreamMode.Read);
StreamReader reader = new StreamReader(crStream);
string data = reader.ReadToEnd();
reader.Close();
stream.Close();
我很难把这两者结合起来。有人能帮我一下吗?
实际上,您应该考虑使用EncryptedXml类。不是加密XML本身,而是加密XML内容。
加密可能需要不同的加密强度、密钥库等方法。遵循MSDN文档中的示例。这不是一个简短的实现,但它运行得非常好。