1. 首页 > 电脑教程 > C#实现DES加密算法与DES解密代码

C#实现DES加密算法与DES解密代码

DES ( data encryption Standard) 是一种世界标准的加密形式, 已15 年历史了,虽然有些老, 可还算是比较可靠的算法。在七十的初期, 随着计算机之间的通信发展, 需要有一种标准密码算法为了限制不同算法的激增使他们之间不能互相对话。为解决这个问题, 美国国家安全局(N.S.A ) 进行招标。 I.B.M 公司研发了一种算法, 称为:Lucifer。 经过几年的研讨和修改, 这种算法, 成为了今天的D.E.S,1976 年11月23 日, 终于被美国国家安全局采用。/// /// DES加密与解密 /// publicclass DESEncrypt { #region DES加密 /// /// 使用默认密钥加密 /// /// /// publicstaticstring Encrypt(string strText) { return Encrypt(strText, "TSF"); } /// /// 使用给定密钥加密 /// /// ///密钥 /// 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解密 /// /// 使用默认密钥解密 /// /// /// publicstaticstring Decrypt(string strText) { return Decrypt(strText, "TSF"); } /// /// 使用给定密钥解密 /// /// /// /// 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 的块, 然后他们一个个接起来 。他使用56位密钥对64位的数据块进行加密,并对64bits的数据块进行16轮编码。和每轮编码时,一个48bits的“每轮”密钥值由56bits的完整密钥得出来。DES用软件进行解码需要用非常长时间,而用硬件解码速度非常快,1977年,人们估计要耗资两千万美元才能建成一个专门计算机用于DES的解密,而且需要12个小时的破解才能得到结果。所以,当时DES被认为是一种十分强壮的加密方法。但今天, 只需 二十万美圆就能制造一台破译DES的特别的计算机,所以目前 DES 对需求“强壮”加密的场合已不再适用了。

声明:希维路由器教程网提供的内容,仅供网友学习交流,如有侵权请与我们联系删除,谢谢。ihuangque@qq.com
本文地址:https://www.ctrlcv.com.cn/diannao/169323124510617.html