[粗]简单字符串加密及解密

2010-08-28 10:49:09来源:西部e网作者:

#endregion
using System;
using System.Security.Cryptography;
using System.IO;
using System.Text;

namespace SDSPNDSC.Common
{
 /// <summary>
 /// 通过DES对称加密算法,完成对字符串的加密和解密操作。
 /// </summary>
 public class Encrypt
 {
  private SymmetricAlgorithm mCSP;
  private const string CIV ="kXwL7X2+fgM=";//密钥
  private const string CKEY ="FwGQWRRgKCI=";//初始化向量

  public Encrypt()
  {
            mCSP = new DESCryptoServiceProvider();
  }

  public string EncryptString(string Value)
  {
   ICryptoTransform ct;
   MemoryStream ms;
   CryptoStream cs;
   byte[] byt;

   ct = mCSP.CreateEncryptor(Convert.FromBase64String(CKEY), Convert.FromBase64String(CIV));

   byt = Encoding.UTF8.GetBytes(Value);

   ms = new MemoryStream();
   cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
   cs.Write(byt, 0, byt.Length);
   cs.FlushFinalBlock();
 
   cs.Close();

   return Convert.ToBase64String(ms.ToArray());
  }

  public string DecryptString(string Value)
  {
   ICryptoTransform ct;
   MemoryStream ms;
   CryptoStream cs;
   byte[] byt;

   ct = mCSP.CreateDecryptor(Convert.FromBase64String(CKEY), Convert.FromBase64String(CIV));

   byt = Convert.FromBase64String(Value);

   ms = new MemoryStream();
   cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
   cs.Write(byt, 0, byt.Length);
   cs.FlushFinalBlock();

   cs.Close();

   return Encoding.UTF8.GetString(ms.ToArray());
  }

 }
}

赞助商链接: