1. 程式人生 > >字串加密解密

字串加密解密

using System.Security.Cryptography;

using System.IO;

//加密函式

static stirng Encrypt(string str)

{

   DESCryptoServiceProvider descsp=new DESCryptoServiceProvider();

   byte[] key=Encoding.Unicode.GetBytes(encryptKey);

   byte[] data=Encoding.Unicode.GetBytes(str);

   MemoryStream MStream=new MemoryStream();

  CryptoStream CStream= new CryptoStream(MStream,descsp.CreateEncryptor(key,key),CryptoStreamMode.Write);

  CStream.Write(data,0,data.Length);

  CStream.FlushFinalBlock();

  return Convert.ToBase64String(MStream.ToArray());

}

//解密函式

static stirng Decrypt(string str)

{

   DESCryptoServiceProvider descsp=new DESCryptoServiceProvider();

   byte[] key=Encoding.Unicode.GetBytes(encryptKey);

   byte[] data=Convert.FromBase64String(str);

   MemoryStream MStream=new MemoryStream();

  CryptoStream CStream= new CryptoStream(MStream,descsp.CreateEncryptor(key,key),CryptoStreamMode.Write);

  CStream.Write(data,0,data.Length);

  CStream.FlushFinalBlock();

  return Encoding.Unicode.GetString(MStream.ToArray()); 

}