欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

DES 加密解密

发布时间:2025/3/13 38 豆豆
生活随笔 收集整理的这篇文章主要介绍了 DES 加密解密 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

【概念】 

数据加密算法(Data Encryption Algorithm,DEA)是一种对称加密算法,很可能是使用最广泛的密钥系统,特别是在保护金融数据的安全中,最初开发的DEA是嵌入硬件中的。通常,自动取款机(Automated Teller Machine,ATM)都使用DEA。它出自IBM的研究工作【from baidu】

 

【部分代码实现】

#region DES加密/解密字符串//默认密钥向量private static byte[] Keys = { 0x11, 0x22, 0x33, 0x44, 0x55, 0xAA, 0xBB, 0xCC };public static string EncryptDES(string encryptString){string encryptKey = StringUtils.ConvertToStr(GetConfig("CryptDESKey"), "abcd");//GetConfig方法为从配置文件读区数据return EncryptDES(encryptString, encryptKey);}/// <summary>/// DES加密字符串/// </summary>/// <param name="encryptString">待加密的字符串</param>/// <param name="encryptKey">加密密钥,要求为8位</param>/// <returns>加密成功返回加密后的字符串,失败返回源串</returns>public static string EncryptDES(string encryptString, string encryptKey){try{byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));byte[] rgbIV = Keys;byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();MemoryStream mStream = new MemoryStream();CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);cStream.Write(inputByteArray, 0, inputByteArray.Length);cStream.FlushFinalBlock();return Convert.ToBase64String(mStream.ToArray()).Replace("+", "%20");}catch (Exception ex){return string.Empty;}}public static string DecryptDES(string decryptString){string decryptKey = StringUtils.ConvertToStr(GetConfig("CryptDESKey"), "abcd");return DecryptDES(decryptString, decryptKey);}/// <summary>/// DES解密字符串/// </summary>/// <param name="decryptString">待解密的字符串</param>/// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param>/// <returns>解密成功返回解密后的字符串,失败返源串</returns>public static string DecryptDES(string decryptString, string decryptKey){try{byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey);byte[] rgbIV = Keys;byte[] inputByteArray = Convert.FromBase64String(decryptString.Replace(' ', '+'));DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();MemoryStream mStream = new MemoryStream();CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);cStream.Write(inputByteArray, 0, inputByteArray.Length);cStream.FlushFinalBlock();return Encoding.UTF8.GetString(mStream.ToArray());}catch (Exception ex){WrLogger logger = new WrLogger();logger.WriteException("App_Code.WebUtils.DecryptDES(string, string) Error, DecryptString:" + decryptString, ex);return string.Empty;}}#endregion

 注:此日志仅留作以后查询。

转载于:https://www.cnblogs.com/fo0ol/p/3614296.html

与50位技术专家面对面20年技术见证,附赠技术全景图

总结

以上是生活随笔为你收集整理的DES 加密解密的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。