Detailed explanation of C to achieve MD5 encryption example code

  • 2021-11-24 02:42:56
  • OfStack

C # implements MD5 encryption as follows:

Method 1

First of all, let's briefly introduce MD5 under 1

The full name of MD5 is message-digest algorithm 5 (information-summary algorithm, which was developed in the early 1990s by mit laboratory for computer science and rsa data security inc ronald l. rivest, and developed by md2, md3 and md4.

MD5 has good security (because it is irreversible, it is extremely unlikely that the encrypted ciphertext will be the same after decryption as before encryption)

Quote


using System.Security.Cryptography;
using System.Text;

The specific code is as follows (written in the Click event of the button):


byte[] result = Encoding.Default.GetBytes(this.tbPass.Text.Trim());  //tbPass Text box for entering password 
MD5 md5 = new MD5CryptoServiceProvider();
byte[] output = md5.ComputeHash(result);
this.tbMd5pass.Text = BitConverter.ToString(output).Replace("-",""); //tbMd5pass A text box for outputting encrypted text 

Method 2

C # md5 Encryption (I)


string a; // Data before encryption 
string b; // Encrypted data 
b=System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(a,"MD5")

using  System;
using  System.Security.Cryptography;

Method 2


public  static  string  GetMD5(string  myString)  
{
MD5  md5   =  new  MD5CryptoServiceProvider();
byte[]  fromData  =  System.Text.Encoding.Unicode.GetBytes(myString);
byte[]  targetData  =  md5.ComputeHash(fromData);
string  byte2String  =  null;

for  (int  i=0;  i<targetData.Length;  i++)  
{
byte2String  +=  targetData[i].ToString("x");
}

return  byte2String;
} 

using  System.Security.Cryptography;


///  <summary>
///   To 1 String MD5 Encryption 
///  </summary>
///  <param  name="strText"> String to be encrypted </param>
///  <returns> Encrypted string </returns>
public  static  string  MD5Encrypt(string  strText)
{  
MD5  md5  =  new  MD5CryptoServiceProvider();
byte[]  result  =  md5.ComputeHash(System.Text.Encoding.Default.GetBytes(strText));
return  System.Text.Encoding.Default.GetString(result);
} 

C # MD5 Encryption


using System.Security.Cryptography;


private void btnOK_Click(object sender, System.EventArgs e)
{
  string strConn = "server=192.168.0.51;database=chengheng;User id=sa; password=123";
  if(texName.Text.Trim()=="")
  {
  this.RegisterStartupScript("sf","<script language='javascript'>alert(' User name cannot be empty ');document.all('texName').focus()</script>");
  return;
  }
  else if(texPassword.Text.Trim()=="")
  {
  this.RegisterStartupScript("sfs","<script language='javascript'>alert(' Password cannot be empty ');document.all('texPassword').focus()</script>");
  return;
  }
  else
  {
  // Compare the obtained password encryption with the encrypted password in the database 
  byte[] by = md5.ComputeHash(utf.GetBytes(texPassword.Text.Trim()));
  string resultPass = System.Text.UTF8Encoding.Unicode.GetString(by);
  conn.ConnectionString=strConn;
  SqlCommand comm = new SqlCommand();
  string name = texName.Text.Trim().ToString();
  comm.CommandText="select Ruser_pwd,Ruser_nm from Ruser where Accountno = @name";
  comm.Parameters.Add("@name",SqlDbType.NVarChar,40);
  comm.Parameters["@name"].Value=name;
  try
  {   
   conn.Open();
   comm.Connection=conn;
   SqlDataReader dr=comm.ExecuteReader();
   if(dr.Read())
   {
   // User exists, check password 
   if(dr.GetValue(0).Equals(resultPass))
   {
    string user_name=dr.GetValue(1).ToString();
    string user_Accountno=texName.Text.Trim();
    Session["logon_name"]=user_name;
    Session["logon_Accountno"]=user_Accountno;
    // Successful login, page orientation 

   }
   else
   {
    this.RegisterStartupScript("wp","<script language='javascript'>alert(' The password is wrong, please check it. ')</script>");
   }
   
   }
   else
   {
   this.RegisterStartupScript("nu","<script language=javascript>alert(' User name does not exist, please check. ')</script>");
   }
  }
  catch(Exception exec)
  { 
   this.RegisterStartupScript("wc","<script language=javascript>alert(' The network connection is different, please try again later. ')</script>");
  } 
  finally
  {
   conn.Close();
  }
  }
}

Method 3

C # Development Notes

1. C # MD 5-16-bit cryptographic instance, 32-bit cryptographic instance (two methods)

Environment: vs. net2005/sql server2000/xp Test Pass

1. MD5 16-bit encryption instance


using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;

namespace md5
{
  class Program
  {
    static void Main(string[] args)
    {
       Console.WriteLine(UserMd5("8"));
       Console.WriteLine(GetMd5Str("8"));
     }
    /**//// <summary>
    /// MD5 16 Bit encryption   The encrypted password is uppercase 
    /// </summary>
    /// <param name="ConvertString"></param>
    /// <returns></returns>
    public static string GetMd5Str(string ConvertString)
    {
       MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
      string t2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(ConvertString)), 4, 8);
       t2 = t2.Replace("-", "");
      return t2;
     }

 /**//// <summary>
    /// MD5 16 Bit encryption   The encrypted password is lowercase 
    /// </summary>
    /// <param name="ConvertString"></param>
    /// <returns></returns>
    public static string GetMd5Str(string ConvertString)
    {
       MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
      string t2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(ConvertString)), 4, 8);
       t2 = t2.Replace("-", "");

      t2 = t2.ToLower();

       return t2;
     }


    /**//// <summary>
    /// MD5   32 Bit encryption 
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    static string UserMd5(string str)
    {
      string cl = str;
      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;
     }
   }
}


