Go to C #: Encrypt and decrypt user passwords using MD5

Source: Internet
Author: User
Tags decrypt md5 encryption sha1



C # often involves encrypting the user's password to decrypt the algorithm, where using MD5 encryption is the most common way to implement it. This paper summarizes the general algorithms and combines their own little experience to share to everyone.



I. Encrypt user names using the 16-bit, 32-bit, 64-bit MD5 method



1) 16-bit MD5 encryption


/// <summary>
/// 16-bit MD5 encryption
/// </ summary>
/// <param name = "password"> </ param>
/// <returns> </ returns>
public static string MD5Encrypt16 (string password)
{
     var md5 = new MD5CryptoServiceProvider ();
     string t2 = BitConverter.ToString (md5.ComputeHash (Encoding.Default.GetBytes (password)), 4, 8);
     t2 = t2.Replace ("-", "");
     return t2;
} 


2) 32-bit MD5 encryption


/// <summary>
/// 32-bit MD5 encryption
/// </ summary>
/// <param name = "password"> </ param>
/// <returns> </ returns>
public static string MD5Encrypt32 (string password)
{
     string cl = password;
     string pwd = "";
     MD5 md5 = MD5.Create (); // Instantiate an md5 object
     // After encryption, it is an array of byte type. Here we should pay attention to the choice of encoding UTF8 / Unicode, etc.
     byte [] s = md5.ComputeHash (Encoding.UTF8.GetBytes (cl));
     // By using a loop, convert an array of byte type into a string, this string is formatted by regular characters
     for (int i = 0; i <s.Length; i ++)
     {
         // The resulting string will be in hexadecimal type format. The formatted characters are lowercase letters. If uppercase (X) is used, the formatted characters are uppercase characters.
         pwd = pwd + s [i] .ToString ("X");
     }
     return pwd;
} 


3) 64-bit MD5 encryption


public static string MD5Encrypt64 (string password)
{
     string cl = password;
     // string pwd = "";
     MD5 md5 = MD5.Create (); // Instantiate an md5 object
     // After encryption, it is an array of byte type. Here we should pay attention to the choice of encoding UTF8 / Unicode, etc.
     byte [] s = md5.ComputeHash (Encoding.UTF8.GetBytes (cl));
     return Convert.ToBase64String (s);
} 


4) Encrypt the user password using MD5


/// <summary>
/// encrypted user password
/// </ summary>
/// <param name = "password"> password </ param>
/// <param name = "codeLength"> Encryption digits </ param>
/// <returns> encrypted password </ returns>
public static string md5 (string password, int codeLength)
{
     if (! string.IsNullOrEmpty (password))
     {
         // 16-bit MD5 encryption (takes 32-bit encrypted 9 ~ 25 characters)
         if (codeLength == 16)
         {
             return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile (password, "MD5"). ToLower (). Substring (8, 16);
         }

         // 32-bit encryption
         if (codeLength == 32)
         {
             return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile (password, "MD5"). ToLower ();
         }
     }
     return string.Empty;
} 


Because the MD5 is irreversible, so after the encryption can not be decrypted, take the user name and password, you need to encrypt the user input data and the database encrypted data. If the result is the same, you can determine the success of the landing! The code looks like this:


/// <summary>
/// Login
/// </ summary>
public Model.UserInfo UserLogOn (string USERID, string pwd, out string statusCode)
{
     // Assume that the Model object of UserInfo has been obtained through the user ID
     Model.UserInfo model = GetModel (USERID);
     if (model! = null)
     {
         if (model.PASSWORD == MD5Encrypt64 (pwd))
         {
             statusCode = "Successfully logged in";
         }
         else {
             statusCode = "Password error";
         }
     }
     else
     {
         statusCode = "User does not exist!";
         model = null;
     }
     return model;
} 


5) Encrypt and decrypt strings by DESCryptoServiceProvider objects


/// <summary>
/// DES data encryption
/// </ summary>
/// <param name = "targetValue"> target value </ param>
/// <param name = "key"> key </ param>
/// <returns> encrypted values </ returns>
public static string Encrypt (string targetValue, string key)
{
    if (string.IsNullOrEmpty (targetValue))
    {
        return string.Empty;
    }

    var returnValue = new StringBuilder ();
    var des = new DESCryptoServiceProvider ();
    byte [] inputByteArray = Encoding.Default.GetBytes (targetValue);
    // Set the initialization vector of the symmetric algorithm by hashing the password twice
    des.Key = Encoding.ASCII.GetBytes (FormsAuthentication.HashPasswordForStoringInConfigFile
                                            (FormsAuthentication.HashPasswordForStoringInConfigFile (key, "md5").
                                                Substring (0, 8), "sha1"). Substring (0, 8));
    // Set the secret key of the algorithm by hashing the password twice
    des.IV = Encoding.ASCII.GetBytes (FormsAuthentication.HashPasswordForStoringInConfigFile
                                            (FormsAuthentication.HashPasswordForStoringInConfigFile (key, "md5")
                                                .Substring (0, 8), "md5"). Substring (0, 8));
    var ms = new MemoryStream ();
    var cs = new CryptoStream (ms, des.CreateEncryptor (), CryptoStreamMode.Write);
    cs.Write (inputByteArray, 0, inputByteArray.Length);
    cs.FlushFinalBlock ();
    foreach (byte b in ms.ToArray ())
    {
        returnValue.AppendFormat ("{0: X2}", b);
    }
    return returnValue.ToString ();
} 


This algorithm can be decrypted by the encryption key, and the method of decryption is as follows:


/// <summary>
/// DES data decryption
/// </ summary>
/// <param name = "targetValue"> </ param>
/// <param name = "key"> </ param>
/// <returns> </ returns>
public static string Decrypt (string targetValue, string key)
{
    if (string.IsNullOrEmpty (targetValue))
    {
        return string.Empty;
    }
    // Define DES encryption object
    var des = new DESCryptoServiceProvider ();
    int len = targetValue.Length / 2;
    var inputByteArray = new byte [len];
    int x, i;
    for (x = 0; x <len; x ++)
    {
        i = Convert.ToInt32 (targetValue.Substring (x * 2, 2), 16);
        inputByteArray [x] = (byte) i;
    }
    // Set the initialization vector of the symmetric algorithm by hashing the password twice
    des.Key = Encoding.ASCII.GetBytes (FormsAuthentication.HashPasswordForStoringInConfigFile
                                            (FormsAuthentication.HashPasswordForStoringInConfigFile (key, "md5").
                                                Substring (0, 8), "sha1"). Substring (0, 8));
    // Set the secret key of the algorithm by hashing the password twice
    des.IV = Encoding.ASCII.GetBytes (FormsAuthentication.HashPasswordForStoringInConfigFile
                                            (FormsAuthentication.HashPasswordForStoringInConfigFile (key, "md5")
                                                .Substring (0, 8), "md5"). Substring (0, 8));
    // define the memory stream
    var ms = new MemoryStream ();
    // define encrypted stream
    var cs = new CryptoStream (ms, des.CreateDecryptor (), CryptoStreamMode.Write);
    cs.Write (inputByteArray, 0, inputByteArray.Length);
    cs.FlushFinalBlock ();
    return Encoding.Default.GetString (ms.ToArray ());
} 


Go to C #: Encrypt and decrypt user passwords using MD5


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.