一、前言
近几天,小编在项目中遇到了加密解密的这些技术,以前也接触过MD5加密解密算法。我说用MD5做得了,同组开发的崔哥说MD5不可逆,研究一下其他的加密解密的算法。然后就在网上找了DES的算法。
二、什么是DES?
DES全称为Data Encryption Standard,即数据加密标准,是一种使用密钥加密的块算法,1977年被美国联邦政府的国家标准局确定为联邦资料处理标准(FIPS),并授权在非密级政府通信中使用,随后该算法在国际上广泛流传开来。需要注意的是,在某些文献中,作为算法的DES称为数据加密算法(Data Encryption Algorithm,DEA),已与作为标准的DES区分开来。
三、封装的DES算法类
关于DES算法,他有一个核心的算法key,不同的key值可以得到不同的结果。所以小编把这个key值分析了一下,提取出来可以由用户自行设置。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;
namespace DESDecder
{
/// <summary>
/// DES加密解密算法
/// </summary>
public class DES
{
/// <summary>
/// DES加密算法
/// sKey为8位或16位
/// </summary>
/// <param name="pToEncrypt">需要加密的字符串</param>
/// <param name="sKey">密钥</param>
/// <returns></returns>
public string DesEncrypt(string pToEncrypt, string sKey)
{
StringBuilder ret = new StringBuilder();
try
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);
des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
foreach (byte b in ms.ToArray())
{
ret.AppendFormat("{0:X2}", b);
}
ret.ToString();
}
catch
{
}
return ret.ToString();
//return a;
}
/// <summary>
/// DES解密算法
/// sKey为8位或16位
/// </summary>
/// <param name="pToDecrypt">需要解密的字符串</param>
/// <param name="sKey">密钥</param>
/// <returns></returns>
public string DesDecrypt(string pToDecrypt, string sKey)
{
MemoryStream ms = new MemoryStream();
try
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
for (int x = 0; x < pToDecrypt.Length / 2; x++)
{
int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
inputByteArray[x] = (byte)i;
}
des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
StringBuilder ret = new StringBuilder();
}
catch
{
}
return System.Text.Encoding.Default.GetString(ms.ToArray());
}
#region 加密解密
public static DES dd = new DES();
public static string StringKey = "A123456."; // 加密密钥
/// <summary>
/// 解密
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string StringDecder(string str)
{
return dd.DesDecrypt(str, StringKey);
}
/// <summary>
/// 加密
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string StringEncoder(string str)
{
return dd.DesEncrypt(str, StringKey);
}
#endregion
}
}
四、小结
通过学习这个算法,算是对这个有了一定的了解了。在以后的算法学习过程中,只要有现成的例子就可以更加深入的学习,可以对比学习了。