des加密解密源码 C# key值问题分析

前端技术 2023/09/06 C#

公司协议安全需求、需要对传输内容做des、md5加密。

因为是新人、刚交给我这个任务的时候有点眩晕。就开始在网上找各种des加密的内容。因为不懂以为需要把原理也搞明白,最后误了时间、把自己也搞糊涂了。当然,逻辑能力强、有兴趣的朋友可以试着去搞搞。

先贴加密、解密的源码:

复制代码 代码如下:

/// <summary>      

/// 加密数据      

/// </summary>      

/// <param name=\"Text\"></param>      

/// <param name=\"sKey\"></param>      

/// <returns></returns>      

public static string Encrypt(string Text, string sKey)         {          

DESCryptoServiceProvider des = new DESCryptoServiceProvider();          

byte[] inputByteArray;          

inputByteArray = Encoding.Default.GetBytes(Text);          

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

/// <summary>      

/// 解密数据      

/// </summary>      

/// <param name=\"Text\"></param>      

/// <param name=\"sKey\"></param>      

/// <returns></returns>      

public static string Decrypt(string Text, string sKey)         {          

DESCryptoServiceProvider des = new DESCryptoServiceProvider();          

int len;          

len = Text.Length / 2;          

byte[] inputByteArray = new byte[len];          

int x, i;          

for (x = 0; x < len; x++)             {              

i = Convert.ToInt32(Text.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

本文地址:https://www.stayed.cn/item/17391

转载请注明出处。

本站部分内容来源于网络,如侵犯到您的权益,请 联系我

我的博客

人生若只如初见,何事秋风悲画扇。