Md5Util.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. using System.Linq;
  2. using System.Security.Cryptography;
  3. using System.Text;
  4. namespace WebDAVSharp.Server.Utilities
  5. {
  6. /// <summary>
  7. /// For generating an MD5 hash
  8. /// </summary>
  9. /// <remarks>
  10. /// Source: <see href="https://gist.github.com/kristopherjohnson/3021045" />
  11. /// </remarks>
  12. internal static class Md5Util
  13. {
  14. /// <summary>
  15. /// Compute hash for string encoded as UTF8
  16. /// </summary>
  17. /// <param name="s">String to be hashed</param>
  18. /// <returns>32-character hex string</returns>
  19. public static string Md5HashStringForUtf8String(string s)
  20. {
  21. byte[] bytes = Encoding.UTF8.GetBytes(s);
  22. MD5 md5 = MD5.Create();
  23. byte[] hashBytes = md5.ComputeHash(bytes);
  24. return HexStringFromBytes(hashBytes);
  25. }
  26. /// <summary>
  27. /// Convert an array of bytes to a string of hex digits
  28. /// </summary>
  29. /// <param name="bytes">Array of bytes</param>
  30. /// <returns>
  31. /// String of hex digits
  32. /// </returns>
  33. public static string HexStringFromBytes(byte[] bytes)
  34. {
  35. StringBuilder sb = new StringBuilder(1000);
  36. foreach (string hex in bytes.Select(b => b.ToString("x2")))
  37. sb.Append(hex);
  38. return sb.ToString();
  39. }
  40. }
  41. }