HashService.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using System;
  2. using System.Text;
  3. using System.Security.Cryptography;
  4. using log4net;
  5. using System.IO;
  6. namespace Agent.Services
  7. {
  8. class HashService
  9. {
  10. private static readonly ILog log = LogManager.GetLogger(typeof(HashService));
  11. private readonly SHA256 _sha256 = SHA256.Create();
  12. private readonly MD5 _md5 = MD5.Create();
  13. /// <summary>
  14. /// SHA256 HEX 문자열 (-제거)
  15. /// </summary>
  16. /// <param name="plain"></param>
  17. /// <returns></returns>
  18. public string ToSHA256(string plain)
  19. {
  20. try
  21. {
  22. return ToSHA256(Encoding.UTF8.GetBytes(plain));
  23. }
  24. catch (Exception e)
  25. {
  26. log.Error(e);
  27. return null;
  28. }
  29. }
  30. private string ToSHA256(byte[] plain)
  31. {
  32. try
  33. {
  34. return BitConverter.ToString(_sha256.ComputeHash(plain)).Replace("-", "");
  35. }
  36. catch (Exception)
  37. {
  38. throw;
  39. }
  40. }
  41. /// <summary>
  42. /// 파일 -> MD5 HEX 문자열 (-제거)
  43. /// </summary>
  44. /// <param name="path"></param>
  45. /// <returns></returns>
  46. public string FileToMD5(string path)
  47. {
  48. try
  49. {
  50. using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
  51. {
  52. byte[] buff = new byte[fs.Length];
  53. fs.Read(buff, 0, buff.Length);
  54. return ToMD5(buff);
  55. }
  56. }
  57. catch (Exception e)
  58. {
  59. log.Error(e);
  60. return null;
  61. }
  62. }
  63. private string ToMD5(byte[] plain)
  64. {
  65. try
  66. {
  67. return BitConverter.ToString(_md5.ComputeHash(plain)).Replace("-", "");
  68. }
  69. catch (Exception)
  70. {
  71. throw;
  72. }
  73. }
  74. }
  75. }