Powered by Blogger.

Sunday, February 16, 2014

Different ways to encrypt or decrypt password in asp.net




In a real life situation, the password field should be stored in database in encrypted mode. Below are some techniques to encrypt or decrypt string in Asp.Net.

Method-1(Followed from CodeProject)

Below is the method to encrypt a string.

private string encryptPassword(string pass)
{
        string _result = string.Empty;

        char[] temp = pass.ToCharArray();

        foreach (var _singleChar in temp)
        {
                var i = (int)_singleChar;

                i = i - 2;

                _result += (char)i;
        }
        return _result;
}

Below is the method to decrypt a string.

private string decryptPassword(string pass)
{
        string _result = string.Empty;

        char[] temp = pass.ToCharArray();

        foreach (var _singleChar in temp)
        {
                var i = (int)_singleChar;

                i = i + 2;

                _result += (char)i;

        }
        return _result;
}


Method-2 (Followed from AspDotNet-Suresh)

private string EncryptPassword(string password)
{
string strmsg = string.Empty;

byte[] encode = new byte[password.Length];

encode = Encoding.UTF8.GetBytes(password);

strmsg = Convert.ToBase64String(encode);

return strmsg;
}


private string DecryptPassword(string encryptpwd)
{
string decryptpwd = string.Empty;

UTF8Encoding encodepwd = new UTF8Encoding();

Decoder Decode = encodepwd.GetDecoder();

byte[] todecode_byte = Convert.FromBase64String(encryptpwd);

int charCount = Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);

char[] decoded_char = new char[charCount];

Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);

decryptpwd = new String(decoded_char);

return decryptpwd;
}



0 comments

Post a Comment