1. import java.security.MessageDigest;
  2. import java.util.Locale;
  3. public class MD5Util {
  4. public static String encode(String content) {
  5. try {
  6. MessageDigest digest = MessageDigest.getInstance("MD5");
  7. digest.update(content.getBytes());
  8. return getEncode16(digest);
  9. //return getEncode32(digest);
  10. } catch (Exception e) {
  11. }
  12. return null;
  13. }
  14. /**
  15. * 32位加密
  16. * @param digest
  17. * @return
  18. */
  19. private static String getEncode32(MessageDigest digest) {
  20. StringBuilder builder = new StringBuilder();
  21. for (byte b : digest.digest()) {
  22. builder.append(Integer.toHexString((b >> 4) & 0xf));
  23. builder.append(Integer.toHexString(b & 0xf));
  24. }
  25. //return builder.toString().toLowerCase(); // 小写
  26. //return builder.toString().toUpperCase(); // 大写
  27. // java.lang.String.toUpperCase(Locale locale) 方法将在此字符串中的所有字符为大写的规则给定的Locale.
  28. //return builder.toString().toUpperCase(Locale.getDefault()); // 大写
  29. return builder.toString();
  30. }
  31. /**
  32. * 16位加密
  33. * @param digest
  34. * @return
  35. */
  36. private static String getEncode16(MessageDigest digest) {
  37. StringBuilder builder = new StringBuilder();
  38. for (byte b : digest.digest()) {
  39. builder.append(Integer.toHexString((b >> 4) & 0xf));
  40. builder.append(Integer.toHexString(b & 0xf));
  41. }
  42. // 16位加密,从第9位到25位
  43. //return builder.substring(8, 24).toString().toUpperCase();
  44. return builder.substring(8, 24).toString();
  45. }
  46. }
  47. 参考:http://jiewushanshan.lofter.com/post/cf538_1d903d
  48. http://blog.csdn.net/lincyang/article/details/5709189
04-28 08:47