Cryptography is the one step in ensuring confidentiality of your sensitive information.Cryptography features is available in all version of .Net Framework from 1.0 to 4.0. however Latest version of .Net framework providing new types and significant enhancement to existing types that can support support symmetric and asymmetric encryption and hasing efficiently.The .NET Framework provides implementations of many standard cryptographic algorithms. These algorithms are easy to use and have the safest possible default properties.The available algorithms or providers are available with in the "System.Security.Cryptography" namespace.In Cryptography there are two major aspects i.e. Encryption and Decryption.
Encryption :
Encryption is the process of translating plain text data into something that appears to be random and meaningless.By using this process we can hide original data and display some junk data and by using this we can provide some security to our data.Encrypted Text is also known as Ciphertext.
Decryption:
Decryption is the process of translating random and meaningless data to plain text.In other words decryption is the process of transforming data that has been rendered unreadable through encryption back to its unencrypted form. In decryption, the system extracts and converts the garbled data and transforms it to texts.
Before moving further we must have some basic idea about following things.Generally we can implement the Cryptography techniques in the following three ways :
Hashing:
Hashes aren't encryption,but they are fundamental to all other encryption operations. A hash is a data fingerprint - a tiny set of bytes that represents the uniqueness.Like fingerprints, no two should ever be alike, and a matching fingerprint is the proof of identity.
Symmetric Encryption:
In symmetric encryption, a single key is used for encrypting and decrypting the data. This type of encryption is quite fast, but has a problem i.e. in order to share a secret with someone, they have to know your key. This implies a very high level of trust between people sharing secrets; if an annonymous person has your key or if your key is hacked by a spy then they can decrypt all the messages you send using that key.
Asymmetric Encryption:
Asymmetric encryption solves the trust problem in symmetric encryption we generally use two different keys i.e. a public key for encrypting messages, and a private key for decrypting messages. Inthis process If an annonymous person has your public key, it's useless for decryption. They can't decrypt any of your messages! However, asymmetric encryption is very slow. It's not recommended for use on more than 1 kb of data.
Different Hashing Techniques(Using Crypto Class) :
The "Crypto" class is present under the "System.Web.Helpers" namespace and the encryption algorithms(service providers) are present within the "System.Security.Cryptography" namespace.During the encryption process there may some situation arise when we need a dynamic or mutable string at that time we take the help of the "StringBuilder" which is present under "System.Text" namespace. (In general we take a string as key value and will calculate hash by any one technique on input parameter string. This hash value would be used as real key for the encryption. ).For better security in cryptography we generally use the salt mechanism, a salt is random data that is used as an additional input to a one-way function that "hashes" a password or a key.
Crypto class exposes the following methods for hashing process in Asp.net/Asp.net MVC :
* string GenerateSalt()
This method generates a new Salt to be added to the input string before the hashing process would start. This string needs to be saved because recreating of an exact match is almost impossible.
* string Hash()
This function hashes the input string using either the default (SHA-256) algorithm or user can pass an algorithm for the ASP.NET/ASP.NET MVC to use to hash the password.
* string HashPassword()
This function returns an RFC 2898 hash value of the input string passed by the user.
* string SHA1()
Returns the SHA1 hashed value for the input string provided.
* string SHA256()
Same as the above, but the algorithm used is SHA-256.
* bool VerifyHashedPassword()
This method can be used by developers while authenticating the users. Because this method would check for the password sent by the user. Salt for the user would be saved in the database, and that salt would be added to the Password string provided by the user and then hashing would proceed resulting into the hashed value, if both values (the hashed value in database) and the value from user match then it returns true.
Examples of some Hashing Techniques:
Write the code under any action method of any Controller as per your wish as follows :
public class BuiltinFilterController : Controller
{
public ActionResult Index()
{
string key="Any Key String";
var hashedPassword = Crypto.HashPassword(key);
(OR)
var Md5 = Crypto.Hash(key, "MD5");
(OR)
var sha1 = Crypto.SHA1(key);
(OR)
var sha256 = Crypto.SHA256(key);
(OR)
var salt = Crypto.GenerateSalt();
var hashedPassword = Crypto.HashPassword(key + salt);
//And for veryfying we can use the following :
//Syntax: var verify = Crypto.VerifyHashedPassword(hashedPassword(any hashing
value),OriginalPassword);
var verify = Crypto.VerifyHashedPassword(hashedPassword, key + salt);
}
}
Example of Symmetric Key Cryptography(TripleDES) :
Create a new Asp.net MVC application or open an existing application. Inside the application add a controller named "SecureController"(you
can give any name) and write the following code :
//Import the namespaces
using System.Text;
using System.Security.Cryptography;
public class SecureController : Controller
{
private static byte[] encryptedByte;
public ActionResult TripleDes()
{
return View();
}
[HttpPost]
public ActionResult TripleDes(FormCollection frc)
{
string password = frc["txtPassword"];
string key = frc["txtKey"];
if (frc["ENC"] != null)
{
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
UTF8Encoding utf8 = new UTF8Encoding();
TripleDESCryptoServiceProvider tripleDES = new TripleDESCryptoServiceProvider();
tripleDES.Key = md5.ComputeHash(utf8.GetBytes(key));
tripleDES.Mode = CipherMode.ECB;
tripleDES.Padding = PaddingMode.PKCS7;
ICryptoTransform iTrans = tripleDES.CreateEncryptor();
encryptedByte =iTrans.TransformFinalBlock
(utf8.GetBytes(password),0,utf8.GetBytes(password).Length);
ViewBag.encrypt ="Encrypted Data : "+BitConverter.ToString(encryptedByte) ;
ViewBag.msg = "Provide only Key For the Decryption ...";
}
else
{
try {
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
UTF8Encoding utf8 = new UTF8Encoding();
TripleDESCryptoServiceProvider tripleDES = new
TripleDESCryptoServiceProvider();
tripleDES.Key = md5.ComputeHash(utf8.GetBytes(key));
tripleDES.Mode = CipherMode.ECB;
tripleDES.Padding = PaddingMode.PKCS7;
ICryptoTransform iTrans = tripleDES.CreateDecryptor();
ViewBag.encrypt = "Encrypted Data : " + BitConverter.ToString(encryptedByte);
ViewBag.decrypt = "Decrypted Data : " +
utf8.GetString(iTrans.TransformFinalBlock
(encryptedByte,0,encryptedByte.Length));
}
catch(Exception ex)
{
ViewBag.msg = "Provided Key is Incorrect Please Check it .... !!!";
}
}
return View();
}
}
Now, for the above action method create a View named "TripleDes.cshtml" and write the code as follows :
@{
ViewBag.Title = "TripleDes";
}
<h2>TripleDes Home Page</h2>
@using (Html.BeginForm())
{
<div>
Enter Password : @Html.TextBox("txtPassword")<br />
Enter Key : @Html.TextBox("txtKey")<br /><br />
@ViewBag.encrypt <br />
@ViewBag.msg<br />
@ViewBag.decrypt<br /><br />
<input type="submit" value="Encrypt" name="ENC" />
<input type="submit" value="Decrypt" name="DYC" />
</div>
}
Now,run the application and check the functionalities.
Example of Asymmetric Key Cryptography(RSA) :
To test this create a new Asp.net MVC application or open an existing application. Inside the application add a controller named
"SecureController"(you can give any name).In this encryption technique we need to generate the keys first then by the help of keys we have
to encrypt(Public Key) and decrypt(Private Key) the provided/required text.Now, write the following code :
//Import the namespaces
using System.Text;
using System.Security.Cryptography;
public class SecureController : Controller
{
private static RSAParameters PublicKey;
private static RSAParameters PrivateKey;
private static byte[] encrypted;
private byte[] decrypted;
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(FormCollection frc)
{
string password = frc["txtPassword"];
if (frc["ENC"] != null)
{
generateKeys();
encrypted = Encrypt(Encoding.UTF8.GetBytes(password));
ViewBag.encrypt ="Encrypted Text :"+ BitConverter.ToString(encrypted);
}
else
{
decrypted = Decrypt(encrypted);
ViewBag.decrypt ="Decrypted text :"+ Encoding.UTF8.GetString(decrypted);
}
return View();
}
static void generateKeys()
{
using(var rsa=new RSACryptoServiceProvider(2048))
{
rsa.PersistKeyInCsp = false;
PublicKey = rsa.ExportParameters(false);
PrivateKey = rsa.ExportParameters(true);
}
}
static byte[] Encrypt(byte[] password)
{
byte[] encrypted;
using (var rsa = new RSACryptoServiceProvider(2048))
{
rsa.PersistKeyInCsp = false;
rsa.ImportParameters(PublicKey);
encrypted = rsa.Encrypt(password,true);
}
return encrypted;
}
static byte[] Decrypt(byte[] encryptedText)
{
byte[] decrypted;
using (var rsa = new RSACryptoServiceProvider(2048))
{
rsa.PersistKeyInCsp = false;
rsa.ImportParameters(PrivateKey);
decrypted = rsa.Decrypt(encryptedText, true);
}
return decrypted;
}
}
Now, add a View for the controller's index action named "Index.cshtml" and write the following code :
@{
ViewBag.Title = "Index";
}
<h2>Index</h2><br />
@using (Html.BeginForm())
{
<div>
Enter Password : @Html.TextBox("txtPassword")<br />
@ViewBag.encrypt<br />
@ViewBag.decrypt<br />
<input type="submit" value="Encrypt" name="ENC" />
<input type="submit" value="Decrypt" name="DYC" />
</div>
}
Now, run the application and check the process of encryption and decryption.
Encoding and Decoding :
Generally,when we apply the cryptography techniques on the required text, we need to encode the required string into byte array so that the cryptographic algorithms should work properly because the algorithms need the byte array as input not the string.During encryption we need to convert the required string or text to byte array and during decryption we need to convert the byte array to string (back to the original form). So the process in which the string is converted into byte array is known as "Encoding" and the reverse process is known as "Decoding". Generally we use the "UTF8" encoding standard to encode or decode the text/string.To check the process of encoding and decoding lets se the following example. Create a new Asp.net MVC application or open an existing application. Inside the application add a controller named "SecureController"(you can give any name) ,define the action methods and create the corresponding view as follows :
//Import the namespace
using System.Text;
public class SecureController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(FormCollection frc)
{
string password = frc["txtPassword"];
if (frc["ENC"] != null)
{
string encodedText = Encode(password);
ViewBag.msg ="Encoded Text : "+ encodedText +"\n Copy and paste the Encoded text
in the textbox before pressing the 'Decode' button .";
}
else
{
string decodedText = Decode(password);
ViewBag.msg ="Decoded Text : "+ decodedText;
}
}
private string Encode(string password)
{
byte[] mybyte = Encoding.UTF8.GetBytes(password);
string returntext = System.Convert.ToBase64String(mybyte);
return returntext;
}
private string Decode(string password)
{
byte[] mybyte = System.Convert.FromBase64String(password);
string returntext = Encoding.UTF8.GetString(mybyte);
return returntext;
}
}
Code for View (Index.cshtml) :
@{
ViewBag.Title = "Index";
}
<h2>Index Page </h2><br />
@using (Html.BeginForm())
{
<div>
Enter Password : @Html.TextBox("txtPassword")<br />
@ViewBag.msg<br />
<input type="submit" value="Encode" name="ENC" />
<input type="submit" value="Decode" />
</div>
}
Now, run the application for checking the encoding and decoding process.
No comments:
Post a Comment