Mã hóa dữ liệu với C#

Mã hóa dữ liệu với Cryptography

public class CryptographyTest
{

public static void Run()
{

//Console.WriteLine(“Enter the text file name”);
//string fname = Console.ReadLine();
Console.WriteLine(“Encrypting…”);
try
{

MemoryStream mem = new MemoryStream();

DESCryptoServiceProvider cryptic = new DESCryptoServiceProvider();
cryptic.Key = ASCIIEncoding.ASCII.GetBytes (“ABCDEFGH”);
cryptic.IV = ASCIIEncoding.ASCII.GetBytes(“ABCDEFGH”);

CryptoStream crStream = new CryptoStream(mem,cryptic.CreateEncryptor(),CryptoStreamMode.Write);
byte[] data = ASCIIEncoding.ASCII.GetBytes (“Hello World!”);
crStream.Write(data,0,data.Length);
crStream.FlushFinalBlock();

byte[] encryptedData = mem.ToArray();

Console.WriteLine(“Original Text: ” + System.Text.Encoding.Default.GetString(data));
Console.WriteLine(“Encrypted Text: ” + System.Text.Encoding.Default.GetString(encryptedData));

MemoryStream mem2 = new MemoryStream(encryptedData);
//Decrypt
CryptoStream deStream = new CryptoStream(mem2,cryptic.CreateDecryptor(),CryptoStreamMode.Read);
byte[] dedata = new byte[encryptedData.Length];

deStream.Read(dedata,0,dedata.Length);

Console.WriteLine(“Dencrypted Text: ” +System.Text.Encoding.Default.GetString(dedata));

crStream.Close();
mem.Close();
mem2.Close();
Console.WriteLine (“Done with Encrypting.”);

}
catch(Exception e)
{

Console.WriteLine (e.StackTrace);
Console.WriteLine (e.Message);

}

}

}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s