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年技術見證,附贈技術全景圖總結
- 上一篇: win32/mfc/qt 异常处理与总结
- 下一篇: ctags对部分目录生成tags