Using System;
Using System. Security. cryptography;
Using System. text;
Using System. IO;
/// <Summary>
/// Example of Using symmetric encryption
/// </Summary>
Class Class1
{
Static Void Main ( String [] ARGs)
{
Class1 C = New Class1 ();
C. startdemo ();
}
Public Void Startdemo ()
{
// Establish shortric Algorithm
Symmetricalgorithm SA = Rijndael. Create ();
// Key and IV
SA. generatekey (); // Generate a random (32*8) Key.
// SA. generateiv (); // Initial vector, which can be used in ECB mode without IV
SA. Mode = Ciphermode. ECB; // Block Processing Mode
SA. padding = Paddingmode. Zeros; // Fill mode of the data block at the end
Console. writeline ( " The key is: " ); ///////// //
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; // Original Text
Byte [] Cipherbytes; // Encrypted data
Byte [] Finalbytes; // Decrypted data
Plaintext = " How are you? This is a line of text. " ;
Byte [] Plainbytes = Encoding. utf8.getbytes (plaintext );
Console. writeline ( " Original Text: \ n {0} \ n " , Plaintext );
// Display plaint text byte array in hex format
Console. writeline ( " Raw data is: " ); ///////// //
For ( Int I = 0 ; I < Plainbytes. length; I ++ ) ///////// //
{ ///////// //
Console. Write ( " {0: X2} " , Plainbytes [I]); ///////// //
} ///////// //
Console. writeline ( " \ N " ); ///////// //
// Encryption Process
CS. Write (plainbytes, 0 , Plainbytes. Length );
CS. Close ();
Cipherbytes = Ms. toarray ();
Ms. Close ();
// Display ciphertext byte array in hex format
Console. writeline ( " The encrypted data is: " ); ///////// //
For ( Int I = 0 ; I < Cipherbytes. length; I ++ ) ///////// //
{ ///////// //
Console. Write ( " {0: X2} " , Cipherbytes [I]); ///////// //
} ///////// //
Console. writeline ( " \ N " ); ///////// //
// The following describes the encryption process.
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 ( " The decrypted data is: " ); ///////// //
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 ( " The decrypted text is \ n {0} \ n " , Finaltext );
Console. writeline ( " Press any key to continue ...... " );
Console. Readline ();
}
}
Http://blog.csdn.net/kwanhong/archive/2005/09/22/486783.aspx