Encryption and decryption of user password using MD5 based on C

  • 2021-08-28 20:56:45
  • OfStack

C # often involves encryption and decryption algorithms for user passwords, among which MD5 encryption is the most common implementation. This paper summarizes the general algorithm and combines my own 1 little experience to share it with everyone.

1. Encrypt the user name 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(); // Instantiation 1 A md5 Object 
  //  Encrypted is 1 Array of byte type, pay attention to encoding here UTF8/Unicode Choice of etc 
  byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(cl));
  //  Converts an array of byte type to a string, which is formatted by regular characters, by using loops 
  for (int i = 0; i < s.Length; i++)
  {
    //  Use the resulting string 106 Binary type format. The characters after the format are lowercase letters, and if you use uppercase ( X ), 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(); // Instantiation 1 A md5 Object 
  //  Encrypted is 1 Array of byte type, pay attention to encoding here UTF8/Unicode Choice of etc 
  byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(cl));
  return Convert.ToBase64String(s);
}

4) Encrypt user passwords using MD5


/// <summary>
///  Encrypt user password 
/// </summary>
/// <param name="password"> Password </param>
/// <param name="codeLength"> Encryption bits </param>
/// <returns> Encryption password </returns>
public static string md5(string password, int codeLength)
{
  if (!string.IsNullOrEmpty(password))
  {
    // 16 Bit MD5 Encryption (take 32 Bit encrypted 9~25 Character)  
    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 MD5 is irreversible, it cannot be decrypted after encryption. When taking the user name and password, it is necessary to encrypt the data input by the user and compare it with the encrypted data in the database. If the comparison result is 1, it can be judged that the login is successful! The code looks like this:


/// <summary>
///  Landing 
/// </summary>
public Model.UserInfo UserLogOn(string USERID, string pwd, out string statusCode)
{
  // Assume that you have passed the user ID Get to UserInfo Adj. Model Object 
  Model.UserInfo model = GetModel(USERID);
  if (model != null)
  {
    if (model.PASSWORD == MD5Encrypt64(pwd))
    {
      statusCode = " Successful login ";
    }
    else {
      statusCode =  "Wrong password"; 
    }
  }
  else
  {
    statusCode = " User does not exist! ";
    model = null;
  }  
  return model;
} 

5) Encrypt and decrypt strings through DESCryptoServiceProvider objects


/// <summary>
/// DES Data encryption 
/// </summary>
/// <param name="targetValue"> Target value </param>
/// <param name="key"> Key </param>
/// <returns> Encryption value </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);
  //  Setting the initialization vector of symmetric algorithm by hashing password twice   
  des.Key = Encoding.ASCII.GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile
                      (FormsAuthentication.HashPasswordForStoringInConfigFile(key, "md5").
                        Substring(0, 8), "sha1").Substring(0, 8));
  //  Setting 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 encryption key, and the decryption method 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;
  }
  //  Definition DES Encrypted 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;
  }
  //  Setting the initialization vector of symmetric algorithm by hashing password twice   
  des.Key = Encoding.ASCII.GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile
                      (FormsAuthentication.HashPasswordForStoringInConfigFile(key, "md5").
                        Substring(0, 8), "sha1").Substring(0, 8));
  //  Setting 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 memory flow 
  var ms = new MemoryStream();
  //  Defining Encrypted Streams 
  var cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
  cs.Write(inputByteArray, 0, inputByteArray.Length);
  cs.FlushFinalBlock();
  return Encoding.Default.GetString(ms.ToArray());
}

The above content is based on C # to use MD5 encryption and decryption of the user password, I hope you like it.


Related articles: