加密解密 DESDecrypt
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;
namespace 加密解密
{
class Program
{
static void Main(string[] args)
{
string s = "hello";
string miwen = DES.DESEncrypt(s);
Console.WriteLine(miwen);
string jiemi = DES.DESDecrypt(miwen);
Console.WriteLine(jiemi);
Console.ReadKey();
}
}
public class DES
{
/// <summary>
/// 获取密钥
/// </summary>
private static string Key
{
get { return @"P@+#wG+Z"; }
}
/// <summary>
/// 获取向量
/// </summary>
private static string IV
{
get { return @"L%n67}G\Mk@k%:~Y"; }
}
/// <summary>
/// DES加密
/// </summary>
/// <param name="plainStr">明文字符串</param>
/// <returns>密文</returns>
public static string DESEncrypt(string plainStr)
{
byte[] bKey = Encoding.UTF8.GetBytes(Key);
byte[] bIV = Encoding.UTF8.GetBytes(IV);
byte[] byteArray = Encoding.UTF8.GetBytes(plainStr);
string encrypt = null;
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
try
{
using (MemoryStream mStream = new MemoryStream())
{
using (CryptoStream cStream = new CryptoStream(mStream, des.CreateEncryptor(bKey, bIV), CryptoStreamMode.Write))
{
cStream.Write(byteArray, 0, byteArray.Length);
cStream.FlushFinalBlock();
encrypt = Convert.ToBase64String(mStream.ToArray());
}
}
}
catch { }
des.Clear();
return encrypt;
}
/// <summary>
/// DES解密
/// </summary>
/// <param name="encryptStr">密文字符串</param>
/// <returns>明文</returns>
public static string DESDecrypt(string encryptStr)
{
byte[] bKey = Encoding.UTF8.GetBytes(Key);
byte[] bIV = Encoding.UTF8.GetBytes(IV);
byte[] byteArray = Convert.FromBase64String(encryptStr);
string decrypt = null;
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
try
{
using (MemoryStream mStream = new MemoryStream())
{
using (CryptoStream cStream = new CryptoStream(mStream, des.CreateDecryptor(bKey, bIV), CryptoStreamMode.Write))
{
cStream.Write(byteArray, 0, byteArray.Length);
cStream.FlushFinalBlock();
decrypt = Encoding.UTF8.GetString(mStream.ToArray());
}
}
}
catch { }
des.Clear();
return decrypt;
}
}
}