The next generation of the Teknik Services. Written in ASP.NET. https://www.teknik.io/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

MD5.cs 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using System;
  2. using System.IO;
  3. using System.Text;
  4. namespace Teknik.Utilities.Cryptography
  5. {
  6. public class MD5
  7. {
  8. public static string Hash(string value)
  9. {
  10. byte[] valBytes = Encoding.ASCII.GetBytes(value);
  11. System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
  12. byte[] hashBytes = md5.ComputeHash(valBytes);
  13. StringBuilder sBuilder = new StringBuilder();
  14. // Loop through each byte of the hashed data
  15. // and format each one as a hexadecimal string.
  16. for (int i = 0; i < hashBytes.Length; i++)
  17. {
  18. sBuilder.Append(hashBytes[i].ToString("x2"));
  19. }
  20. // Return the hexadecimal string.
  21. return sBuilder.ToString();
  22. }
  23. public static byte[] Hash(byte[] value)
  24. {
  25. System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
  26. return md5.ComputeHash(value);
  27. }
  28. public static string FileHash(string filename)
  29. {
  30. try
  31. {
  32. using (var md5 = System.Security.Cryptography.MD5.Create())
  33. {
  34. using (var stream = File.OpenRead(filename))
  35. {
  36. return BitConverter.ToString(md5.ComputeHash(stream)).Replace("-", "").ToLower();
  37. }
  38. }
  39. }
  40. catch (Exception)
  41. {
  42. return string.Empty;
  43. }
  44. }
  45. public static string DataHash(string data)
  46. {
  47. try
  48. {
  49. using (var md5 = System.Security.Cryptography.MD5.Create())
  50. {
  51. // convert string to stream
  52. byte[] byteArray = Encoding.UTF8.GetBytes(data);
  53. using (MemoryStream stream = new MemoryStream(byteArray))
  54. {
  55. return BitConverter.ToString(md5.ComputeHash(stream)).Replace("-", "").ToLower();
  56. }
  57. }
  58. }
  59. catch (Exception)
  60. {
  61. return string.Empty;
  62. }
  63. }
  64. }
  65. }