文件加密处理(转)

由于是网络版系统,因而安全性要考虑周全。数据库连接字符串加密保存在配置文件中。为了防止软件XCopy到其它机器中,可以取机器的硬件(如硬盘、网卡、CPU)序列号的一部分再加上自己的私有密钥作为连接字符串的加密密钥(八位ASCII),确保密钥的私密性、每机器唯一性。 

 

(1)取得机器CPU的ID的前八位作为密钥: 

public static string Encode(string data) 

byte[] aKey = System.Text.ASCIIEncoding.ASCII.GetBytes(GetProcessID()); 

byte[] aIV = System.Text.ASCIIEncoding.ASCII.GetBytes(GetProcessID()); 

 

DESCryptoServiceProvider cp = new DESCryptoServiceProvider(); 

MemoryStream ms = new MemoryStream(); 

CryptoStream cs = new CryptoStream(ms, cp.CreateEncryptor(aKey, aIV), CryptoStreamMode.Write); 

StreamWriter sw = new StreamWriter(cs); 

 

sw.Write(data); 

sw.Flush(); 

cs.FlushFinalBlock(); 

sw.Flush(); 

return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length); 

 

 

(2)加密算法: 

 

 

public static string Encode(string data) 

byte[] aKey = System.Text.ASCIIEncoding.ASCII.GetBytes(GetProcessID()); 

byte[] aIV = System.Text.ASCIIEncoding.ASCII.GetBytes(GetProcessID()); 

 

DESCryptoServiceProvider cp = new DESCryptoServiceProvider(); 

MemoryStream ms = new MemoryStream(); 

CryptoStream cs = new CryptoStream(ms, cp.CreateEncryptor(aKey, aIV), CryptoStreamMode.Write); 

StreamWriter sw = new StreamWriter(cs); 

 

sw.Write(data); 

sw.Flush(); 

cs.FlushFinalBlock(); 

sw.Flush(); 

return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length); 

 

(3)解密算法:

 

public static string Decode(string data) 

byte[] aKey = System.Text.ASCIIEncoding.ASCII.GetBytes(GetProcessID()); 

byte[] aIV = System.Text.ASCIIEncoding.ASCII.GetBytes(GetProcessID()); 

 

byte[] Enc; 

try 

Enc = Convert.FromBase64String(data); 

catch 

return null; 

 

DESCryptoServiceProvider cp = new DESCryptoServiceProvider(); 

MemoryStream ms = new MemoryStream(Enc); 

CryptoStream cs = new CryptoStream(ms, cp.CreateDecryptor(aKey, aIV), CryptoStreamMode.Read); 

StreamReader sr = new StreamReader(cs); 

return sr.ReadToEnd(); 

你可能感兴趣的:(算法,加密,数据库,String,解密,byte)