C# 的 DES 加密和解密方法(转)


DES加密应该是最基础的加密算法,为了搞清楚它在.NET C#里面的用法,我费了不少功夫,希望有心人能看到。
DES一共就有4个参数参与运作:明文、密文、密钥、向量。为了初学者容易理解,可以把4个参数的关系写成:密文=明文+密钥+向量;明文=密文-密钥-向量。为什么要向量这个参数呢?因为如果有一篇文章,有几个词重复,那么这个词加上密钥形成的密文,仍然会重复,这给破解者有机可乘,破解者可以根据重复的内容,猜出是什么词,然而一旦猜对这个词,那么,他就能算出密钥,整篇文章就被破解了!加上向量这个参数以后,每块文字段都会依次加上一段值,这样,即使相同的文字,加密出来的密文,也是不一样的,算法的安全性大大提高!

/// <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>
// 进行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;
 }
}  

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM