/*@file destest.cs
用C#2005编译OK
chinanetboy
*/
using System;
using System.IO;
using System.Security.Cryptography;
namespace TEST
{
class ExampleDES
{
//定制加密函数DESEncrypt
static byte[] DESEncrypt(String strInput, byte[] byteKey, byte[] byteIV)
{
DES des = null;
ICryptoTransform ict = null;
MemoryStream ms = null;
CryptoStream cs = null;
StreamWriter sw = null;
byte[] byteResult = null;
try
{
des = DES.Create();
des.Key = byteKey;
des.IV = byteIV;
ict = des.CreateEncryptor();
ms = new MemoryStream();
cs = new CryptoStream(ms, ict, CryptoStreamMode.Write);
sw = new StreamWriter(cs);
sw.Write(strInput);
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();
}
}//end DESEncrypt
//定制解密函数DESDecrypt
static String DESDecrypt(byte[] byteInput, byte[] byteKey, byte[] byteIV)
{
DES des = null;
ICryptoTransform ict = null;
MemoryStream ms = null;
CryptoStream cs = null;
StreamReader sr = null;
String strResult = String.Empty;
try
{
des = DES.Create();
des.Key = byteKey;
des.IV = byteIV;
ict = des.CreateDecryptor();
ms = new MemoryStream(byteInput);
cs = new CryptoStream(ms, ict, CryptoStreamMode.Read);
sr = new StreamReader(cs);
strResult = sr.ReadToEnd();
sr.Close();
cs.Close();
ms.Close();
return strResult;
}
catch (Exception e)
{ throw e; }
finally
{
if (sr != null) sr.Close();
if (cs != null) cs.Close();
if (ms != null) ms.Close();
}
}//end DESDecrypt
//Main() test
static void Main(string[] args)
{
byte[] byteKey = { 1, 2, 3, 4, 5, 6, 7, 8 };
byte[] byteIV = { 8, 7, 6, 5, 4, 3, 2, 1 };
byte[] byteEncrypt = null;
String strPlainText = String.Empty;
try
{
Console.WriteLine("DES SAMPLE WITH C#");
Console.WriteLine();
Console.Write("输入文字:");
// CALL DES 加密方法
byteEncrypt = DESEncrypt(Console.ReadLine(), byteKey, byteIV);
// 输出加密结果
Console.WriteLine("DES 密文是[用Base64编码]:{0}", Convert.ToBase64String(byteEncrypt));
// Call DES 解密方法
strPlainText = DESDecrypt(byteEncrypt, byteKey, byteIV);
// 输出解密结果
Console.WriteLine("DES 明文是:{0}", strPlainText);
}
catch (Exception e)
{ Console.Write("发生例外错误:" + e.Message); }
Console.ReadLine();
}//end main
}//end class
}//end namespace