Popular Posts

Jan 26, 2014

Encrypt/Decrypt String in c#




In .net you can easily encrypt/decrypt string.
The following code describes how to do:

    /// <summary>
    /// To encrypt the input password
    /// </summary>
    /// <param name="txtPassword"></param>
    /// <returns>It returns encrypted code</returns>
    public string EncryptPassword(string txtString)
    {
        byte[] passBytes = System.Text.Encoding.Unicode.GetBytes(txtString);
        string encryptPassword = Convert.ToBase64String(passBytes);
        return encryptPassword;
    }


    /// <summary>
    /// To Decrypt password
    /// </summary>
    /// <param name="encryptedPassword"></param>
    /// <returns>It returns plain password</returns>
    public string DecryptPassword(string encryptedString)
    {
        byte[] passByteData = Convert.FromBase64String(encryptedString);
        string originalPassword = System.Text.Encoding.Unicode.GetString(passByteData);
        return originalPassword;
    }



You can do it in another way:


        /// <summary>
    ///
    /// </summary>
    /// <param name="password"></param>
    /// <returns>It returns encyped string</returns>
    public string Encryptdata(string password)
    {
        string strmsg = string.Empty;
        byte[] encode = new
        byte[password.Length];
        encode = Encoding.UTF8.GetBytes(password);
        strmsg = Convert.ToBase64String(encode);
        return strmsg;
    }

    /// <summary>
    ///
    /// </summary>
    /// <param name="encryptpwd"></param>
    /// <returns>It returns text string</returns>
    public string Decryptdata(string encryptpwd)
    {
        string decryptpwd = string.Empty;


        UTF8Encoding encodepwd = new UTF8Encoding();
        System.Text.Decoder utf8Decode = encodepwd.GetDecoder();
        byte[] todecode_byte = Convert.FromBase64String(encryptpwd);
        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);
        decryptpwd = new String(decoded_char);
        return decryptpwd;
    }