Encrypt and Decrypt Text in Web API (2024)

Encrypt and Decrypt Text in Web API (1)

  • 138.8k
  • 0
  • 2

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.

    Encrypt and Decrypt Text in Web API (3)

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

    Encrypt and Decrypt Text in Web API (4)

  • 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#".

    Encrypt and Decrypt Text in Web API (5)

  • Select Class and click the "Add" button.

Add the following code:

  1. usingSystem;
  2. usingSystem.Collections.Generic;
  3. usingSystem.Linq;
  4. usingSystem.Web;
  5. namespaceEncriptCode.Models
  6. {
  7. publicclassEModel
  8. {
  9. publicstringword{get;set;}
  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".

    Encrypt and Decrypt Text in Web API (6)

Add the following code:

  1. usingSystem;
  2. usingSystem.Collections.Generic;
  3. usingSystem.Linq;
  4. usingSystem.Web;
  5. usingSystem.Web.Mvc;
  6. usingEncriptCode.Models;
  7. usingSystem.Text;
  8. usingSystem.Security.Cryptography;
  9. namespaceEncriptCode.Controllers
  10. {
  11. publicclassHomeController:Controller
  12. {
  13. stringkey="1prt56";
  14. publicActionResultIndex()
  15. {
  16. EModelobj=newEModel();
  17. returnView(obj);
  18. }
  19. [HttpPost]
  20. publicActionResultIndex(EModelobj)
  21. {
  22. intreq=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. returnView(obj);
  32. }
  33. publicstringEncryptword(stringEncryptval)
  34. {
  35. byte[]SrctArray;
  36. byte[]EnctArray=UTF8Encoding.UTF8.GetBytes(Encryptval);
  37. SrctArray=UTF8Encoding.UTF8.GetBytes(key);
  38. TripleDESCryptoServiceProviderobjt=newTripleDESCryptoServiceProvider();
  39. MD5CryptoServiceProviderobjcrpt=newMD5CryptoServiceProvider();
  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. ICryptoTransformcrptotrns=objt.CreateEncryptor();
  46. byte[]resArray=crptotrns.TransformFinalBlock(EnctArray,0,EnctArray.Length);
  47. objt.Clear();
  48. returnConvert.ToBase64String(resArray,0,resArray.Length);
  49. }
  50. publicstringDecryptword(stringDecryptText)
  51. {
  52. byte[]SrctArray;
  53. byte[]DrctArray=Convert.FromBase64String(DecryptText);
  54. SrctArray=UTF8Encoding.UTF8.GetBytes(key);
  55. TripleDESCryptoServiceProviderobjt=newTripleDESCryptoServiceProvider();
  56. MD5CryptoServiceProviderobjmdcript=newMD5CryptoServiceProvider();
  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. ICryptoTransformcrptotrns=objt.CreateDecryptor();
  63. byte[]resArray=crptotrns.TransformFinalBlock(DrctArray,0,DrctArray.Length);
  64. objt.Clear();
  65. returnUTF8Encoding.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".

    Encrypt and Decrypt Text in Web API (7)

Add the following code:

  1. @modelEncriptCode.Models.EModel
  2. @{
  3. ViewBag.Title="CodeforEncryptandDecrypttheTextinWebAPI";
  4. }
  5. @using(Html.BeginForm("Index","Home",FormMethod.Post))
  6. {
  7. <h2>
  8. EncryptandDecryptText</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. <inputtype="submit"value="submit"/>
  17. }

Step 5

Execute the application.

Encrypt and Decrypt Text in Web API (8)

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

Encrypt and Decrypt Text in Web API (9)

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.

Encrypt and Decrypt Text in Web API (10)

Encrypt and Decrypt Text in Web API (2024)
Top Articles
Latest Posts
Article information

Author: Delena Feil

Last Updated:

Views: 5833

Rating: 4.4 / 5 (45 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Delena Feil

Birthday: 1998-08-29

Address: 747 Lubowitz Run, Sidmouth, HI 90646-5543

Phone: +99513241752844

Job: Design Supervisor

Hobby: Digital arts, Lacemaking, Air sports, Running, Scouting, Shooting, Puzzles

Introduction: My name is Delena Feil, I am a clean, splendid, calm, fancy, jolly, bright, faithful person who loves writing and wants to share my knowledge and understanding with you.