using System.Security.Cryptography;
using System.Text; 

public static string StringToMD5Hash(string inputString)
    {
      MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
      byte[] encryptedBytes = md5.ComputeHash(Encoding.ASCII.GetBytes(inputString));
      StringBuilder sb = new StringBuilder();
      for (int i = 0; i < encryptedBytes.Length; i++)
      {
        sb.AppendFormat("{0:x2}", encryptedBytes[i]);
      }
      return sb.ToString();
    }


2. Firstly, using System. Web. Security is introduced into the interface;

Assuming the name of the password dialog box password, encrypt the entered password and store it in the variable pwd. The statement is as follows:


 string pwd = FormsAuthentication.HashPasswordForStoringInConfigFile(password.Text, "MD5");

If you want to enter, enter pwd, so that the actual password of the database is 202****** and other garbled codes.

If you log in to the query:


select username,password from users where username='"+ UserName.Text +"' and password='"+ pwd +"'

Because MD5 cannot be decrypted, the original password can only be encrypted and compared with the encrypted password in the database

3. C # MD5 Encryption Method 16-bit or 32-bit


 public string md5(string str,int code) 
 { 
  if(code==16) //16 Bit MD5 Encryption (take 32 Bit encrypted 9~25 Character)  
  { 
    return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str,"MD5").ToLower().Substring(8,16) ; 
  } 
  else//32 Bit encryption  
  { 
    return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str,"MD5").ToLower(); 
  } 
 } 

4. When making a website, it must involve user login, user login must involve password, password must involve security, and security must involve encryption.

At present, the most popular and said to be the safest algorithm for encryption is MD5 algorithm, which is an irreversible algorithm, that is, after plaintext is encrypted, it cannot be restored according to the encrypted ciphertext.

At present, there are many websites specializing in breaking secrets of MD5. Baidu searched for MD5 once and found a lot. This morning, I tried several websites to break secrets. MD5 ciphertext with pure digital password within 6 digits can restore plaintext, but long ones or ones with characters will not work. They use exhaustive comparison, that is to say, put the included plaintext and ciphertext into the database, and determine the plaintext through the comparison of ciphertext. After all, the included data is limited, so the cracked password is very limited.

Excuse me, breaking the secret MD5 requires a large number of MONEY, because it requires a computer with ultra-fast operation and a database with ultra-good search performance and super-large database collection. But encryption is easier. The following is an MD5 encryption method I wrote in C #, which can be called directly through MD5_APP. StringToMD5 (string str, int i) using the method in. NET:


byte[] result = Encoding.Default.GetBytes(this.tbPass.Text.Trim());  //tbPass Text box for entering password 
MD5 md5 = new MD5CryptoServiceProvider();
byte[] output = md5.ComputeHash(result);
this.tbMd5pass.Text = BitConverter.ToString(output).Replace("-",""); //tbMd5pass A text box for outputting encrypted text 
0

Related articles: