yambroskin

Untitled

Aug 25th, 2017
212
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.96 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Security.Cryptography;
  4. using System.Text;
  5. using MongoDB.Bson;
  6.  
  7. namespace Yambr.Core.Helpers
  8. {
  9. public static class MD5Helper
  10. {
  11. public static string GetHashByJson(this object sourse)
  12. {
  13. return GetHash(sourse.ToJson());
  14. }
  15.  
  16. public static string GetHash(this string source)
  17. {
  18. using (var md5Hash = MD5.Create())
  19. {
  20. return GetMd5Hash(md5Hash, source);
  21. }
  22. }
  23.  
  24. public static string GetHash(this byte[] source)
  25. {
  26. using (var md5Hash = MD5.Create())
  27. {
  28. return GetMd5Hash(md5Hash, source);
  29. }
  30. }
  31. /*не протестировано
  32. public static string GetHash(this Stream source)
  33. {
  34. using (var md5Hash = MD5.Create())
  35. {
  36. return GetMd5Hash(md5Hash, source);
  37. }
  38. }*/
  39.  
  40.  
  41. public static bool VerifyHash(string source, string hash)
  42. {
  43. using (var md5Hash = MD5.Create())
  44. {
  45. return VerifyMd5Hash(md5Hash, source, hash);
  46. }
  47. }
  48.  
  49.  
  50. private static string GetMd5Hash(HashAlgorithm md5Hash, string input)
  51. {
  52. var bytes = Encoding.UTF8.GetBytes(input);
  53. return GetMd5Hash(md5Hash, bytes);
  54. }
  55.  
  56. private static string GetMd5Hash(HashAlgorithm md5Hash, byte[] bytes)
  57. {
  58. // Convert the input string to a byte array and compute the hash.
  59. var data = md5Hash.ComputeHash(bytes);
  60. return Md5ToString(data);
  61. }
  62. /*private static string GetMd5Hash(HashAlgorithm md5Hash, Stream stream)
  63. {
  64. // Convert the input string to a byte array and compute the hash.
  65. var data = md5Hash.ComputeHash(stream);
  66. return Md5ToString(data);
  67. }*/
  68.  
  69. private static string Md5ToString(IEnumerable<byte> data)
  70. {
  71. // Create a new Stringbuilder to collect the bytes
  72. // and create a string.
  73. var sBuilder = new StringBuilder();
  74.  
  75. // Loop through each byte of the hashed data
  76. // and format each one as a hexadecimal string.
  77. foreach (var t in data)
  78. {
  79. sBuilder.Append(t.ToString("x2"));
  80. }
  81.  
  82. // Return the hexadecimal string.
  83. return sBuilder.ToString();
  84. }
  85.  
  86. // Verify a hash against a string.
  87. private static bool VerifyMd5Hash(HashAlgorithm md5Hash, string input, string hash)
  88. {
  89. // Hash the input.
  90. var hashOfInput = GetMd5Hash(md5Hash, input);
  91. // Create a StringComparer an compare the hashes.
  92. var comparer = StringComparer.OrdinalIgnoreCase;
  93. return 0 == comparer.Compare(hashOfInput, hash);
  94. }
  95.  
  96. }
  97. }
Advertisement
Add Comment
Please, Sign In to add comment