DES可实现对文本内容的加密和解密
DES设计中使用了分组密码设计的两个原则:混淆(confusion)和扩散(diffusion),其目的是抗击敌手对密码系统的统计分析。混淆是使密文的统计特性与密钥的取值之间的关系尽可能复杂化,以使密钥和明文以及密文之间的依赖性对密码分析者来说是无法利用的。扩散的作用就是将每一位明文的影响尽可能迅速地作用到较多的输出密文位中,以便在大量的密文中消除明文的统计结构,并且使每一位密钥的影响尽可能迅速地扩展到较多的密文位中,以防对密钥进行逐段破译。
DES加密源码:
/// <summary>
/// DES加密操作
/// </summary>
/// <param name="normalTxt"></param>
/// <returns></returns>
public static string DesEncrypt(string str, string key)
{
using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
{
byte[] inputByteArray = Encoding.UTF8.GetBytes(str);
des.Key = ASCIIEncoding.ASCII.GetBytes(key);
des.IV = ASCIIEncoding.ASCII.GetBytes(key);
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 result = Convert.ToBase64String(ms.ToArray());
ms.Close();
return result;
}
}
DES解密源码:
/// <summary>
/// DES解密操作
/// </summary>
/// <param name="securityTxt">加密字符串</param>
/// <returns></returns>
public static string DesDecrypt(string str, string key)//解密
{
byte[] inputByteArray = Convert.FromBase64String(str);
using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
{
des.Key = ASCIIEncoding.ASCII.GetBytes(key);
des.IV = ASCIIEncoding.ASCII.GetBytes(key);
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 result = Encoding.UTF8.GetString(ms.ToArray());
ms.Close();
return result;
}
}