简单的使用.NET对称加密的例子

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

/// <summary>
/// 使用对称加密的例子
/// </summary>
class Class1
{

static void Main(string[] args)
{
Class1 c
=new Class1();
c.StartDemo();
}

public void StartDemo()
{
//establish symmetric algorithm
SymmetricAlgorithm sa = Rijndael.Create();

//key and iv
sa.GenerateKey(); //产生随机的 (32*8) 位的密钥
//sa.GenerateIV(); //初始向量,在ECB模式里面可以不用IV
sa.Mode = CipherMode.ECB; //块处理模式
sa.Padding = PaddingMode.Zeros; //末尾数据块的填充模式


Console.WriteLine(
"密钥是:"); ///////////
for (int i=0; i<sa.Key.Length; i++) ///////////
{ ///////////
Console.Write("{0:X2} ",sa.Key[i]); ///////////
} ///////////
Console.WriteLine("\n"); ///////////


//establish crypto stream
MemoryStream ms = new MemoryStream();
CryptoStream cs
= new CryptoStream(ms,sa.CreateEncryptor(),CryptoStreamMode.Write);

//
string plaintext; //原始文本
byte[] cipherbytes; //加密后的数据
byte[] finalbytes; //解密后的数据

plaintext
="How are you? 这是一行文字。";
byte[] plainbytes = Encoding.UTF8.GetBytes(plaintext);


Console.WriteLine(
"原始文本是:\n{0}\n",plaintext);
//display plaint text byte array in hex format
Console.WriteLine("原始数据是:"); ///////////
for (int i=0; i<plainbytes.Length; i++) ///////////
{ ///////////
Console.Write("{0:X2} ",plainbytes[i]); ///////////
} ///////////
Console.WriteLine("\n"); ///////////

//加密过程
cs.Write(plainbytes, 0, plainbytes.Length);
cs.Close();
cipherbytes
= ms.ToArray();
ms.Close();

//display ciphertext byte array in hex format
Console.WriteLine("加密后的数据是:"); ///////////
for (int i=0; i<cipherbytes.Length; i++) ///////////
{ ///////////
Console.Write("{0:X2} ",cipherbytes[i]);///////////
} ///////////
Console.WriteLine("\n"); ///////////


//下面的为加密过程
ms=new MemoryStream(cipherbytes);
cs
=new CryptoStream(ms,sa.CreateDecryptor(),CryptoStreamMode.Read);
finalbytes
=new byte[plainbytes.Length];
cs.Read(finalbytes,
0,plainbytes.Length);

Console.WriteLine(
"解密后的数据是:"); ///////////
for (int i=0; i<finalbytes.Length; i++) ///////////
{ ///////////
Console.Write("{0:X2} ",finalbytes[i]); ///////////
} ///////////
Console.WriteLine("\n"); ///////////

string finaltext=Encoding.UTF8.GetString(finalbytes);

Console.WriteLine(
"解密后的文本是:\n{0}\n\n",finaltext );
Console.WriteLine(
"按任意键继续......");
Console.ReadLine();

}
}

 

http://blog.csdn.net/kwanhong/archive/2005/09/22/486783.aspx

 

 

posted @ 2010-04-09 16:06  庚武  Views(384)  Comments(0Edit  收藏  举报