Labels

slider

Recent

Navigation

Encryption and Decryption a String using C#

Encryption and Decryption a String using C#

Introduction

The previous articles dealt on extensive usage of HtmlAgility pack such as finding text by class name and HTML Writer. This particular one here talks about encryption and decryption of string using C#. Encryption and decryption are very much essential keeping in view about the potential data security threats in the present world.

Encryption and Decryption a String using C#

Encryption: Data Security Importance

Data is the most important part of any organization. It cannot be thrown open to the unauthorized public and the data needs to be delivered only to the intended. The intended party or the end-user on the other hand, however, needs to receive information completely. Over the ages and after a lot of advancements in the field of computer science, encryption and decryption of the data were found to be the most secure and convenient technique. This involves encoding the human-readable information into a non-readable form with the help of a secret key and then at the receiving side, the key is used to decode this non-readable form to readable. Anyone who gets hold of this encrypted data and is unauthorized will never be able to crack down what information is present in it.
The major chunks of information in today's world are technically some set of strings and therefore every organization must implement the encryption and decryption technique. If you are comfortable about manipulating HTML as discussed here, it is easy to understand how important it is to protect the data that is being carried. The practice of encryption and decryption falls into the category of cryptography.


Encryption: How to do it in C#

AES(Advanced Encryption Standard) is the practice followed most widely as its effectiveness is proven through years. Coming to its implementation in C# for our purpose, it is not rocket science as all the basic components are provided in the form of libraries and APIs. Follow the below steps to get a good idea about how to implement encryption and thereafter you can use it for your purposes.

Import the required namespaces:

using System;
using System.Security.Cryptography;
using System.IO;
using System.Text;
Among these, the namespace System.Security.Cryptography should be noticed here, as it provides all cryptographic services which include operations such as encoding  and decoding the data, generating random numbers, hashing and many more. Keys are auto generated when you create and use an instance of any encryption algorithmic classes and the default properties can be very well trusted to be secure. Thus, it should not be a big deal for someone who is not expert on cryptography to use these services.

Step #1

Define a method with the name of your choice for encrypting a string similar to the one shown here.


public static string EncryptString(string key, string plainInput)
{
 byte[] iv = new byte[16];
 byte[] array;
 using (Aes aes = Aes.Create())
 {
  aes.Key = Encoding.UTF8.GetBytes(key);
  aes.IV = iv;
  ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
  using (MemoryStream memoryStream = new MemoryStream())
  {
   using (CryptoStream cryptoStream = new CryptoStream((Stream)memoryStream, encryptor, CryptoStreamMode.Write))
   {
    using (StreamWriter streamWriter = new StreamWriter((Stream)cryptoStream))
    {
     streamWriter.Write(plainInput);
    }

    array = memoryStream.ToArray();
   }
  }
 }

 return Convert.ToBase64String(array);
}


  • Define an initialization vector which is nothing but a byte array of size 16. Inherit the AES which is an abstract base class that contains the implementations of the standard AES.
  • The method accepts two parameters i.e. the key and the string that needs to be encrypted. 
  • The key, is converted into byte array and the iv declared earlier is assigned to the aes instance iv field.
  • ICryptoTransform contains the basic cryptographic transformation services.
  • At last, the input plain text is encrypted, converted into a byte array and returned to the calling method as a base64 string.

Step #2

Define a method with the name of your choice for decrypting a string similar to the one shown here.
public static string DecryptString(string key, string cipherText)
{
 byte[] iv = new byte[16];
 byte[] buffer = Convert.FromBase64String(cipherText);
 using (Aes aes = Aes.Create())
 {
  aes.Key = Encoding.UTF8.GetBytes(key);
  aes.IV = iv;
  ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
  using (MemoryStream memoryStream = new MemoryStream(buffer))
  {
   using (CryptoStream cryptoStream = new CryptoStream((Stream)memoryStream, decryptor, CryptoStreamMode.Read))
   {
    using (StreamReader streamReader = new StreamReader((Stream)cryptoStream))
    {
     return streamReader.ReadToEnd();
    }
   }
  }
 }
}


  • The method accepts two parameters which are the key and the cipher text.
  • The cipher text is converted into byte array. 
  • The cipher text is deciphered using CryptoStream and is finally returned as a string.

Step #3

In the main method, declare a string which will hold the value for the key used in encryption and decryption. The value is arbitrary.

Step #4

Declare a variable input which is a concatenation of url along with query parameters. Here the parameters are encrypted by calling to the method defined by us earlier. We write onto the console this input to have an idea of how encrypted text looks like.

Step #5

Declare a variable decryptedInput which holds the decrypted value which is obtained by calling the decrypt method defined by us earlier.
The code for the main is shown below:
public static void Main()
{
 // declaring key
 var key = "b14ca5898a4e4133bbce2ea2315a1916";
 
 // encrypt parameters
 var input = string.Concat("https://myDomain.in/", "Encrypt.aspx?query=", EncryptString(key, string.Format("emailID={0}", "myemail@gmail.com")));
 
 Console.WriteLine("Encrypted Input: " + input);
 
 // decrypt parameters
 var decrptedInput = DecryptString(key, input.Substring(input.IndexOf("=") + 1)); 
 Console.WriteLine("Decrypted Input: " + decrptedInput);
}

Final Output


Conclusion

Cryptography is a very interesting topic and is quite challenging as you explore in deep about it.

Suggested Reading

Share

Anjan kant

Outstanding journey in Microsoft Technologies (ASP.Net, C#, SQL Programming, WPF, Silverlight, WCF etc.), client side technologies AngularJS, KnockoutJS, Javascript, Ajax Calls, Json and Hybrid apps etc. I love to devote free time in writing, blogging, social networking and adventurous life

Post A Comment:

0 comments: