Wednesday, July 9, 2014

Serialization in C#

The serialization and its uses are as follows.
Serialization is the process of converting an object into stream of bytes in order to store the object in a file, Memory, Database and in transferring the object over the network. The reverse process is called as De-Serialization. Please find the below Fig.
In order to achieve this serialization, the class should be encapsulated with [Serializable] attribute. Without this attribute, “Serialization” is not possible. If the base class is derived, then the both class should be encapsulate with[Serializable] attribute to achieve the serialization.
Given below the serialization example by using two classes.
namespace SerializationExample
{
    [Serializable]
    public class EmployeeSkill
    {
        public string Skill { getset; }
    }

    [Serializable]
    public class Employee : EmployeeSkill
    {
        public string Name { getset; }
        public int Experience { getset; }
    }
}
By using the above two classes I am going to show how to,

1.       Convert an object into bytes and vice versa.
2.       Serialize an object to save and retrieve the object from the text file.
3.       Serialize an object to save and retrieve the object from the XML file.

1.    Convert an object into bytes and vice versa.
namespace SerializationExample
{
    class Program
    {
        static void Main(string[] args)
        {
            var objSerializationObject = new Employee()
            {
                Name = "Employee",
                Experience = 3,
                Skill = ".Net"
            };
            var objConvertedToBytes = ConvertObjectToBytes(objSerializationObject);
            var objEmployee = (Employee)ConvertBytesToObject(objConvertedToBytes);
            Console.WriteLine(objEmployee.Name);
            Console.WriteLine(objEmployee.Experience);
            Console.WriteLine(objEmployee.Skill);
            Console.ReadLine();
        }
        #region Converting Object into Bytes
        /// <summary>
        /// To convert object into Bytes.
        /// </summary>
        /// <param name="objEmployee">Employee Object</param>
        /// <returns>Array Of Bytes</returns>
        public static byte[] ConvertObjectToBytes(Employee objEmployee)
        {
            if (objEmployee == nullreturn null;

            MemoryStream objMemoryStream = new MemoryStream();
            BinaryFormatter objBinaryFormatter = new BinaryFormatter();

            objBinaryFormatter.Serialize(objMemoryStream, objEmployee);
            return objMemoryStream.ToArray();
        }
        #endregion


        #region Converting Bytes into Original Object
        /// <summary>
        /// To convert bytes into Object.
        /// </summary>
        /// <param name="objArrayBytes">Array Of Bytes</param>
        /// <returns>Original Object</returns>
        public static Object ConvertBytesToObject(byte[] objArrayBytes)
        {
            MemoryStream objMemoryStream = new MemoryStream();
            BinaryFormatter objBinaryFormatter = new BinaryFormatter();
            objMemoryStream.Write(objArrayBytes, 0, objArrayBytes.Length);
            objMemoryStream.Seek(0, SeekOrigin.Begin);
            Object obj = (Object)objBinaryFormatter.Deserialize(objMemoryStream);
            return obj;
        }
        #endregion
    }
}

2.       Serialize  to save and retrieve an object from the text file.

namespace SerializationExample
{

  class Program
    {
        static void Main(string[] args)
        {
            var objSerializationObject = new Employee()
            {
                Name = "Employee",
                Experience = 3,
                Skill = ".Net"
            };


            #region Saving the object stream in the text file
            IFormatter objFormatter = new BinaryFormatter();
            Stream objStream = new FileStream("MyFile.txt"FileMode.Create, FileAccess.Write, FileShare.None);
            objFormatter.Serialize(objStream, objSerializationObject);
            objStream.Close();
            #endregion

            #region Read and Convert the Stream of bytes into original Object
            IFormatter objReadFormatter = new BinaryFormatter();
            Stream objReadStream = new FileStream("MyFile.txt"FileMode.Open, FileAccess.Read, FileShare.None);
            Employee objDeserialize = (Employee)objReadFormatter.Deserialize(objReadStream);
            objReadStream.Close();
            #endregion

            Console.WriteLine(objDeserialize.Name);
            Console.WriteLine(objDeserialize.Experience);
            Console.WriteLine(objDeserialize.Skill);
            Console.ReadLine();
        }
    }
}

3.       Serialize to save and retrieve an object from the XML file.


namespace SerializationExample
{
    class Program
    {
        static void Main(string[] args)
        {
            var objSerializationObject = new Employee()
            {
                Name = "Employee",
                Experience = 3,
                Skill = ".Net"
            };


            #region Saving the object stream in the XML file
            XmlSerializer objXMLSerializer = new XmlSerializer(typeof(Employee));

            StreamWriter objWriter = new StreamWriter("MyFile.XML");
            objXMLSerializer.Serialize(objWriter, objSerializationObject);
            objWriter.Close();
            #endregion

            #region Read the XML and Convert it into original Object
            StreamReader objReader = new StreamReader("MyFile.XML");
            Employee objDeserialize = (Employee)objXMLSerializer.Deserialize(objReader);
            objReader.Close();
            #endregion

            Console.WriteLine(objDeserialize.Name);
            Console.WriteLine(objDeserialize.Experience);
            Console.WriteLine(objDeserialize.Skill);
            Console.ReadLine();
        }
    }
}

Encryption and Decryption in C#

Encryption is used to transform a data into some un-readable form so that authenticated person only can read/access the data. It requires some secret information to transform the plain text to cipher text; it is usually referred as key.
There are many modern cryptographic methods used for encryption and decryption and it is classified in to two classes of key based algorithms.
1.       Symmetric Algorithm
a.        Same key is used for both Encryption and Decryption. The key will be kept as secret.
b.       Symmetric Ciphers is divided into Stream and Block Ciphers.
                                                               i.      Stream Ciphers – It encrypts a single bit of plain text at a time.
                                                             ii.      Block Ciphers –    It takes number of bits and encrypts them as a single unit.
2.       Asymmetric Algorithm
a.       Different key is used for Encryption and Decryption. It is also called as public Key algorithm.
b.      Encryption key is public and the Decryption key will be kept as secret.
c.       By using this asymmetric algorithm, anyone can encrypt the message by using encryption key but the message can be decrypted only by using decryption key.
3.       Hybrid Encryption – Symmetric and Asymmetric algorithm are used together and it is called as Hybrid Encryption.
  Algorithm Requirements:
1.       The Key will be kept secret and should be Random.
2.       It should not be possible to find the key even if the plain text and Cipher text are known.

  Types of Symmetric Encryption Algorithm:
1.       Data Encryption Standard (DES)
2.       Blow Fish
3.       Triple DES (3DES)
4.       Advanced Encryption Standard (AES)
  Below is the example for encryption and decryption in C# using Triple DES algorithm.
 Public class Program
    {
        static void Main(string[] args)
        {
            var text = "This is Plain Text";

            var encryptedText = CryptoGraphyExample.EncryptPlainTextToCipherText(text);
            var decryptedText = CryptoGraphyExample.DecryptCipherTextToPlainText(encryptedText);

            Console.WriteLine("Passed Text = " + text);
            Console.WriteLine("EncryptedText = " + encryptedText);
            Console.WriteLine("DecryptedText = " + decryptedText);

            Console.ReadLine();
        }
    }

public class CryptoGraphyExample
    {
        /// <summary>
        /// This security key should be very complex and Random for encrypting the text. This playing vital role in encrypting the text.
        /// </summary>
        private const string _securityKey = "MyComplexKey";


        /// <summary>
        /// This method is used to convert the plain text to Encrypted/Un-Readable Text format.
        /// </summary>
        /// <param name="PlainText">Plain Text to Encrypt before transferring over the network.</param>
        /// <returns>Cipher Text</returns>
        public static string EncryptPlainTextToCipherText(string PlainText)
        {
            //Getting the bytes of Input String.
            byte[] toEncryptedArray = UTF8Encoding.UTF8.GetBytes(PlainText);

            MD5CryptoServiceProvider objMD5CryptoService = new MD5CryptoServiceProvider();

            //Gettting the bytes from the Security Key and Passing it to compute the Corresponding Hash Value.
            byte[] securityKeyArray = objMD5CryptoService.ComputeHash(UTF8Encoding.UTF8.GetBytes(_securityKey));

            //De-allocatinng the memory after doing the Job.
            objMD5CryptoService.Clear();

            var objTripleDESCryptoService = new TripleDESCryptoServiceProvider();

            //Assigning the Security key to the TripleDES Service Provider.
            objTripleDESCryptoService.Key = securityKeyArray;

            //Mode of the Crypto service is Electronic Code Book.
            objTripleDESCryptoService.Mode = CipherMode.ECB;

            //Padding Mode is PKCS7 if there is any extra byte is added.
            objTripleDESCryptoService.Padding = PaddingMode.PKCS7;

            var objCrytpoTransform = objTripleDESCryptoService.CreateEncryptor();

            //Transform the bytes array to resultArray
            byte[] resultArray = objCrytpoTransform.TransformFinalBlock(toEncryptedArray, 0, toEncryptedArray.Length);

            //Releasing the Memory Occupied by TripleDES Service Provider for Encryption.
            objTripleDESCryptoService.Clear();

            //Convert and return the encrypted data/byte into string format.
            return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }


        /// <summary>
        /// This method is used to convert the Cipher/Encypted text to Plain Text.
        /// </summary>
        /// <param name="CipherText">Encrypted Text</param>
        /// <returns>Plain/Decrypted Text</returns>
        public static string DecryptCipherTextToPlainText(string CipherText)
        {
            byte[] toEncryptArray = Convert.FromBase64String(CipherText);

            MD5CryptoServiceProvider objMD5CryptoService = new MD5CryptoServiceProvider();

            //Gettting the bytes from the Security Key and Passing it to compute the Corresponding Hash Value.
            byte[] securityKeyArray = objMD5CryptoService.ComputeHash(UTF8Encoding.UTF8.GetBytes(_securityKey));

            //De-allocatinng the memory after doing the Job.
            objMD5CryptoService.Clear();

            var objTripleDESCryptoService = new TripleDESCryptoServiceProvider();

            //Assigning the Security key to the TripleDES Service Provider.
            objTripleDESCryptoService.Key = securityKeyArray;
           
            //Mode of the Crypto service is Electronic Code Book.
            objTripleDESCryptoService.Mode = CipherMode.ECB;

            //Padding Mode is PKCS7 if there is any extra byte is added.
            objTripleDESCryptoService.Padding = PaddingMode.PKCS7;

            var objCrytpoTransform = objTripleDESCryptoService.CreateDecryptor();

            //Transform the bytes array to resultArray
            byte[] resultArray = objCrytpoTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

            //Releasing the Memory Occupied by TripleDES Service Provider for Decryption.          
            objTripleDESCryptoService.Clear();

            //Convert and return the decrypted data/byte into string format.
            return UTF8Encoding.UTF8.GetString(resultArray);
        }
    }