Encrypt and Decrypt Text in Web API

Introduction

In this article, I will show you how to encrypt and decrypt text. Here we convert the text into a secret form by encrypting it and convert it back into its original text by decrypting it.

Encrypt : It is process of converting text into a secret form that cannot be readable by other humans. It can only be read by that person that has the encryption key. This is basically used for security.

Decrypt : It is the reverse of encryption. It converts the encrypted text back into its original text. It requires a secret key.

Procedure for creating the application.

Step 1

First we create a Web API application as in the following:

  • Start Visual Studio 2012.
  • From the start window select "New Project".
  • From the new project window select "Installed" -> "Visual C#" -> "Web".
  • Select "ASP.NET MVC4 Web Application" and click the "OK" button.

    en.jpg
  • From the "MVC4 Project" window select "Web API".

    en1.jpg
  • Click the "OK" button.

Step 2

Create a Model class as in the following:

  • In the "Solution Explorer".
  • Right-click on the "Model folder" then select "Add" -> "Class".
  • From the Add Item window select "Installed" -> "Visual C#".

    en2.jpg
  • Select Class and click the "Add" button.

Add the following code:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. namespace EncriptCode.Models  
  6. {  
  7.     public class EModel  
  8.     {  
  9.         public string word { getset; }  
  10.     }  
  11. } 

Step 3

In the "HomeController" write the code to encrypt and decrypt the text. This file exists:

  • In the "Solution Explorer".
  • Expand the Controller folder.
  • Select "HomeController".

    en3.jpg

Add the following code:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using EncriptCode.Models;  
  7. using System.Text;  
  8. using System.Security.Cryptography;  
  9. namespace EncriptCode.Controllers  
  10. {  
  11.     public class HomeController : Controller  
  12.     {  
  13.          string key = "1prt56";     
  14.          public ActionResult Index()  
  15.          {  
  16.             EModel obj = new EModel();  
  17.             return View(obj);  
  18.         }  
  19.         [HttpPost]  
  20.         public ActionResult Index( EModel obj)  
  21.         {  
  22.             int req = Convert.ToInt32(Request.Form["type"]);  
  23.             if (req == 1)  
  24.             {  
  25.                 ViewBag.Result = Encryptword(obj.word);  
  26.             }  
  27.             else  
  28.             {  
  29.                 ViewBag.Result = Decryptword(obj.word);  
  30.             }  
  31.             return View(obj);  
  32.         }  
  33.         public string Encryptword(string Encryptval)  
  34.         {  
  35.             byte[] SrctArray;  
  36.             byte[] EnctArray = UTF8Encoding.UTF8.GetBytes(Encryptval);  
  37.             SrctArray = UTF8Encoding.UTF8.GetBytes(key);  
  38.             TripleDESCryptoServiceProvider objt = new TripleDESCryptoServiceProvider();  
  39.              MD5CryptoServiceProvider objcrpt = new MD5CryptoServiceProvider();  
  40.             SrctArray = objcrpt.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));  
  41.             objcrpt.Clear();  
  42.             objt.Key = SrctArray;  
  43.             objt.Mode = CipherMode.ECB;  
  44.             objt.Padding = PaddingMode.PKCS7;  
  45.             ICryptoTransform crptotrns = objt.CreateEncryptor();  
  46.             byte[] resArray = crptotrns.TransformFinalBlock(EnctArray, 0, EnctArray.Length);  
  47.             objt.Clear();  
  48.             return Convert.ToBase64String(resArray, 0, resArray.Length);  
  49.         }  
  50.         public string Decryptword(string DecryptText)  
  51.         {  
  52.             byte[] SrctArray;  
  53.             byte[] DrctArray = Convert.FromBase64String(DecryptText);  
  54.             SrctArray = UTF8Encoding.UTF8.GetBytes(key);  
  55.             TripleDESCryptoServiceProvider objt = new TripleDESCryptoServiceProvider();  
  56.             MD5CryptoServiceProvider objmdcript = new MD5CryptoServiceProvider();  
  57.             SrctArray = objmdcript.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));  
  58.             objmdcript.Clear();  
  59.             objt.Key = SrctArray;  
  60.             objt.Mode = CipherMode.ECB;  
  61.             objt.Padding = PaddingMode.PKCS7;  
  62.             ICryptoTransform crptotrns = objt.CreateDecryptor();  
  63.             byte[] resArray = crptotrns.TransformFinalBlock(DrctArray, 0, DrctArray.Length);  
  64.             objt.Clear();  
  65.             return UTF8Encoding.UTF8.GetString(resArray);  
  66.         }  
  67.     }  
  68. } 

UTF8Encoding.UTF8.GetBytes : It encodes the specified string into a specified byte array.

TripleDESCrptoServiceProvider : It provides a wrapper object for accessing the cryptographic service provider version of the TripelDES algorithm. We use the "System.Security.Cryptography" namespace for it.

CipherMode.ECB : CipherMode specifies a block cipher mode for the encryption and the ECB (Electronic Codebook) that encrypts every block individually.

MD5CryptoServiceProvider :  It computes the MD5 hash value for the input data using the implementation provided by the cryptographic service provider.

PaddingMode.PKCS7 : Padding is applied when the message data block is shorter than the number of bytes needed for the cryptography. And the PKCS7 padding string consists of a sequence of bytes.

Step 4

Now use the "index.cshtml" file. This file exists:

  • In the "Solution Explorer".
  • Expand the Views folder.
  • Select "Home" -> "index.cshtml".

    en4.jpg

Add the following code:

  1. @model EncriptCode.Models.EModel  
  2. @{  
  3.     ViewBag.Title = "Code for Encrypt and Decrypt the Text in Web API";  
  4. }  
  5. @using (Html.BeginForm("Index""Home", FormMethod.Post))  
  6. {  
  7.     <h2>  
  8.         Encrypt and Decrypt Text</h2>  
  9.     @Html.TextBoxFor(p => p.word, new { @style = "width:200px" })  
  10.     <div>  
  11.         @Html.RadioButton("type", 1, true)EncryptText  
  12. <br>@Html.RadioButton("type", 2, false)DecryptText  
  13.     </div>  
  14.     <div>  
  15.        <b>Output</b> :@ViewBag.Result</div>  
  16.     <input type="submit" value="submit" />  
  17. } 

Step 5

Execute the application.

en8.jpg

Type some text and select "Encrypt". Click on the "Submit" button. It generates an encrypted code version of the text.

en9.jpg

Copy the encrypted code and paste it into the text box and select decrypt. Now click on the "Submit" button. It generates the original text.

en91.jpg


Similar Articles