.NET

Encrypt And Decrypt String in MVC,C#

In this artical, I will expain you how to encrypt and decrypt string.

For security purpose, we are storing some valuable things in Encrypt format.(like password)

Follow the below steps to learn about how to implement encryption and decryption thereafter you can use it for your purposes.

First, create a new project of MVC from File -> New -> Project.

second, Select ASP.NET Web Application (.Net Framework) for creating an MVC application and set Name and Location of Project.

After creating a project inside the home controller add required namespaces as follwing:

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Web.Mvc;

Among these, the namespaces syatem.security.cryptography provides all cryptographic services which include operations such as encoding  and decoding the data, generating random numbers, hashing and many more.

Define the method with appropriate name for encrypting a string similar to as below.

public System.Web.Mvc.JsonResult EncryptString(string plainText)
        {
            string key = "Xc4u7x!A%D*G-KaPdSr56tp2s5v8y/B?";
            byte[] iv = new byte[16];
            byte[] array;

            using (Aes aes = Aes.Create())
            {
                aes.Key = Encoding.UTF8.GetBytes(key);
                aes.IV = iv;

                ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);

                using (MemoryStream memoryStream = new MemoryStream())
                {
                    using (CryptoStream cryptoStream = new CryptoStream((Stream)memoryStream, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter streamWriter = new StreamWriter((Stream)cryptoStream))
                        {
                            streamWriter.Write(plainText);
                        }

                        array = memoryStream.ToArray();
                    }
                }
            }
            return Json(new { encryptstring = Convert.ToBase64String(array) }, JsonRequestBehavior.AllowGet);
        }

Inherit the Aes which is an abstract base class that contains the implementations of the standard Aes.

The IV declared earlier is assigned to the aes instance iv feild.

This method accept string parameter that needs to encrypted.

And last, the input plain text is encrypted, it converted into a byte array and returned to the calling method as a base64 string.

Define the method with appropriate name for decrypting a string similar to as below.

public System.Web.Mvc.JsonResult DecryptString(string cipherText)
        {
            string key = "Xc4u7x!A%D*G-KaPdSr56tp2s5v8y/B?";
            byte[] iv = new byte[16];
            byte[] buffer = Convert.FromBase64String(cipherText);

            using (Aes aes = Aes.Create())
            {
                aes.Key = Encoding.UTF8.GetBytes(key);
                aes.IV = iv;
                ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);

                using (MemoryStream memoryStream = new MemoryStream(buffer))
                {
                    using (CryptoStream cryptoStream = new CryptoStream((Stream)memoryStream, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader streamReader = new StreamReader((Stream)cryptoStream))
                        {
                            return Json(new { decryptsyring = streamReader.ReadToEnd() }, JsonRequestBehavior.AllowGet);
                        }
                    }
                }
            }
        }

This method accepts  parameters which are the cipher text.

The cipher text is converted into byte array.

The cipher text is deciphered using CryptoStream and is finally returned as a string.

Add View for Index method as below:

<div>
    <div class="form-group">
        <label>Enter Value:</label>
        <input type="text" id="str" />
        <input type="submit" id="encrypt" value="encrypt" />
        <input type="submit" id="decrypt" value="decrypt" />
    </div>

</div>
<script>
    $("#encrypt").click(function () {
        $.ajax({
            url: "/Home/EncryptString?plainText=" + $("#str").val(),
            type: "POST",
            contentType: false,
            dataType: "json",
            success: function (result) {
                alert(result.encryptstring);

            },
            error: function (errormessage) {
                alert(errormessage.responseText);
            }
        });
    })
    $("#decrypt").click(function () {
        $.ajax({
            url: "/Home/DecryptString?cipherText=" + $("#str").val(),
            type: "POST",
            contentType: false,
            dataType: "json",
            success: function (result) {
                alert(result.decryptsyring);

            },
            error: function (errormessage) {
                alert(errormessage.responseText);
            }
        });
    })
</script>

OUTPUT:

monika gabani

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

2 years ago