C #: Md5 and Sha1 encryption methods,
1. Create a console application
2. Create an EncryptHelper. cs class.
1 public static class EncryptHelper 2 {3 /// <summary> 4 /// Md5-based custom encryption string method: enter a string, returns a hex Hash hash (string) consisting of 32 characters ). 5 /// </summary> 6 /// <param name = "str"> string to be encrypted </param> 7 /// <returns> the encrypted hexadecimal value hash hash (string) </returns> 8 public static string Md5 (this string str) 9 {10 // convert the input string to a byte array 11 var buffer = Encoding. default. getBytes (str); 12 // then, create an Md5 object for hash calculation 13 var data = MD5.Create (). computeHash (buffer); 14 15 // create a new Stringbuilder to collect byte 16 var sb = new StringBuilder (); 17 18 // traverse the hash data of each byte 19 foreach (var t in data) 20 {21 // Lattice Every hexadecimal string 22 sb. append (t. toString ("X2"); 23} 24 25 // returns the hexadecimal string 26 return sb. toString (); 27} 28 29 // <summary> 30 // Sha1-based custom encryption string method: enter a string, returns a hex Hash hash (string) consisting of 40 characters ). 31 /// </summary> 32 // <param name = "str"> string to be encrypted </param> 33 // <returns> the encrypted hexadecimal value hash hash (string) </returns> 34 public static string Sha1 (this string str) 35 {36 var buffer = Encoding. UTF8.GetBytes (str); 37 var data = SHA1.Create (). computeHash (buffer); 38 39 var sb = new StringBuilder (); 40 foreach (var t in data) 41 {42 sb. append (t. toString ("X2"); 43} 44 45 return sb. toString (); 46} 47}
3. modify Program. cs
1 class Program 2 {3 static void Main (string [] args) 4 {5 const string s = "123456"; 6 Console. writeLine ("Password:" + s); 7 8 Console. writeLine ("Md5:" + s. md5 (); 9 Console. writeLine ("Length:" + s. md5 (). length); 10 11 Console. writeLine ("Sha1:" + s. sha1 (); 12 Console. writeLine ("Length:" + s. sha1 (). length); 13 14 Console. read (); 15} 16}View Code
4.