C # implements MD5 encryption

Source: Internet
Author: User
Tags md5 encryption

C # implements MD5 encryption

Excerpt from: http://blog.csdn.net/shenghui188/archive/2010/03/28/5423959.aspx

Method One:

First, let's briefly introduce MD5

MD5 's full name is Message-digest algorithm 5 (Information-Digest algorithm, in the early 90 by MIT Laboratory for Computer Science and RSA Data Security Inc Ronald L. Rive St developed, developed by MD2, Md3 and MD4.

MD5 has a very good security (because it has irreversible characteristics, encrypted ciphertext after decryption and the same as before the encryption of the same probability)

Reference
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 a text box for entering a password
MD5 MD5 = new MD5CryptoServiceProvider ();
byte[] Output = Md5.computehash (result);
This.tbMd5pass.Text = bitconverter.tostring (Output).  Replace ("-", "" "); Tbmd5pass text box for output encrypted text

Method Two:

C # MD5 encryption (top)
String A; Pre-encryption data
String B; Post-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>
MD5 encryption for a string
</summary>
<param name= "StrText" > Strings to be encrypted </param>
<returns> string after encryption </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 ');d ocument.all (' Texname '). Focus ( ) </script> ");
Return
}
else if (texPassword.Text.Trim () = = "")
{
This. RegisterStartupScript ("SFS", "<script language= ' JavaScript ' >alert (' password cannot be empty ');d ocument.all (' Texpassword '). Focus () </script> ");
Return
}
Else
{
The password encryption obtained is compared with the secret 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 ())
{
The user exists, checks the 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;
Login successful, page oriented

}
Else
{
This. RegisterStartupScript ("WP", "<script language= ' JavaScript ' >alert (' Password error, please check. ') </script> ");
}

}
Else
{
This. RegisterStartupScript ("Nu", "<script language=javascript>alert (' username not present, 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 Three
C # MD5 Encryption

C # Development Note One, C # md5-16 bit encryption instance, 32-bit encryption instance (two methods)

Environment: Vs.net2005/sql SERVER2000/XP Test passed
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 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 after encrypting the password as 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 ();//Instantiate a MD5 pair of images
After the encryption is an array of byte type, here should pay attention to the choice of coding utf8/unicode, etc.
Byte[] s = Md5.computehash (Encoding.UTF8.GetBytes (CL));
Converts an array of byte types to a string by using a loop, which is a regular character formatting the resulting
for (int i = 0; i < s.length; i++)
{
The resulting string is formatted using the hexadecimal type. The formatted character is a lowercase letter, and if uppercase (X) is used, the character after the format is 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 ();
}


Second, first introduced in the interface: using System.Web.Security;

Assuming the password dialog name password, encrypt the input password into the variable pwd, the following statement:

string pwd = formsauthentication.hashpasswordforstoringinconfigfile (password. Text, "MD5");

If you want to enter the PWD, so that the actual database password is 202***** and so garbled.

If you want to log in to the query:

Select Username,password from users where username= ' "+ Username.text +" ' and password= ' "+ pwd +" '

Because MD5 cannot decrypt, only the original password is encrypted and compared with the encrypted password in the database.

Third, 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 characters)  
   { 
       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 ();  
  }  
 }

Four, to do a website, is bound to involve the user login, user login must involve password, password must involve security, security must involve encryption.
Encryption now the most popular is also said that the most secure algorithm is the MD5 algorithm, MD5 is an irreversible algorithm, that is, after the plaintext is encrypted, according to encrypted ciphertext can not restore the plaintext.
There are a lot of web sites dedicated to MD5, Baidu search MD5 on a lot of search, this morning bored to try a few broken secret website, 6 bits of pure digital password MD5 ciphertext can restore the plaintext, long point or with characters on the die. They are used in comparison, that is, the inclusion of plaintext and ciphertext into the database, through the comparison of ciphertext to determine the clear text, after all, the limited data collected, so the password is very limited.
Pull away, break the secret MD5 need a lot of money, because to an ultra-fast computing and a search performance of the database and super-large database ingest. But encryption is easier. Here is a MD5 encryption method I wrote in C #, using the. NET, through the Md5_app. StringToMD5 (string str, int i) can be called directly:

public class Md5_app
{
Public Md5_app ()
{

}

public static string StringToMD5 (string str, int i)
{
Get the field to encrypt and convert to byte[] Array
byte[] data = System.Text.Encoding.Unicode.GetBytes (str. ToCharArray ());
Establishing Cryptographic Services
System.Security.Cryptography.MD5 MD5 = new System.Security.Cryptography.MD5CryptoServiceProvider ();
Encrypt byte[] Array
Byte[] result = Md5.computehash (data);
Convert an encrypted array into a field
if (i = = && str! = string. Empty)
{
return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile (str, "MD5"). ToLower (). Substring (8, 16);
}
else if (i = = && str! = string. Empty)
{
return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile (str, "MD5"). ToLower ();
}
Else
{
Switch (i)
{
Case 16:return "000000000000000";
Case 32:return "000000000000000000000000000000";
Default:return "Make sure the second parameter is 16 or 32 when calling the function";
}

}
}

This article from Csdn Blog, reproduced please indicate the source: http://blog.csdn.net/shenghui188/archive/2010/03/28/5423959.aspx

C # implements MD5 encryption

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.