Tuesday 4 December 2012

Encrypt and Decrypt Password in Asp.Net



Encrypt and Decrypt Password in Asp.Net

// Encryption of Password in Asp.Net on form before storeing value in database.
// Dencryption of Password in Asp.Net on form after getting value from database.
// To evaluate this code drag one <asp:TextBox> and one <asp:Button> control on your web page & write     this code on .CS page.

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
     string s= Encrypt(TextBox1.Text);
     Response.Write("Encrypted Password"+s+"<br/>");
     Response.Write("decrypt Password"+ Decrypt(s));
    }

//     Method or Function for Encrytion

    public string Encrypt(string str)
    {
        byte[] encrt_byte = new byte[str.Length];
        encrt_byte = UTF8Encoding.UTF8.GetBytes(str);
        String s = Convert.ToBase64String(encrt_byte);
        return s;
    }

//     Method or Function for Decrytion

    public string Decrypt(string str)
    {
        UTF8Encoding objutfencoding = new UTF8Encoding();
        Decoder utfdecode = objutfencoding.GetDecoder();
        byte[] todecode_byte = Convert.FromBase64String(str);
        int countchar = utfdecode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
        char[] decoded_char = new char[countchar];
        utfdecode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
        string s = new string(decoded_char);
        return s;
    }
}


No comments:

Post a Comment