简体   繁体   English

C#将对象加密为XML文件

[英]C# Encrypting an Object to an XML file

I am trying to create a license file and I need it encrypted. 我正在尝试创建许可证文件,我需要对其进行加密。

I have License object and List<License>licenses . 我有License对象和List<License>licenses I am needing to encrypt the stream prior to saving it to the xml file so that it can not be easily read. 我需要先将流加密,然后再将其保存到xml文件中,以使其无法轻松读取。

I have found this post: MSDN Code: Writing Class Data to an XML File (Visual C#) 我发现了这篇文章: 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();
   }
}

And this post: CodeProject: Using CryptoStream in C# 这篇文章: CodeProject:在C#中使用CryptoStream

Writing the xml file: 编写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();

Reading the xml file: 读取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();

I am having a hard time trying to combine the two. 我很难将两者结合起来。 Can anyone help me out here? 有人可以帮我从这里出去吗?

Actually, you should consider using the EncryptedXml class. 实际上,您应该考虑使用EncryptedXml类。 Rather than encrypting the XML itself, you encrypt the XML contents. 而不是加密XML本身,而是加密XML内容。

Encryption can entail different approaches for cryptographic strength, key bases, etc. Follow the examples in the MSDN documentation. 加密可能需要使用不同的方法来提高密码强度,密钥基础等。请遵循MSDN文档中的示例。 This is not a short implementation, but it works very well. 这不是一个简短的实现,但效果很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM