Encrypt and Decrypt Data using .Net Framework

This article explains how we can Encrypt and Decrypt data using .Net Framework

What You’ll learn:

  • Namespace – System.Security.Cryptography
  • Symmetric and Asymmetric Algorithms
  • Symmetric –  Key and IV (Initialization Vector)
  • Asymmetric – Public Key and Private Key
  • Encryption and Decryption

Background

Before we begin, we should know one important point is that – in order to Encrypt or Decrypt data, we must use a KEY along with an Encryption Algorithm to transform and secure any data.

  • KEY: the name itself  tells us that it the key which helps the sender or receiver to encrypt or decrypt the data respectively.
  • Encryption Algorithm: We have several standard algorithms available in the Cypher world and most of them are implemented and available for us to use in .NET framework.

Information: Interested to learn more about Cryptography concepts? – Here you go – Cryptography, The .NET Way

Namespace Used

  • System.Security.Cryptography

We have one single namespace available in .NET Framework is System.Security.Cryptography in order to perform Encrypting and Decrypting of data. Apart from these, this namespace also provides many cryptography related services such as Encoding and Decoding, Hashing, Message authentication etc.,

Information: To know more about Cryptography namespace, Here is the resource – MSDN Library – Cryptography.

Types of Encryption Algorithms

  • Symmetric Algorithms
    • Symmetric Algorithms will be used to perform on streams of data and hence we use these algorithms to encrypt large amounts of data.
    • These algorithms requires the creation of a KEY and an Initialization Vector(IV), wherein the KEY must be kept secret from anyone who should not decrypt our data and the IV need not to be secret and but should be changed for each session. we cannot store the IV created for this session to use in another session.
  • Asymmetric Algorithms
    • Asymmetric Algorithms will be used to perform data transformations on small bytes of data and hence we use these algorithms to encrypt small amounts of data.
    • These algorithms requires the creation of a pair of public and private keys. Wherein the public key can be made public to anyone and the private key must be known to only the receiver to decrypt the data encrypted using public key.
    • Generally we use Asymmetric Algorithms to encrypt the Symmetric Key and IV for transmitting to the remote user.

Creating Symmetric and Asymmetric Keys

By this time, we got to know that we must create Symmetric or Asymmetric Keys in order to use any algorithms to encrypt the data. In this section we will see how can we create both these Keys.

  • Symmetric Keys

As we have discussed, Every new session will create a new set of KEY and IV and these cannot be shared between the sessions.

  • Whenever we create an Instance of any managed Symmetric Cryptographic Class using its default constructor, the KEY and IV will be generated automatically.
  • Anyone who should Decrypt the data must possess the same KEY and IV with them and must use the same algorithm which was used to encrypt the data.
  • To communicate the KEY and IV which are used for the encryption with the remote party, usually we would encrypt the KEY and IV using some Asymmetric Algorithm because send keys over insecure network is unsafe as someone with KEY and IV can decrypt the data.

The following example will create the instance of TripleDESCryptoServiceProvider class that implements TripleDES Algorithm which will generate a KEY and IV automatically and stores them in KEY and IV properties of the created Instance.

TripleDESCryptoServiceProvider tripleDes = new TripleDESCryptoServiceProvider();

sometime we might need additional KEY and IV pairs, at that time we can simply call the GenerateKey() and GenerateIV() methods using the instance we created for the Symmetric class to get the new pair of KEY and IV.

tripleDes.GenerateKey();tripleDes.GenerateIV();

  • Asymmetric Keys

.NET Framework provides the following two classes for the encryption using Asymmetric algorithms:

    • RSACryptoServiceProvider
    • DSACryptoServiceProvider
  • Whenever we create an Instance of any managed Asymmetric Cryptographic Class using its default constructor, a pair of public and private keys will be generated automatically.
  • We can use the same pair of public/private keys in multiple sessions or we can create a separate pair for each session.
  • We can extract the created Keys using one of the two methods available under the Asymmetric Cryprographic class.
    • ToXMLString() – Generates Key information in XML format
    • ExportParameters()  Generates Key Information as RSAParameters type.
  • If we want to store the Private Key, we must use the Key Container to store them.

The following example will create the instance of RSACryptoServiceProvider class that implements RSA Algorithm which will generate a pair of public/private keys automatically and stores them in RSAParameters structure.

        //it will create an instance and will generate a pair of public/private keys        

RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();         //extracts the public key information into RSAParameters        RSAParameters rsaParam = rsa.ExportParameters(false);

Note: The boolean argument passed to ExportParamaeters represent whether to include the Private Key information or not.

Encrypting and Decrypting Data using Symmetric Algorithms

The method below will create an instance of TripleDESCryptoServiceProvider and Encrypts the clear text passed as an argument to it.

 

