public static class DESSecurity
{
#region DES加密字符串
/// <summary>
/// DES加密方法
/// </summary>
/// <param name="plain">明文</param>
/// <param name="key">密钥</param>
/// <param name="iv">向量</param>
/// <param name="isBase64">生成的密码是否用base64编码</param>
/// <returns>密文</returns>
public static String EncryptDES(string plain, byte[] rgbKey, byte[] rgbIV)
{
if (rgbKey.Length != 8) throw new ArgumentException("长度必须为8。", "rgbKey");
if (rgbIV.Length != 8) throw new ArgumentException("长度必须为8。", "rgbIV");
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
using (StreamWriter sw = new StreamWriter(cs))
{
sw.Write(plain);
sw.Flush();
cs.FlushFinalBlock();
ms.Flush();
return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);
}
}
#endregion
#region DES解密字符串
/// <summary>
/// DES解密方法
/// </summary>
/// <param name="cipher">密文</param>
/// <param name="key">密钥</param>
/// <param name="iv">向量</param>
/// <param name="isBase64">密文是否用base64解码</param>
/// <returns>明文</returns>
public static String DecryptDES(string cipher, byte[] key64, byte[] iv64)
{
byte[] bytesCipher;
bytesCipher = Convert.FromBase64String(cipher);
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
MemoryStream ms = new MemoryStream(bytesCipher);
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(key64, iv64), CryptoStreamMode.Read);
using (StreamReader sr = new StreamReader(cs))
{
return sr.ReadToEnd();
}
}
#endregion