///<summary>
/// DES加密與解密
///</summary>
publicclass DESEncrypt
{
#region DES加密
///<summary>
/// 使用默認(rèn)密鑰加密
///</summary>
///<param name="strText"></param>
///<returns></returns>
publicstaticstring Encrypt(string strText)
{
return Encrypt(strText, "TSF");
}
///<summary>
/// 使用給定密鑰加密
///</summary>
///<param name="strText"></param>
///<param name="sKey">密鑰</param>
///<returns></returns>
publicstaticstring Encrypt(string strText, string sKey)
{
DESCryptoServiceProvider des =new DESCryptoServiceProvider();
byte[] inputByteArray = Encoding.Default.GetBytes(strText);
des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
System.IO.MemoryStream ms =new System.IO.MemoryStream();
CryptoStream cs =new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
StringBuilder ret =new StringBuilder();
foreach (byte b in ms.ToArray())
{
ret.AppendFormat("{0:X2}", b);
}
return ret.ToString();
}
#endregion
#region DES解密
///<summary>
/// 使用默認(rèn)密鑰解密
///</summary>
///<param name="strText"></param>
///<returns></returns>
publicstaticstring Decrypt(string strText)
{
return Decrypt(strText, "TSF");
}
///<summary>
/// 使用給定密鑰解密
///</summary>
///<param name="strText"></param>
///<param name="sKey"></param>
///<returns></returns>
publicstaticstring Decrypt(string strText, string sKey)
{
DESCryptoServiceProvider des =new DESCryptoServiceProvider();
int len = strText.Length /2;
byte[] inputByteArray =newbyte[len];
int x, i;
for (x =0; x < len; x++)
{
i = Convert.ToInt32(strText.Substring(x *2, 2), 16);
inputByteArray[x] = (byte)i;
}
des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
System.IO.MemoryStream ms =new System.IO.MemoryStream();
CryptoStream cs =new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
return Encoding.Default.GetString(ms.ToArray());
}
#endregion
}
D.E.S 是分塊加密的,將明文分割成 64 BITS 的塊, 然后他們一個(gè)個(gè)接起來 。他使用56位密鑰對(duì)64位的數(shù)據(jù)塊進(jìn)行加密,并對(duì)64bits的數(shù)據(jù)塊進(jìn)行16輪編碼。和每輪編碼時(shí),一個(gè)48bits的“每輪”密鑰值由56bits的完整密鑰得出來。DES用軟件進(jìn)行解碼需要用非常長(zhǎng)時(shí)間,而用硬件解碼速度非?,1977年,人們估計(jì)要耗資兩千萬美元才能建成一個(gè)專門計(jì)算機(jī)用于DES的解密,而且需要12個(gè)小時(shí)的破解才能得到結(jié)果。所以,當(dāng)時(shí)DES被認(rèn)為是一種十分強(qiáng)壯的加密方法。但今天, 只需 二十萬美圓就能制造一臺(tái)破譯DES的特別的計(jì)算機(jī),所以目前 DES 對(duì)需求“強(qiáng)壯”加密的場(chǎng)合已不再適用了。