Tuesday, April 14, 2015

How to do Query Strings Encryption in 5 minutes

In this article we describe Step by step How to do Query Strings Encryption in 5 minutes .
We are going to build here in just 5 minutes a simple query strings' obfuscator, meant to send  information on the query string.
However, this is not a sophisticated security tool to be used on sending classified information. The present utility just transforms a query string like the following: "$BenderRodriguez@gmail.com$MySubject$20150321"
into an obfuscated query string like this: "mlzcmFlbEBnbWFpbC5jb20kTXlTdWJqZWN0JDIwMTUvMDMvMjE%3D"

This encrypted string will later be Url encoded, since it is meant to be in an URL.
The complete MVC C# code for this tutorial can be found in the following GitHub repository:
https://github.com/CarmelSoftware/QueryStringEncrypter

How to do Query Strings Encryption in 5 minutes

Step by step How to do Query Strings Encryption in 5 minutes

We start the present example  by setting the "usings" needed for the encryption:

 Query Strings Encryption in 5 minutes


Next, create an Utility class "Encrypter" which will provide the "Encrypt" and the "Decrypt" functionalities:
 Query Strings Encryption
Inside that class, create an "Encrypt" method which gets a string argument and returns a Tuple<> object containing the encrypted string and a boolean flag informing whether the encryption was successful.
This method transforms the string in an array of bytes using Encoding.UTF8, and then converts the bytes in a Base64 string. Finally, we escape the string for using in an URL.
All exceptions are caught and, in case of error,  the method returns a false+errorMessage Tuple:
Encryption in 5 minutes


The second method to add is the Decryption method:
Encryption
This method operates acts just the opposite: it Unescapes the Base64 escaped-encrypted string in an array of bytes, then converts the bytes in a decoded string using Encoding.UTF8.  
The exceptions treatment is the same of the encoder method:
How to do Encryption in 5 minutes

The Encryption method will be called from a Controller as follows:

How to Encryption

The Decryption method is called this way:


How to do Query Strings Encryption in 5 minutes  1
Of course, you can use every separator that you wish, in place of the " $ " of our example. 

We hope this utility Encryption class example will be useful to you.

Happy programming.....

      by Carmel Schvartzman


כתב: כרמל שוורצמן