Saturday, August 17, 2013

Encrypt and Decrypt Password into Session Variable, Application Variable, Global Variable etc in SQL Server/Asp.net/C#

Description : Encrypt and Decrypt Password/Session Variable/Global Variable in SQL Server using ASP.NET


There are Two Method for Encrypt and Decrypt mechanism.
1) Encode and Decode Data
2) Encryption and Decryption using Algorithm
PrjSecurity.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Web.Security;
using System.Windows.Forms;
using System.Security;
using System.Security.Cryptography;


namespace Musakkhir.Code
{
    public class PrjSecurity
    {
        public  string EncodePasswordToBase64(string password)
        {
            try
            {
                byte[] encData_byte = new byte[password.Length];
                encData_byte = System.Text.Encoding.UTF8.GetBytes(password);
                string encodedData = Convert.ToBase64String(encData_byte);
                return encodedData;
            }
            catch (Exception ex)
            {
                throw new Exception("Error in base64Encode" + ex.Message);
            }
        }

        public string DecodeFrom64(string encodedData)
        {
            System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
            System.Text.Decoder utf8Decode = encoder.GetDecoder();
            byte[] todecode_byte = Convert.FromBase64String(encodedData);
            int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
            char[] decoded_char = new char[charCount];
            utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
            string result = new String(decoded_char);
            return result;
        }
        /// <summary>
        /// ///////////    Musakkhir   ///////////
        /// </summary>
        /// <param name="stringToDecrypt"></param>
        /// <param name="sEncryptionKey"></param>
        /// <returns></returns>
        public string Decrypt(string stringToDecrypt, string sEncryptionKey)
        {
            byte[] key = { };
            byte[] IV = { 10, 20, 30, 40, 50, 60, 70, 80 };
            //Private IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF}

            byte[] inputByteArray = new byte[stringToDecrypt.Length];
            try
            {
                key = Encoding.UTF8.GetBytes(sEncryptionKey.Substring(0, 8));
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                inputByteArray = Convert.FromBase64String(stringToDecrypt);

                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(key, IV), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();

                Encoding encoding = Encoding.UTF8;
                return encoding.GetString(ms.ToArray());
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
        }

        //public static string Encrypt(string stringToEncrypt,
        public string Encrypt(string stringToEncrypt,   string sEncryptionKey)
        {
            byte[] key = { };
            byte[] IV = { 10, 20, 30, 40, 50, 60, 70, 80 };
            byte[] inputByteArray; //Convert.ToByte(stringToEncrypt.Length)
            try
            {
                key = Encoding.UTF8.GetBytes(sEncryptionKey.Substring(0, 8));
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                inputByteArray = Encoding.UTF8.GetBytes(stringToEncrypt);
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(key, IV), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();

                return Convert.ToBase64String(ms.ToArray());
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
        }
    }
}


USE:

Import Namespace.
using System.Security;
using System.Security.Cryptography; 
using PrjSecurity;

Create object of PrjSecurity Class file to call Encrypt and Decrypt method.
PrjSecurity s=new PrjSecurity();

Define Variable.
string EncPassword, DecPassword;

Encrypt Password which is store in session variable, in this way u can also encrypt and decrypt global variable, static variable, application variable, etc.

EncPassword = txtPassword.Text;
Session["Password"] = s.Encrypt(EncPassword, SHA512.Create().ToString());

The session variable Password which is store in session variable is encrypted by using SHA512 algorithm and it is store in EncPassword variable.
Decrypt Session Variable which is tore in Encypted format can be decrypt in string variable DecPassword in this way.

DecPassword = s.Decrypt(Session["Password"], SHA512.Create().ToString());

7 comments :

  1. this will not work, because the encryption is taking place on server and the form data will be still visible ... if some one want to encrypt form data he must use JavaScript encryption before submitting data to the server.

    ReplyDelete
  2. Your posts is really helpful for me.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 in Chennai reach FITA, rated as No.1 Dot Net Training Institutes in Chennai.

    ReplyDelete
  3. This has saved me a lot of time, thank you very much!

    ReplyDelete
  4. Variables stored in a Session object hold information about one single user, and are available to all pages in one application. Common information stored in session variables are name, id, and preferences. The server creates a new Session object for each new user, and destroys the Session object when the session expires. Dot Net Training in chennai | Dot Net Training in velachery

    ReplyDelete
  5. Superbly written article, if only all bloggers offered the same content as you, the internet would be a far better place..
    cs代写

    ReplyDelete
  6. Positive site, where did u come up with the information on this posting? I'm pleased I discovered it though, ill be checking back soon to find out what additional posts you include.
    cs代写

    ReplyDelete