//************************************************************************************ // // Copyright (c) 2007 Mohammad Sadeq Dousti // All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, provided that the above // copyright notice(s) and this permission notice appear in all copies of // the Software and that both the above copyright notice(s) and this // permission notice appear in supporting documentation. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT // OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR // HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL // INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING // FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, // NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION // WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. // //************************************************************************************ using System; using System.Collections.Generic; using System.Text; using System.Security.Cryptography; using System.IO; class Program { static void Main(string[] args) { //When creating a DES cipher, .NET sets its Key and IV to random values. DES des = DES.Create(); /* * You may set your own Key and IV as follows: * des.Key = new byte[] { 0xBE, 0xC9, 0x52, 0x01, 0x96, 0x18, 0xE1, 0xAB }; * des.IV = new byte[] { 0x8E, 0x2F, 0xCB, 0xFC, 0x92, 0xE9, 0x96, 0xAF }; */ //Set operating mode to ECB; default mode is CBC des.Mode = CipherMode.ECB; //Set padding algorithm to none; default mode is PKCS7 des.Padding = PaddingMode.None; //DES plain texts are 64 bits (8 bytes) byte[] plain = new byte[8]; // Create a random number generator to fill plain text with random data RandomNumberGenerator rng = RandomNumberGenerator.Create(); rng.GetBytes(plain); //Please refer to MSDN to see what the heck is going on here ;) MemoryStream ms= new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(plain, 0, plain.Length); cs.Close(); byte[] cipher = ms.ToArray(); ms.Close(); Console.WriteLine("Plaintext:\t{0}", BitConverter.ToString(plain)); Console.WriteLine("Key:\t\t{0}", BitConverter.ToString(des.Key)); Console.WriteLine("Ciphertext:\t{0}", BitConverter.ToString(cipher)); // Release resources! des.Clear(); } }