2011-10-19 55 views
0

我想創建一個許可證文件,我需要它加密。我有License對象,List<License>licenses。在將流保存到xml文件之前,我需要對流進行加密,以防止它被輕易讀取。C#加密一個對象到一個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(); 

我很難將兩者結合起來。有人可以幫我從這裏出去嗎?

回答

3

其實,你應該考慮使用EncryptedXml這個類。您不是加密XML本身,而是加密XML內容。

加密可能需要不同的加密強度,關鍵基礎等方法。請按照MSDN文檔中的示例進行操作。這不是一個簡短的實現,但它工作得很好。

相關問題