MD5Util.java 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package com.uas.eis.utils;
  2. import java.security.MessageDigest;
  3. import java.security.NoSuchAlgorithmException;
  4. public class MD5Util {
  5. /**
  6. * MD5加密
  7. * @param message
  8. * @return
  9. */
  10. public static String getEncryption(String message){
  11. String result = "";
  12. if(message != null){
  13. try {
  14. MessageDigest md = MessageDigest.getInstance("MD5"); //指定加密方式
  15. //加密
  16. byte[] bytes = md.digest(message.getBytes());
  17. for(int i = 0; i < bytes.length; i++){
  18. // 将整数转换成十六进制形式的字符串 这里与0xff进行与运算的原因是保证转换结果为32位
  19. String str = Integer.toHexString(bytes[i] & 0xFF);
  20. if(str.length() == 1){
  21. str += "F";
  22. }
  23. result += str;
  24. }
  25. } catch (NoSuchAlgorithmException e) {
  26. e.printStackTrace();
  27. }
  28. }
  29. return result;
  30. }
  31. public static String encodeByMD5(String originString) {
  32. if (originString != null) {
  33. try {
  34. MessageDigest md = MessageDigest.getInstance("MD5");
  35. byte[] results = md.digest(originString.getBytes());
  36. String resultString = byteArrayToHexString(results);
  37. return resultString.toUpperCase();
  38. } catch (Exception ex) {
  39. ex.printStackTrace();
  40. }
  41. }
  42. return null;
  43. }
  44. public static String byteArrayToHexString(byte[] bArr) {
  45. StringBuffer sb = new StringBuffer(bArr.length);
  46. String sTmp;
  47. for (int i = 0; i < bArr.length; i++) {
  48. sTmp = Integer.toHexString(0xFF & bArr[i]);
  49. if (sTmp.length() < 2){
  50. sb.append(0);
  51. }
  52. sb.append(sTmp.toUpperCase());
  53. }
  54. return sb.toString();
  55. }
  56. /**
  57. * hex字符串转byte数组
  58. * @param inHex 待转换的Hex字符串
  59. * @return 转换后的byte数组结果
  60. */
  61. public static byte[] hexToByteArray(String inHex){
  62. int hexlen = inHex.length();
  63. byte[] result;
  64. if (hexlen % 2 == 1){
  65. //奇数
  66. hexlen++;
  67. result = new byte[(hexlen/2)];
  68. inHex="0"+inHex;
  69. }else {
  70. //偶数
  71. result = new byte[(hexlen/2)];
  72. }
  73. int j=0;
  74. for (int i = 0; i < hexlen; i+=2){
  75. result[j]=(byte)Integer.parseInt(inHex.substring(i,i+2),16);
  76. j++;
  77. }
  78. return result;
  79. }
  80. }