MD5Util.java 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package com.tiangua.star.util;
  2. import java.security.MessageDigest;
  3. /**
  4. * The type Md 5 util.
  5. */
  6. public abstract class MD5Util {
  7. /**
  8. * Md 5 string.
  9. *
  10. * @param pwd the pwd
  11. * @return the string
  12. */
  13. public final static String MD5(String pwd) {
  14. //用于加密的字符
  15. char md5String[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  16. 'A', 'B', 'C', 'D', 'E', 'F' };
  17. try {
  18. //使用平台的默认字符集将此 String 编码为 byte序列,并将结果存储到一个新的 byte数组中
  19. byte[] btInput = pwd.getBytes();
  20. //信息摘要是安全的单向哈希函数,它接收任意大小的数据,并输出固定长度的哈希值。
  21. MessageDigest mdInst = MessageDigest.getInstance("MD5");
  22. //MessageDigest对象通过使用 update方法处理数据, 使用指定的byte数组更新摘要
  23. mdInst.update(btInput);
  24. // 摘要更新之后,通过调用digest()执行哈希计算,获得密文
  25. byte[] md = mdInst.digest();
  26. // 把密文转换成十六进制的字符串形式
  27. int j = md.length;
  28. char str[] = new char[j * 2];
  29. int k = 0;
  30. for (int i = 0; i < j; i++) { // i = 0
  31. byte byte0 = md[i]; //95
  32. str[k++] = md5String[byte0 >>> 4 & 0xf]; // 5
  33. str[k++] = md5String[byte0 & 0xf]; // F
  34. }
  35. //返回经过加密后的字符串
  36. return new String(str);
  37. } catch (Exception e) {
  38. return null;
  39. }
  40. }
  41. private static String byteArrayToHexString(byte b[]) {
  42. StringBuffer resultSb = new StringBuffer();
  43. for (int i = 0; i < b.length; i++)
  44. resultSb.append(byteToHexString(b[i]));
  45. return resultSb.toString();
  46. }
  47. private static String byteToHexString(byte b) {
  48. int n = b;
  49. if (n < 0)
  50. n += 256;
  51. int d1 = n / 16;
  52. int d2 = n % 16;
  53. return hexDigits[d1] + hexDigits[d2];
  54. }
  55. /**
  56. * Md 5 encode string.
  57. *
  58. * @param origin the origin
  59. * @param charsetname the charsetname
  60. * @return the string
  61. */
  62. public static String MD5Encode(String origin, String charsetname) {
  63. String resultString = null;
  64. try {
  65. resultString = new String(origin);
  66. MessageDigest md = MessageDigest.getInstance("MD5");
  67. if (charsetname == null || "".equals(charsetname))
  68. resultString = byteArrayToHexString(md.digest(resultString
  69. .getBytes()));
  70. else
  71. resultString = byteArrayToHexString(md.digest(resultString
  72. .getBytes(charsetname)));
  73. } catch (Exception exception) {
  74. }
  75. return resultString;
  76. }
  77. private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5",
  78. "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
  79. public static void main(String[] a) {
  80. System.out.println(MD5Encode("13758525535NsArzbOcYie4XMW5iGrkA","UTF-8"));
  81. }
  82. }