public static string SymmetricEncryptData(string clearText)    {        //create a byte array to store the encrypted result.        byte[] encryptedText;        //create an instance of UTF8 Encoding        System.Text.UTF8Encoding UTF8Encoding = new System.Text.UTF8Encoding();        //create an instance of any hash provider        MD5CryptoServiceProvider hash = new MD5CryptoServiceProvider();        //encode and then hash the shared private KEY.        byte[] tripleDESKey = hash.ComputeHash(UTF8Encoding.GetBytes(symmetricKey));         //create an instance of 3DES Cryptography class and assign the shared Key to that instance        TripleDESCryptoServiceProvider tripleDes = new TripleDESCryptoServiceProvider();        tripleDes.Key = tripleDESKey;        tripleDes.Mode = CipherMode.ECB;        tripleDes.Padding = PaddingMode.PKCS7;         //convert the input clear text to byte array         byte[] clearBytes = UTF8Encoding.GetBytes(clearText);        try        {            ICryptoTransform cryptoEncryptor = tripleDes.CreateEncryptor();            encryptedText = cryptoEncryptor.TransformFinalBlock(clearBytes, 0, clearBytes.Length);        }        finally        {            tripleDes.Clear();            hash.Clear();        }        return Convert.ToBase64String(encryptedText);    }

 

The method below will create an instance of TripleDESCryptoServiceProvider and Decrypts the cypher text passed as an argument to it.

public static string SymmetricDecryptData(string cypherText)    {        //create a byte array to store the encrypted result.        byte[] decryptedData;        //create an instance of UTF8 Encoding        System.Text.UTF8Encoding UTF8Encoding = new System.Text.UTF8Encoding();        //create an instance of any hash provider        MD5CryptoServiceProvider hash = new MD5CryptoServiceProvider();        //encode and then hash the shared private KEY.        byte[] tripleDESKey = hash.ComputeHash(UTF8Encoding.GetBytes(symmetricKey));         //create an instance of 3DES Cryptography class and assign the shared Key to that instance        TripleDESCryptoServiceProvider tripleDes = new TripleDESCryptoServiceProvider();        tripleDes.Key = tripleDESKey;        tripleDes.Mode = CipherMode.ECB;        tripleDes.Padding = PaddingMode.PKCS7;         //convert the input cypher text to byte array         byte[] cypherBytes = Convert.FromBase64String(cypherText);        try        {            ICryptoTransform cryptoDecryptor = tripleDes.CreateDecryptor();            decryptedData = cryptoDecryptor.TransformFinalBlock(cypherBytes, 0, cypherBytes.Length);        }        finally        {            tripleDes.Clear();            hash.Clear();        }        return UTF8Encoding.GetString(decryptedData);    }

The usage of above encryption and decryption methods is also implemented in the attached solution file.

Encrypting and Decrypting Data using Asymmetric Algorithms

I have implemented the Windows forms Solution for this Asymmetric Cryptography using RSA Algorithm.

Here are the methods to encrypt as well as decrypt the data.

static public byte[] AsymmetricEncrypt(byte[] clearText, RSAParameters KeyInfo, bool oaepPadding){    try    {        byte[] encryptedData;        //Create a new instance of RSACryptoServiceProvider.         using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())        {             //Import the RSA Key information. This only needs             //toinclude the public key information.            rsa.ImportParameters(KeyInfo);             //Encrypt the passed byte array and specify OAEP padding.               //OAEP padding is only available on Microsoft Windows XP or             //later.              encryptedData = rsa.Encrypt(clearText, oaepPadding);        }        return encryptedData;    }    //Catch and display a CryptographicException       catch (CryptographicException e)    {        return null;    } }static public byte[] AsymmetricDecrypt(byte[] cypherText, RSAParameters KeyInfo, bool oaepPadding)        {            try            {                byte[] decryptedData;                //Create a new instance of RSACryptoServiceProvider.                 using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())                {                    //Import the RSA Key information. This needs                     //to include the private key information.                    rsa.ImportParameters(KeyInfo);                     //Decrypt the passed byte array and specify OAEP padding.                       //OAEP padding is only available on Microsoft Windows XP or                     //later.                      decryptedData = rsa.Decrypt(cypherText, oaepPadding);                }                return decryptedData;            }            //Catch and display a CryptographicException               //to the console.             catch (CryptographicException e)            {                return null;            }        }

That’s all it. Hope you have successfully Encrypted and Decrypted your data. Please do comment if you face any issues.

Thank You.

 

I am a Consultant at Microsoft currently living in Hyderabad, India. My interests range from blogging to technology especially into /Web. I am also interested in movies and photography.

Leave a Reply

Skip to toolbar