Wednesday, 21 May 2014

Encoding and Decoding base64 string using Asp.net MVC application

Encoding and Decoding base64 string using Asp.net MVC application


Introduction

Here we learn how to encode string value to base64 string and decode base64 to simple string.

Description

Here we learn how to encode string value to base64 string and decode base64 to simple string.
We use Asp.net mvc 4 application to do this transaction. Using  System.Text.Encoding methods.

Solution


Step 1 :  Create your Asp.net MVC 4 application first using Visual Studio 2012 or Above .

Step 2 :  Create one folder in your application called "Utilities" we will all customize .cs file in this folder. We called this type of transaction as utilities of application.

Step 3 :  Add one class file in to you application name as "Encryption.cs" or as per your acquirement.


Step 4 :  Now open that class file and make that class public and static for entire website after that there is no need to create object of that class file, we can directly access all function and property of this class.

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace WebApplication1
{
    public static class Encryption
    {

    }

}

Step 5 :  Add below code to that file for Encryption of string.

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

namespace WebApplication1
{
    public static class Encryption
    {        
        /// <summary>
        /// Encrypt the password in base64 string
        /// </summary>
        /// <param name="password"></param>
        /// <returns></returns>
        public static string EncryptToBase64(this string password)
        {
            byte[] encodedBytes = Encoding.UTF8.GetBytes(password);
            string base64EncodedText = Convert.ToBase64String(encodedBytes);
            return base64EncodedText;
        }

        /// <summary>
        /// Decrypt the password to base 64 string
        /// </summary>
        /// <param name="password"></param>
        /// <returns></returns>
        public static string DecryptToBase64(this string password)
        {
            byte[] encodedBytes = Convert.FromBase64String(password);
            string plainText = Encoding.UTF8.GetString(encodedBytes);
            return plainText;
        }
    }
}

Step 6 :  Now access Encryption method to encode and decode your simple string.

string encodeResult = Encryption.EncryptToBase64("Simple Text String");

string recodeResult = Encryption.DecryptToBase64("Base64 String");


1 comment:

  1. Thanks for your wonderful post.It is really very helpful for us and I have gathered some important information from this blog.If anyone wants to get Dot Net Training reach FITA,

    ReplyDelete

Thank you for your interest .