fork download
  1. using System;
  2. using System.Security.Cryptography;
  3. using System.Text;
  4.  
  5. class Example
  6. {
  7. // Hash an input string and return the hash as
  8. // a 32 character hexadecimal string.
  9. static string getMd5Hash(string input)
  10. {
  11. // Create a new instance of the MD5CryptoServiceProvider object.
  12. MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
  13.  
  14. // Convert the input string to a byte array and compute the hash.
  15. byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));
  16.  
  17. // Create a new Stringbuilder to collect the bytes
  18. // and create a string.
  19. StringBuilder sBuilder = new StringBuilder();
  20.  
  21. // Loop through each byte of the hashed data
  22. // and format each one as a hexadecimal string.
  23. for (int i = 0; i < data.Length; i++)
  24. {
  25. sBuilder.Append(data[i].ToString("x2"));
  26. }
  27.  
  28. // Return the hexadecimal string.
  29. return sBuilder.ToString();
  30. }
  31.  
  32. // Verify a hash against a string.
  33. static bool verifyMd5Hash(string input, string hash)
  34. {
  35. // Hash the input.
  36. string hashOfInput = getMd5Hash(input);
  37.  
  38. // Create a StringComparer an compare the hashes.
  39. StringComparer comparer = StringComparer.OrdinalIgnoreCase;
  40.  
  41. if (0 == comparer.Compare(hashOfInput, hash))
  42. {
  43. return true;
  44. }
  45. else
  46. {
  47. return false;
  48. }
  49. }
  50.  
  51.  
  52. static void Main()
  53. {
  54. string source = "Grup 941";
  55.  
  56. string hash = getMd5Hash(source);
  57.  
  58. Console.WriteLine("The MD5 hash of " + source + " is: " + hash + ".");
  59.  
  60. Console.WriteLine("Verifying the hash...");
  61.  
  62. if (verifyMd5Hash(source, hash))
  63. {
  64. Console.WriteLine("The hashes are the same.");
  65. }
  66. else
  67. {
  68. Console.WriteLine("The hashes are not same.");
  69. }
  70.  
  71. }
  72. }
  73. // This code example produces the following output:
  74. //
  75. // The MD5 hash of Hello World! is: ed076287532e86365e841e92bfc50d8c.
  76. // Verifying the hash...
  77. // The hashes are the same.
Success #stdin #stdout 0.01s 131648KB
stdin
Standard input is empty
stdout
The MD5 hash of Grup 941 is: f9dc4dda4acf405ebb0100f326e6cbbd.
Verifying the hash...
The hashes are the same.