关于对称加密算法,这个不多作解释,百度百科给出的说明如下:des对称加密,对称加密,是一种比较传统的加密方式,其加密运算、解密运算使用的是同样的密钥,信息的发送者和信息的接收者在进行信息的传输与处理时,必须共同持有该密码(称为对称密码),是一种对称加密算法。
简而言之就是用一个密钥加密的数据,也必须用该密钥来解密。这种方式在我们日常开发中非常常见。与之对应的就是非对称加密,广泛应用于web开发的https技术就是用了非对称加密和对称加密相结合的方式,这里不多作展开,我们只讨论对称加密。
下面是一个简单的demo,直接拿来用就行(测试在.NET Framework中可以完美运行)。
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace NETFrameworkTools
{
/// <summary>
/// DES对称加密和解密的工具类
/// </summary>
public static class DESTool
{
/// <summary>
/// DES加密字符串
/// </summary>
/// <param name="encryptString">待加密的字符串</param>
/// <param name="encryptKey">加密密钥,要求为8位</param>
/// <returns>加密成功返回加密后的字符串,失败返回源串</returns>
public static string EncryptDES(string encryptString, string key)
{
try
{
byte[] rgbKey = Encoding.UTF8.GetBytes(key);
//用于对称算法的初始化向量(默认值)。
byte[] rgbIV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
MemoryStream mStream = new MemoryStream();
CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
cStream.Write(inputByteArray, 0, inputByteArray.Length);
cStream.FlushFinalBlock();
return Convert.ToBase64String(mStream.ToArray());
}
catch(Exception ex)
{
throw ex;
}
}
/// <summary>
/// DES解密字符串
/// </summary>
/// <param name="decryptString">待解密的字符串</param>
/// <param name="key">解密密钥,要求8位</param>
/// <returns></returns>
public static string DecryptDES(string decryptString, string key)
{
try
{
//用于对称算法的初始化向量(默认值)
byte[] Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
byte[] rgbKey = Encoding.UTF8.GetBytes(key);
byte[] rgbIV = Keys;
byte[] inputByteArray = Convert.FromBase64String(decryptString);
DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
MemoryStream mStream = new MemoryStream();
CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
cStream.Write(inputByteArray, 0, inputByteArray.Length);
cStream.FlushFinalBlock();
return Encoding.UTF8.GetString(mStream.ToArray());
}
catch
{
return decryptString;
}
}
}
}
如有不正之处,还望大佬们多指点。