MD5Util.java 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package com.caimei.utils;
  2. import java.security.MessageDigest;
  3. import java.util.UUID;
  4. /**
  5. * @author : Charles
  6. * @description : Description
  7. * @date : 2020/1/3
  8. */
  9. public class MD5Util {
  10. /**
  11. * md5加密
  12. * @param s:待加密字符串
  13. * @return 加密后16进制字符串
  14. */
  15. public static String md5(String s) {
  16. try {
  17. //实例化MessageDigest的MD5算法对象
  18. MessageDigest md = MessageDigest.getInstance("MD5");
  19. //通过digest方法返回哈希计算后的字节数组
  20. byte[] bytes = md.digest(s.getBytes("utf-8"));
  21. //将字节数组转换为16进制字符串并返回
  22. return toHex(bytes);
  23. }
  24. catch (Exception e) {
  25. throw new RuntimeException(e);
  26. }
  27. }
  28. /**
  29. * 获取随即盐
  30. * @return
  31. */
  32. public static String salt(){
  33. //利用UUID生成随机盐
  34. UUID uuid = UUID.randomUUID();
  35. //返回a2c64597-232f-4782-ab2d-9dfeb9d76932
  36. String[] arr = uuid.toString().split("-");
  37. return arr[0];
  38. }
  39. /**
  40. * 字节数组转换为16进制字符串
  41. * @param bytes数组
  42. * @return 16进制字符串
  43. */
  44. private static String toHex(byte[] bytes) {
  45. final char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray();
  46. StringBuilder ret = new StringBuilder(bytes.length * 2);
  47. for (int i=0; i<bytes.length; i++) {
  48. ret.append(HEX_DIGITS[(bytes[i] >> 4) & 0x0f]);
  49. ret.append(HEX_DIGITS[bytes[i] & 0x0f]);
  50. }
  51. return ret.toString();
  52. }
  53. }