Md5Utils.java 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. package com.onemap.api.util;
  2. import org.apache.commons.codec.binary.Hex;
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import java.io.File;
  6. import java.io.FileInputStream;
  7. import java.io.IOException;
  8. import java.nio.charset.StandardCharsets;
  9. import java.security.MessageDigest;
  10. /**
  11. * Md5加密方法
  12. *
  13. * @author ruoyi
  14. */
  15. public class Md5Utils
  16. {
  17. private static final Logger log = LoggerFactory.getLogger(Md5Utils.class);
  18. private static byte[] md5(String s)
  19. {
  20. MessageDigest algorithm;
  21. try
  22. {
  23. algorithm = MessageDigest.getInstance("MD5");
  24. algorithm.reset();
  25. algorithm.update(s.getBytes("UTF-8"));
  26. byte[] messageDigest = algorithm.digest();
  27. return messageDigest;
  28. }
  29. catch (Exception e)
  30. {
  31. log.error("MD5 Error...", e);
  32. }
  33. return null;
  34. }
  35. private static final String toHex(byte hash[])
  36. {
  37. if (hash == null)
  38. {
  39. return null;
  40. }
  41. StringBuffer buf = new StringBuffer(hash.length * 2);
  42. int i;
  43. for (i = 0; i < hash.length; i++)
  44. {
  45. if ((hash[i] & 0xff) < 0x10)
  46. {
  47. buf.append("0");
  48. }
  49. buf.append(Long.toString(hash[i] & 0xff, 16));
  50. }
  51. return buf.toString();
  52. }
  53. public static String hash(String s)
  54. {
  55. try
  56. {
  57. return new String(toHex(md5(s)).getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8);
  58. }
  59. catch (Exception e)
  60. {
  61. log.error("not supported charset...{}", e);
  62. return s;
  63. }
  64. }
  65. /**
  66. * 获取一个文件的md5值(可处理大文件)
  67. * @return md5 value
  68. */
  69. public static String getMD5(File file) {
  70. FileInputStream fileInputStream = null;
  71. try {
  72. MessageDigest MD5 = MessageDigest.getInstance("MD5");
  73. fileInputStream = new FileInputStream(file);
  74. byte[] buffer = new byte[8192];
  75. int length;
  76. while ((length = fileInputStream.read(buffer)) != -1) {
  77. MD5.update(buffer, 0, length);
  78. }
  79. return new String(Hex.encodeHex(MD5.digest()));
  80. } catch (Exception e) {
  81. e.printStackTrace();
  82. return null;
  83. } finally {
  84. try {
  85. if (fileInputStream != null){
  86. fileInputStream.close();
  87. }
  88. } catch (IOException e) {
  89. System.out.println(e.getMessage());
  90. }
  91. }
  92. }
  93. }