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 stringMd5encrypt16 (stringpassword) { varMD5 =NewMD5CryptoServiceProvider (); stringT2 = bitconverter.tostring (Md5.computehash (Encoding.Default.GetBytes (password)),4,8); T2= T2. Replace ("-",""); returnT2;}
2) 32-bit MD5 encryption
/// <summary>///32-bit MD5 encryption/// </summary>/// <param name= "password" ></param>/// <returns></returns> Public Static stringMd5encrypt32 (stringpassword) { stringCL =password; stringPWD =""; 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(inti =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 charactersPWD = pwd + s[i]. ToString ("X"); } returnpwd;}
3) 64-bit MD5 encryption
Public Static string Md5encrypt64 (string password) { string cl = password; // string pwd = ""; // 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)); return convert.tobase64string (s);}
4) Encrypt the user password using MD5
/// <summary>///Encrypt user Password/// </summary>/// <param name= "password" >Password</param>/// <param name= "Codelength" >number of encrypted bits</param>/// <returns>Encrypt Password</returns> Public Static stringMD5 (stringPasswordintcodelength) { if(!string. IsNullOrEmpty (password)) {//16-bit MD5 encryption (take 32-bit encrypted 9~25 characters) if(Codelength = = -) { returnSystem.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile (Password,"MD5"). ToLower (). Substring (8, -); } //32-bit encryption if(Codelength = = +) { returnSystem.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> PublicModel.userinfo Userlogon (stringUseridstringPwd out stringStatusCode) { //assume that the model object for UserInfo has been obtained through the user IDModel.userinfo model =Getmodel (USERID); if(Model! =NULL) { if(model. PASSWORD = =Md5encrypt64 (PWD)) {StatusCode="Landing Success"; } Else{StatusCode="Password Error";}} Else{StatusCode="The user does not exist!" "; Model=NULL; } returnmodel;}
5) Encrypt and decrypt strings by DESCryptoServiceProvider objects
/// <summary>///des data Encryption/// </summary>/// <param name= "Targetvalue" >target value</param>/// <param name= "key" >secret key</param>/// <returns>Encrypted Value</returns> Public Static stringEncrypt (stringTargetvalue,stringkey) { if(string. IsNullOrEmpty (Targetvalue)) {return string. Empty; } varReturnValue =NewStringBuilder (); varDes =NewDESCryptoServiceProvider (); byte[] Inputbytearray =Encoding.Default.GetBytes (Targetvalue); //set the initialization vector of the symmetric algorithm with a two-time hash cipherDes. Key =Encoding.ASCII.GetBytes (formsauthentication.hashpasswordforstoringinconfigfile (FormsAuthentication.HashPasswordForStoringInConfigFile (Key,"MD5"). Substring (0,8),"SHA1"). Substring (0,8)); //set the secret key of the algorithm with a two-time hash cipherDES.IV =Encoding.ASCII.GetBytes (formsauthentication.hashpasswordforstoringinconfigfile (FormsAuthentication.HashPasswordForStoringInConfigFile (Key,"MD5") . Substring (0,8),"MD5"). Substring (0,8)); varms =NewMemoryStream (); varCS =NewCryptoStream (MS, Des. CreateEncryptor (), cryptostreammode.write); Cs. Write (Inputbytearray,0, inputbytearray.length); Cs. FlushFinalBlock (); foreach(byteBinchMs. ToArray ()) {Returnvalue.appendformat ("{0:x2}", B); } returnreturnvalue.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 stringDecrypt (stringTargetvalue,stringkey) { if(string. IsNullOrEmpty (Targetvalue)) {return string. Empty; } //defining DES encryption Objects varDes =NewDESCryptoServiceProvider (); intLen = targetvalue.length/2; varInputbytearray =New byte[Len]; intx, I; for(x =0; x < Len; X + +) {i= Convert.ToInt32 (targetvalue.substring (x *2,2), -); INPUTBYTEARRAY[X]= (byte) I; } //set the initialization vector of the symmetric algorithm with a two-time hash cipherDes. Key =Encoding.ASCII.GetBytes (formsauthentication.hashpasswordforstoringinconfigfile (FormsAuthentication.HashPasswordForStoringInConfigFile (Key,"MD5"). Substring (0,8),"SHA1"). Substring (0,8)); //set the secret key of the algorithm with a two-time hash cipherDES.IV =Encoding.ASCII.GetBytes (formsauthentication.hashpasswordforstoringinconfigfile (FormsAuthentication.HashPasswordForStoringInConfigFile (Key,"MD5") . Substring (0,8),"MD5"). Substring (0,8)); //Defining Memory Streams varms =NewMemoryStream (); //defining an encrypted stream varCS =NewCryptoStream (MS, Des. CreateDecryptor (), cryptostreammode.write); Cs. Write (Inputbytearray,0, inputbytearray.length); Cs. FlushFinalBlock (); returnEncoding.Default.GetString (Ms. ToArray ());}
Description: This article is Healer007 original, signature: Radish! Some of the information from the Internet, if you want to reprint please specify the source!
C #: Encrypt and decrypt user passwords using MD5