加密:
//-- 檔案加密(DES) --//
private byte[] EncryptDES(byte[] bData)
{
DES des = null;
ICryptoTransform ict = null;
MemoryStream ms = null;
CryptoStream cs = null;
BinaryWriter sw = null;
byte[] byteResult = null;
try
{
des = DES.Create();
des.Key = ASCIIEncoding.ASCII.GetBytes(Global.DESKey.Substring(0, 8));
des.IV = Global.DESIV;
ict = des.CreateEncryptor(des.Key, des.IV);
ms = new MemoryStream();
cs = new CryptoStream(ms, ict, CryptoStreamMode.Write);
sw = new BinaryWriter(cs);
foreach (byte b in bData)
{
sw.Write(b);
}
sw.Close();
cs.Close();
byteResult = ms.ToArray();
ms.Close();
return byteResult;
}
catch (Exception e)
{
throw e;
}
finally
{
if (sw != null) sw.Close();
if (cs != null) cs.Close();
if (ms != null) ms.Close();
}
}
解密:
//-- 檔案加解密(DES) --//
private byte[] DecryptDES(byte[] bData)
{
DES des = null;
ICryptoTransform ict = null;
MemoryStream ms = null;
CryptoStream cs = null;
BinaryReader sr = null;
byte[] bResult = new byte[Global.iFileLength];
try
{
des = DES.Create();
des.Key = ASCIIEncoding.ASCII.GetBytes(Global.DESKey.Substring(0, 8));
des.IV = Global.DESIV;
ict = des.CreateDecryptor(des.Key, des.IV);
ms = new MemoryStream(bData);
cs = new CryptoStream(ms, ict, CryptoStreamMode.Read);
sr = new BinaryReader(cs);
int i=0;
byte getByte;
while ((getByte = sr.ReadByte())!= 0x00)
{
bResult[i++] = getByte;
}
sr.Close();
cs.Close();
ms.Close();
return bResult;
}
catch (Exception e)
{
throw e;
}
finally
{
if (sr != null) sr.Close();
if (cs != null) cs.Close();
if (ms != null) ms.Close();
}
}
加/解密都是以 “Byte”的方式進行,把要加/解密的資料以 byte[] 的型態丟進來就可以了。

0 意見:
張貼意見