柯桥增值式服务
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.

52 lines
1.5KB

  1. package com.ningdatech.kqapi.common.util;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. import java.nio.charset.StandardCharsets;
  5. import java.security.MessageDigest;
  6. public class Md5Utils {
  7. private static final Logger LOGGER = LoggerFactory.getLogger(Md5Utils.class);
  8. public static byte[] md5(String s) {
  9. MessageDigest algorithm;
  10. try {
  11. algorithm = MessageDigest.getInstance("MD5");
  12. algorithm.reset();
  13. algorithm.update(s.getBytes(StandardCharsets.UTF_8));
  14. return algorithm.digest();
  15. } catch (Exception e) {
  16. LOGGER.error("MD5 Error...",e.getMessage());
  17. }
  18. return null;
  19. }
  20. private static String toHex(byte[] hash) {
  21. if (hash == null) {
  22. return null;
  23. }
  24. StringBuilder buf = new StringBuilder(hash.length * 2);
  25. int i;
  26. for (i = 0; i < hash.length; i++) {
  27. if ((hash[i] & 0xff) < 0x10) {
  28. buf.append("0");
  29. }
  30. buf.append(Long.toString(hash[i] & 0xff, 16));
  31. }
  32. return buf.toString();
  33. }
  34. public static String hash(String s) {
  35. try {
  36. String hex = toHex(md5(s));
  37. if (hex == null) {
  38. return s;
  39. }
  40. return new String(hex.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8);
  41. } catch (Exception e) {
  42. LOGGER.error("not supported charset:", e.getMessage());
  43. return s;
  44. }
  45. }
  46. }