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.3KB

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