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:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

 

namespace EncriptCode.Models

{

    public class EModel

    {

        public string word { get; set; }

    }

}

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:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using EncriptCode.Models;

using System.Text;

using System.Security.Cryptography;

namespace EncriptCode.Controllers

{

    public class HomeController : Controller

    {

         string key = "1prt56";   

       public ActionResult Index()

        {

            EModel obj = new EModel();

            return View(obj);

        }

        [HttpPost]

        public ActionResult Index( EModel obj)

        {

            int req = Convert.ToInt32(Request.Form["type"]);

            if (req == 1)

            {

                ViewBag.Result = Encryptword(obj.word);

            }

            else

            {

                ViewBag.Result = Decryptword(obj.word);

            }

            return View(obj);

        }

                public string Encryptword(string Encryptval)

        {

            byte[] SrctArray;

            byte[] EnctArray = UTF8Encoding.UTF8.GetBytes(Encryptval);

            SrctArray = UTF8Encoding.UTF8.GetBytes(key);

            TripleDESCryptoServiceProvider objt = new TripleDESCryptoServiceProvider();

             MD5CryptoServiceProvider objcrpt = new MD5CryptoServiceProvider();

            SrctArray = objcrpt.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));

            objcrpt.Clear();

            objt.Key = SrctArray;

            objt.Mode = CipherMode.ECB;

            objt.Padding = PaddingMode.PKCS7;

            ICryptoTransform crptotrns = objt.CreateEncryptor();

            byte[] resArray = crptotrns.TransformFinalBlock(EnctArray, 0, EnctArray.Length);

            objt.Clear();

            return Convert.ToBase64String(resArray, 0, resArray.Length);

        }

        public string Decryptword(string DecryptText)

        {

            byte[] SrctArray;

            byte[] DrctArray = Convert.FromBase64String(DecryptText);

            SrctArray = UTF8Encoding.UTF8.GetBytes(key);

            TripleDESCryptoServiceProvider objt = new TripleDESCryptoServiceProvider();

             MD5CryptoServiceProvider objmdcript = new MD5CryptoServiceProvider();

            SrctArray = objmdcript.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));

            objmdcript.Clear();

            objt.Key = SrctArray;

            objt.Mode = CipherMode.ECB;

            objt.Padding = PaddingMode.PKCS7;

            ICryptoTransform crptotrns = objt.CreateDecryptor();

            byte[] resArray = crptotrns.TransformFinalBlock(DrctArray, 0, DrctArray.Length);

                        objt.Clear();

            return UTF8Encoding.UTF8.GetString(resArray);

        }

    }

}

 

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:

@model EncriptCode.Models.EModel

@{

    ViewBag.Title = "Code for Encrypt and Decrypt the Text in Web API";

}

@using (Html.BeginForm("Index", "Home", FormMethod.Post))

{

    <h2>

        Encrypt and Decrypt Text</h2>

    @Html.TextBoxFor(p => p.word, new { @style = "width:200px" })

    <div>

      

        @Html.RadioButton("type", 1, true)EncryptText

<br>@Html.RadioButton("type", 2, false)DecryptText

    </div>

    <div>

       <b>Output</b> :@ViewBag.Result</div>

    <input type="submit" value="submit" />

}

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

Up Next
    Ebook Download
    View all
    Learn
    View all