using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static string encryptKey = "Oyea" ; //定義密鑰
#region 加密字符串
/// <summary> /// 加密字符串
/// </summary>
/// <param name="str">要加密的字符串</param>
/// <returns>加密后的字符串</returns>
static string Encrypt( string str)
{
DESCryptoServiceProvider descsp = new DESCryptoServiceProvider(); //實例化加/解密類對象
byte [] key = Encoding.Unicode.GetBytes(encryptKey); //定義字節(jié)數(shù)組,用來存儲密鑰
byte [] data = Encoding.Unicode.GetBytes(str); //定義字節(jié)數(shù)組,用來存儲要加密的字符串
MemoryStream MStream = new MemoryStream(); //實例化內(nèi)存流對象
//使用內(nèi)存流實例化加密流對象
CryptoStream CStream = new CryptoStream(MStream, descsp.CreateEncryptor(key, key), CryptoStreamMode.Write);
CStream.Write(data, 0, data.Length); //向加密流中寫入數(shù)據(jù)
CStream.FlushFinalBlock(); //釋放加密流
return Convert.ToBase64String(MStream.ToArray()); //返回加密后的字符串
}
#endregion
#region 解密字符串
/// <summary>
/// 解密字符串
/// </summary>
/// <param name="str">要解密的字符串</param>
/// <returns>解密后的字符串</returns>
static string Decrypt( string str)
{
DESCryptoServiceProvider descsp = new DESCryptoServiceProvider(); //實例化加/解密類對象
byte [] key = Encoding.Unicode.GetBytes(encryptKey); //定義字節(jié)數(shù)組,用來存儲密鑰
byte [] data = Convert.FromBase64String(str); //定義字節(jié)數(shù)組,用來存儲要解密的字符串
MemoryStream MStream = new MemoryStream(); //實例化內(nèi)存流對象
//使用內(nèi)存流實例化解密流對象
CryptoStream CStream = new CryptoStream(MStream, descsp.CreateDecryptor(key, key), CryptoStreamMode.Write);
CStream.Write(data, 0, data.Length); //向解密流中寫入數(shù)據(jù)
CStream.FlushFinalBlock(); //釋放解密流
return Encoding.Unicode.GetString(MStream.ToArray()); //返回解密后的字符串
}
#endregion
static void Main( string [] args)
{
Console.Write( "請輸入要加密的字符串:" ); //提示輸入字符串
Console.WriteLine(); //換行輸入
string str = Console.ReadLine(); //記錄輸入的字符串
string strNew = Encrypt(str); //加密字符串
Console.WriteLine( "加密后的字符串:" + strNew); //輸出加密后的字符串
Console.WriteLine( "解密后的字符串:" + Decrypt(strNew)); //解密字符串并輸出
Console.ReadLine();
}
}
}
|