在上次DataSet的加密解密一文發佈後,有網友提出採用XML序列化的方式速度較慢,建議用二進制序列化。我覺得很有道理,下面是在VS2005種採用二進制序列化方式結合對稱加密算法對DataSet進行加密解密的代碼:
2using System.Collections;
3using System.Security.Cryptography;
4using System.IO ;
5using System.Data;
6using System.Runtime.Serialization.Formatters.Binary;
7namespace zjz.ClsDoCode
8{
9 /**//// <summary>
10 /// ClsEncryption 的摘要說明。
11 /// </summary>
12 public class ClsEncryption
13 {
14 public ClsEncryption()
15 {
16 //
17 // TODO: 在此處添加構造函數邏輯
18 //
19 }
20 //密鑰
21 //獲取或設置對稱算法的機密密鑰。機密密鑰既用於加密,也用於解密。爲了保證對稱算法的安全,必須只有發送方和接收方知道該機密密鑰。有效密鑰大小是由特定對稱算法實現指定的,密鑰大小在 LegalKeySizes 中列出。
22 private static byte[] DESKey = new byte[] {11, 23, 93, 102, 72, 41, 18, 12};
23 //獲取或設置對稱算法的初始化向量
24 private static byte[] DESIV = new byte[] {75, 158, 46, 97, 78, 57, 17, 36};
25
26 public static void EncryptDataSetToBinary(DataSet objDataSet, string outFilePath)
27 {
28 DESCryptoServiceProvider objDES = new DESCryptoServiceProvider();
29 FileStream fout = new FileStream(outFilePath, FileMode.OpenOrCreate, FileAccess.Write);
30 //用指定的 Key 和初始化向量 (IV) 創建對稱數據加密標準 (DES) 加密器對象
31 CryptoStream objCryptoStream = new CryptoStream(fout, objDES.CreateEncryptor(DESKey, DESIV), CryptoStreamMode.Write);
32 //StreamWriter objStreamWriter = new StreamWriter(objCryptoStream);
33 objDataSet.RemotingFormat = SerializationFormat.Binary;
34 BinaryFormatter bf = new BinaryFormatter();
35 bf.Serialize(objCryptoStream, objDataSet);
36 objCryptoStream.Close();
37 fout.Close();
38
39 }
40 public static DataSet DecryptDataSetFromBinary(string inBinFilePath)
41 {
42 DESCryptoServiceProvider objDES = new DESCryptoServiceProvider();
43 FileStream fin = new FileStream(inBinFilePath, FileMode.Open, FileAccess.Read);
44 //用指定的 Key 和初始化向量 (IV) 創建對稱數據加密標準 (DES) 加密器對象
45 CryptoStream objCryptoStream = new CryptoStream(fin, objDES.CreateDecryptor(DESKey, DESIV), CryptoStreamMode.Read);
46 BinaryFormatter bf = new BinaryFormatter();
47 DataSet ds = (DataSet)bf.Deserialize(objCryptoStream);
48 fin.Close();
49 return ds;
50 }
51 }
52}