C # MD5 encryption,

Source: Internet
Author: User

C # MD5 encryption,
First, let's briefly introduce MD5.

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

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

Reference
Using System. Security. Cryptography;
Using System. Text;

The Code is as follows (written in the Click Event of the button ):
Byte [] result = Encoding. Default. GetBytes (this. tbPass. Text. Trim (); // tbPass is the Text box for entering the password
MD5 md5 = new MD5CryptoServiceProvider ();
Byte [] output = md5.ComputeHash (result );
This. tbMd5pass. Text = BitConverter. ToString (output). Replace ("-", ""); // tbMd5pass is the Text box for outputting encrypted Text


Method 2

C # md5 encryption (on)
String a; // pre-encryption data
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>
/// Perform MD5 encryption on a string
/// </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 blank'); document. all ('textname '). focus () </script> ");
Return;
}
Else if (texPassword. Text. Trim () = "")
{
This. registerStartupScript ("sfs", "<script language = 'javascript '> alert ('password cannot be blank'); document. all ('textpassword '). focus () </script> ");
Return;
}
Else
{
// Encrypt the obtained password and the password added to the database
Byte [] by = md5.ComputeHash (utf. GetBytes (texPassword. Text. Trim ()));
String resultPass = System. Text. UTF8Encoding. Unicode. GetString ();
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 ())
{
// Check the password if the user exists
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;
// Log on to the Apsara stack console.

}
Else
{
This. RegisterStartupScript ("wp", "<script language = 'javascript '> alert ('incorrect password, please check. ') </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 ('network connection is different. Please try again later. ') </Script> ");
}
Finally
{
Conn. Close ();
}
}
}


Method 3
C # MD5 Encryption

C # Development Notes 1, C # MD5-16 bit encryption instance, 32 bit encryption instance (two methods)

Environment: vs. net2005/SQL server2000/xp passed the test
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>
/// The MD5 16-bit encrypted password is capitalized
/// </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>
/// The MD5 16-bit encrypted password is in lower case
/// </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 (); // instantiate an md5 object
// After encryption, it is an array of the byte type. Pay attention to the selection of UTF-8/Unicode encoding.
Byte [] s = md5.ComputeHash (Encoding. UTF8.GetBytes (cl ));
// Convert an array of the byte type into a string by using a loop. This string is obtained by regular character formatting.
For (int I = 0; I <s. Length; I ++)
{
// Use the hexadecimal format of the obtained string. The characters in the format are lowercase letters. If uppercase letters (X) are used, the characters in the format are uppercase letters.

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 ();
}

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.