This is a mirror of official site: http://jasper-net.blogspot.com/

AES Encrypted Serialization Tutorial

| Friday, April 8, 2011
Advanced Encryption Standard (AES) also called the Rijndael cipher, based off a combination of the two Belgian author's names Joan Daemen and Vincent Rijmen.  AES was accepted in 2002 to replace DES cipher and quickly became the preferred encryption choice to hide secret data. AES is a symmetric cipher, also known as shared key cipher, which means that it uses one single key for both encryption and decryption. 

In .Net the AES is visible through the System.Security.Cryptography namespace.
I use the RijndaelManaged class in this example to show you how to easily take a object, serialize it to an XML string, encode it to a byte array, and then deserialize it back to a new copy of the original object. 

This example originates from a recent project of mine where I needed to securely store a user object containing sensitive information. This way I can quickly load and save my serialized object to disk and have it encrypted using my secret key.

To show you the different steps, I created a Console App that goes through the different steps:

class Program
    {
        static void Main(string[] args)
        {
            const string SecretKey = "needstobe32bytesneedstobe32bytes"; //need to be 32 bytes for 256 bit encryption

            var oldUser = new User() {Password = "mysecret", Username = "MyName"};
            var str = Serializer.SerializeToString(oldUser); //Serialize User to XML string

            Console.WriteLine("Serialized object: "+str);
            User newUser = Serializer.FromString<User>(str); //Deserialize User from XML string
            Console.WriteLine("****");
            Console.WriteLine("Old user name is: "+oldUser.Username+" and new user name is: "+newUser.Username);
            Console.ReadKey();

            byte[] encryptedOldUser = Security.Encrypt(str, SecretKey); //Encrypt XML string using AES 
            Console.WriteLine("Encrypted old user: "+Encoding.ASCII.GetString(encryptedOldUser));

            Console.WriteLine("****");
            string decryptedOldUser = Security.Decrypt(encryptedOldUser, SecretKey); //Decrypt bytes
            Console.WriteLine("decrypted old user: " + decryptedOldUser);

            User secureUser = Serializer.FromString<User>(decryptedOldUser); //Serialize back to a new User object
            Console.WriteLine("****");
            Console.WriteLine("Old user name is: " + oldUser.Username + " and secure user name is: " + secureUser.Username);
            Console.ReadKey();

        }
    }

Read more: robbanp

Posted via email from Jasper-net

0 comments: