C#DES算法加密解密實例解析
C# DES算法加密解密作為我們開發中的安全部分我們需要明白它的使用,雖然56位密鑰的DES算法已經風光不在,而且常有用Des加密的明文被破譯的報道,但是了解一下昔日美國的標準加密算法總是有益的,而且目前DES算法得到了廣泛的應用,在某些場合,仍然發揮著余熱。
C# DES算法加密解密特點:分組比較短、密鑰太短、密碼生命周期短、運算速度較慢。C# DES算法加密解密工作的基本原理:其入口參數有三個:key、data、mode。key為加密解密使用的密鑰;data為加密解密的數據;mode為其工作模式。
C# DES算法加密解密核心代碼演示:DES是常用的對稱加密解密方法
- /**//// <summary>
- /// 進行DES加密。
- /// </summary>
- /// <param name="pToEncrypt">要加密的字符串。</param>
- /// <param name="sKey">密鑰,且必須為8位。</param>
- /// <returns>以Base64格式返回的加密字符串。</returns>
- public string Encrypt(string pToEncrypt, string sKey)
- {
- using (DESCryptoServiceProvider des =
- new DESCryptoServiceProvider())
- {
- byte[] inputByteArray = Encoding.UTF8.GetBytes(pToEncrypt);
- des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
- des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
- System.IO.MemoryStream ms = new System.IO.MemoryStream();
- using (CryptoStream cs = new CryptoStream(ms,
- des.CreateEncryptor(), CryptoStreamMode.Write))
- {
- cs.Write(inputByteArray, 0, inputByteArray.Length);
- cs.FlushFinalBlock();
- cs.Close();
- }
- string str = Convert.ToBase64String(ms.ToArray());
- ms.Close();
- return str;
- }
- }
- /**//// <summary>
- /// 進行C#DES解密。
- /// </summary>
- /// <param name="pToDecrypt">要解密的以Base64</param>
- /// <param name="sKey">密鑰,且必須為8位。</param>
- /// <returns>已解密的字符串。</returns>
- public string Decrypt(string pToDecrypt, string sKey)
- {
- byte[] inputByteArray = Convert.FromBase64String(pToDecrypt);
- using (DESCryptoServiceProvider des =
- new DESCryptoServiceProvider())
- {
- des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
- des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
- System.IO.MemoryStream ms = new System.IO.MemoryStream();
- using (CryptoStream cs = new CryptoStream(ms,
- des.CreateDecryptor(), CryptoStreamMode.Write))
- {
- cs.Write(inputByteArray, 0, inputByteArray.Length);
- cs.FlushFinalBlock();
- cs.Close();
- }
- string str = Encoding.UTF8.GetString(ms.ToArray());
- ms.Close();
- return str;
- }
- }
C# DES算法加密解密的基本情況就向你介紹到這里,希望對你了解和學習C# DES算法加密解密有所幫助。
【編輯推薦】