【问题标题】:C# Encrypting an Object to an XML fileC# 将对象加密为 XML 文件
【发布时间】:2011-10-19 17:07:20
【问题描述】:

我正在尝试创建一个许可文件,我需要对其进行加密。

我有License 对象和List<License>licenses。我需要在将流保存到 xml 文件之前对其进行加密,以免被轻易读取。

我找到了这个帖子:MSDN Code: Writing Class Data to an XML File (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: Using CryptoStream in C#

编写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();

我很难将两者结合起来。有谁能帮帮我吗?

【问题讨论】:

    标签: c# xml encryption stream


    【解决方案1】:

    实际上,您应该考虑使用EncryptedXml 类。不是加密 XML 本身,而是加密 XML 内容。

    加密可能需要不同的加密强度、密钥库等方法。请按照 MSDN 文档中的示例进行操作。这不是一个简短的实现,但效果很好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-08
      • 1970-01-01
      • 2016-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-28
      • 1970-01-01
      相关资源
      最近更新 更多