private const string key="lyfhednc";
private const string iv="sikechtf";
public static void Main()
{
string str="hello,world!";
do
{
Console.WriteLine("原始-->{0}",str);
DESCryptoServiceProvider DES=new DESCryptoServiceProvider();
//Console.WriteLine(Encoding.ASCII.GetString(DES.IV));
//Console.WriteLine(Encoding.ASCII.GetString(DES.Key));
//DES.IV=Encoding.ASCII.GetBytes(iv);
//DES.Key=Encoding.ASCII.GetBytes(key); // 這裡可以指定使用的key與iv 沒有指定則是隨機的 所
// 以每 次 都 不一樣
byte[] b=Encrypt(str,DES);
str=Encoding.UTF8.GetString(b);
Console.WriteLine("加密-->{0}",str);
Console.WriteLine("解密-->{0}",Decrypt(b,DES));
}while((str=Console.ReadLine())!="a");
}
public static string Decrypt(byte[] CypherText, SymmetricAlgorithm key)
{
// Create a memory stream to the passed buffer.
MemoryStream ms = new MemoryStream(CypherText);
// Create a CryptoStream using the memory stream and the
// CSP DES key.
CryptoStream encStream = new CryptoStream(ms, key.CreateDecryptor(), CryptoStreamMode.Read);
// Create a StreamReader for reading the stream.
StreamReader sr = new StreamReader(encStream);
// Read the stream as a string.
string val = sr.ReadLine();
// Close the streams.
sr.Close();
encStream.Close();
ms.Close();
return val;
}
public static byte[] Encrypt(string PlainText, SymmetricAlgorithm key)
{
// Create a memory stream.
MemoryStream ms = new MemoryStream();
// Create a CryptoStream using the memory stream and the
// CSP DES key.
CryptoStream encStream = new CryptoStream(ms, key.CreateEncryptor(), CryptoStreamMode.Write);
// Create a StreamWriter to write a string
// to the stream.
StreamWriter sw = new StreamWriter(encStream);
// Write the plaintext to the stream.
sw.WriteLine(PlainText);
// Close the StreamWriter and CryptoStream.
sw.Close();
encStream.Close();
// Get an array of bytes that represents
// the memory stream.
byte[] buffer = ms.ToArray();
// Close the memory stream.
ms.Close();
// Return the encrypted byte array.
return buffer;
}
以上引用到:
using System.Security.Cryptography;
using System.IO;