Symmetric Encryption : Encryption « Security « C# / CSharp Tutorial






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

    class Program
    {
        static void Main(string[] args)
        {
            RijndaelManaged rmCrypto = new RijndaelManaged();
            byte[] key = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 };
            byte[] IV = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 };

            string clearMessage = "this is a test";

            FileStream fs = new FileStream("encrypted.dat", FileMode.Create);
            CryptoStream cs = new CryptoStream(fs, rmCrypto.CreateEncryptor(key, IV), CryptoStreamMode.Write);
            cs.Write(System.Text.ASCIIEncoding.ASCII.GetBytes(clearMessage),0, clearMessage.Length);
            cs.Close();
            fs.Close();

            FileStream fs2 = new FileStream("encrypted.dat", FileMode.Open);
            CryptoStream cs2 = new CryptoStream(fs2, rmCrypto.CreateDecryptor(key, IV), CryptoStreamMode.Read);
            byte[] decryptedData = new byte[fs2.Length];
            cs2.Read(decryptedData, 0, (int)fs2.Length);
            cs2.Close();
            fs2.Close();
            Console.WriteLine(System.Text.ASCIIEncoding.ASCII.GetString(decryptedData));
        }
    }








35.14.Encryption
35.14.1.Symmetric Encryption
35.14.2.PublicKey Cryptography
35.14.3.Secret Key Cryptography: RijndaelManaged
35.14.4.Create a new instance of the CipherData class using CipherReference information.
35.14.5.Use DataReference to encrypt and decrypt multiple XML elements using different session keys.