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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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 string FileHash(string filename)
  27. {
  28. try
  29. {
  30. using (var md5 = System.Security.Cryptography.MD5.Create())
  31. {
  32. using (var stream = File.OpenRead(filename))
  33. {
  34. return BitConverter.ToString(md5.ComputeHash(stream)).Replace("-", "").ToLower();
  35. }
  36. }
  37. }
  38. catch (Exception)
  39. {
  40. return string.Empty;
  41. }
  42. }
  43. public static string DataHash(string data)
  44. {
  45. try
  46. {
  47. using (var md5 = System.Security.Cryptography.MD5.Create())
  48. {
  49. // convert string to stream
  50. byte[] byteArray = Encoding.UTF8.GetBytes(data);
  51. using (MemoryStream stream = new MemoryStream(byteArray))
  52. {
  53. return BitConverter.ToString(md5.ComputeHash(stream)).Replace("-", "").ToLower();
  54. }
  55. }
  56. }
  57. catch (Exception)
  58. {
  59. return string.Empty;
  60. }
  61. }
  62. }
  63. }