使用DES算法实现加密解密

时间:2023-03-08 21:26:00
使用DES算法实现加密解密

使用DES算法实现加密解密

我们常见的加密算法有DES、MD5、IDEA、AES等等,这篇随笔介绍使用DES算法实现加密解密

首先介绍一下DES算法:

DES算法为密码*中的对称密码*,又被称为美国数据加密标准,是1972年美国IBM公司研制的对称密码*加密算法。 明文按64位进行分组,密钥长64位,密钥事实上是56位参与DES运算(第8、16、24、32、40、48、56、64位是校验位, 使得每个密钥都有奇数个1)分组后的明文组和56位的密钥按位替代或交换的方法形成密文组的加密方法。

DES算法基本原理:

其入口参数有三个:key、data、mode。key为加密解密使用的密钥,data为加密解密的数据,mode为其工作模式。当模式为加密模式时,明文按照64位进行分组,形成明文组,key用于对数据加密,当模式为解密模式时,key用于对数据解密。实际运用中,密钥只用到了64位中的56位,这样才具有高的安全性。

附上常用的DES算法加密解密类:

 using System;
using System.IO;
using System.Security.Cryptography;
using System.Text; namespace CodeFirst.Common
{
public class Encryption
{
/// <summary>
/// 加密
/// </summary>
/// <param name="inputString">加密的字符串</param>
/// <returns></returns>
public static string DesEncrypt(string inputString)
{
return DesEncrypt(inputString, Key);
}
/// <summary>
/// 解密
/// </summary>
/// <param name="inputString">解密的字符串</param>
/// <returns></returns>
public static string DesDecrypt(string inputString)
{
return DesDecrypt(inputString, Key);
}
/// <summary>
/// 密匙
/// </summary>
public static string Key
{
get
{
return "hongye10";
}
}
/// <summary>
/// 加密字符串
/// 注意:密钥必须为8位
/// </summary>
/// <param name="strText">字符串</param>
/// <param name="encryptKey">密钥</param>
/// <param name="encryptKey">返回加密后的字符串</param>
public static string DesEncrypt(string inputString, string encryptKey)
{
byte[] byKey = null;
byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
try
{
byKey = System.Text.Encoding.UTF8.GetBytes(encryptKey.Substring(, ));
DESCryptoServiceProvider des = new DESCryptoServiceProvider();//加密服务提供者类
byte[] inputByteArray = Encoding.UTF8.GetBytes(inputString);
MemoryStream ms = new MemoryStream();//内存流
//将数据流连接到加密转换的流
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write);
cs.Write(inputByteArray, , inputByteArray.Length);
cs.FlushFinalBlock();
return Convert.ToBase64String(ms.ToArray());
}
catch (System.Exception error)
{
//return error.Message;
return null;
}
}
/// <summary>
/// 解密字符串
/// </summary>
/// <param name="this.inputString">加了密的字符串</param>
/// <param name="decryptKey">密钥</param>
/// <param name="decryptKey">返回解密后的字符串</param>
public static string DesDecrypt(string inputString, string decryptKey)
{
byte[] byKey = null;
byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
byte[] inputByteArray = new Byte[inputString.Length];
try
{
byKey = System.Text.Encoding.UTF8.GetBytes(decryptKey.Substring(, ));
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
inputByteArray = Convert.FromBase64String(inputString);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write);
cs.Write(inputByteArray, , inputByteArray.Length);
cs.FlushFinalBlock();
System.Text.Encoding encoding = new System.Text.UTF8Encoding();
return encoding.GetString(ms.ToArray());
}
catch (System.Exception error)
{
//return error.Message;
return null;
}
}
}
}

End!