MD5Util.java 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package com.uas.utils;
  2. import java.io.UnsupportedEncodingException;
  3. import java.math.BigInteger;
  4. import java.security.MessageDigest;
  5. import java.security.NoSuchAlgorithmException;
  6. public class MD5Util {
  7. public static String MD5(String plainText) {
  8. try {
  9. MessageDigest md = MessageDigest.getInstance("MD5");
  10. try {
  11. md.update(plainText.getBytes("UTF8"));
  12. } catch (UnsupportedEncodingException e) {
  13. e.printStackTrace();
  14. }
  15. byte b[] = md.digest();
  16. int i;
  17. StringBuffer buf = new StringBuffer(200);
  18. for (int offset = 0; offset < b.length; offset++) {
  19. i = b[offset] & 0xff;
  20. if (i < 16) buf.append("0");
  21. buf.append(Integer.toHexString(i));
  22. }
  23. return buf.toString();
  24. } catch (NoSuchAlgorithmException e) {
  25. throw new RuntimeException("MD5加密出现错误");
  26. }
  27. }
  28. public static String getMD5(String str) {
  29. try {
  30. MessageDigest md = MessageDigest.getInstance("MD5");
  31. md.update(str.getBytes());
  32. return new BigInteger(1, md.digest()).toString(16);
  33. } catch (Exception e) {
  34. throw new RuntimeException("MD5加密出现错误");
  35. }
  36. }
  37. /**
  38. * MD5加密
  39. * @param message
  40. * @return
  41. */
  42. public static String getEncryption(String message){
  43. String result = "";
  44. if(message != null){
  45. try {
  46. MessageDigest md = MessageDigest.getInstance("MD5"); //指定加密方式
  47. //加密
  48. byte[] bytes = md.digest(message.getBytes());
  49. for(int i = 0; i < bytes.length; i++){
  50. // 将整数转换成十六进制形式的字符串 这里与0xff进行与运算的原因是保证转换结果为32位
  51. String str = Integer.toHexString(bytes[i] & 0xFF);
  52. if(str.length() == 1){
  53. str += "F";
  54. }
  55. result += str;
  56. }
  57. } catch (NoSuchAlgorithmException e) {
  58. e.printStackTrace();
  59. }
  60. }
  61. return result;
  62. }
  63. }