Public Static stringGetMD5 (stringstr)//write-Yourself {//Create a MD5 objectMD5 md5=MD5. Create (); //Start Encryption//need to convert a string into a byte array byte[] buffer =Encoding.Default.GetBytes (str); byte[] Md5buffer =md5.computehash (buffer); //converts a character array to a string//character array-------string//First: Parses each element in a byte array into a string according to the specified encoding format
Md5str = Encoding.Default.GetString (Md5buffer);//The character array cannot be converted to a string in this instance//the second type: directly the array tostring ()//each element in a byte array is tostring () stringMd5str=string. Empty; for(inti =0; i < md5buffer.length; i++) {Md5str+ = Md5buffer[i]. ToString ("X2");//Convert to 32 binary } returnMd5str; }
Using System; The MSDN Library using system.security.cryptography;using System.text;namespace md5sample{class Program {static void Main (string[] args) {string source = "Hello world!"; using (MD5 Md5hash = MD5. Create ()) {string hash = Getmd5hash (Md5hash, source); Console.WriteLine ("The MD5 hash of" + Source + "is:" + hash + "."); Console.WriteLine ("Verifying the hash ..."); if (Verifymd5hash (Md5hash, source, hash)) {Console.WriteLine ("The hashes is the same.") ); } else {Console.WriteLine ("The hashes is not same."); }}}} static string Getmd5hash (MD5 md5hash, string input) {//Convert the Inpu T string to a byte array and compute the hash. byte[] data = Md5hash.computehash (Encoding.UTF8. GetBytes (input)); Create a new Stringbuilder to collect the bytes//and create a string. StringBuilder Sbuilder = new StringBuilder (); Loop through each byte of the hashed data//and format each one as a hexadecimal string. for (int i = 0; i < data. Length; i++) {sbuilder.append (Data[i]. ToString ("X2")); }//Return the hexadecimal string. return sbuilder.tostring (); }//Verify a hash against a string. static bool Verifymd5hash (MD5 Md5hash, string input, string hash) {//hash the input. String hashofinput = Getmd5hash (Md5hash, input); Create a StringComparer an compare the hashes. StringComparer comparer = stringcomparer.ordinalignorecase; if (0 = = Comparer.compare (hashofinput, hash)) {return true; } else{return false; }}}}//This code example produces the following output://the MD5 hash of Hello world! is:ed076287532e86365e841e92bfc50d8c.//verifying the hash...//the hashes is the same.
MD5 Encryption method