MD5.java 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package com.yihu.ehr.util.encrypt;
  2. import com.yihu.ehr.util.encode.HexEncode;
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.FileNotFoundException;
  6. import java.io.IOException;
  7. import java.lang.reflect.Method;
  8. import java.nio.MappedByteBuffer;
  9. import java.nio.channels.FileChannel;
  10. import java.security.AccessController;
  11. import java.security.MessageDigest;
  12. import java.security.PrivilegedAction;
  13. /**
  14. * @created Air 2015/6/2.
  15. */
  16. public class MD5 {
  17. static public String hash(String str) throws Exception {
  18. MessageDigest messageDigest = null;
  19. messageDigest = MessageDigest.getInstance("MD5");
  20. messageDigest.reset();
  21. messageDigest.update(str.getBytes());
  22. return HexEncode.toHexString(messageDigest.digest());
  23. }
  24. public static String getMd5ByFile(File file) throws FileNotFoundException {
  25. String value = null;
  26. FileInputStream in = new FileInputStream(file);
  27. MappedByteBuffer byteBuffer =null;
  28. try {
  29. byteBuffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length());
  30. MessageDigest md5 = MessageDigest.getInstance("MD5");
  31. md5.update(byteBuffer);
  32. // BigInteger bi = new BigInteger(1, md5.digest());
  33. // value = bi.toString(16);
  34. value= HexEncode.toHexString(md5.digest());
  35. } catch (Exception e) {
  36. e.printStackTrace();
  37. } finally {
  38. if(null != in) {
  39. try {
  40. in.close();
  41. clean(byteBuffer);
  42. } catch (IOException e) {
  43. e.printStackTrace();
  44. } catch (Exception e) {
  45. e.printStackTrace();
  46. }
  47. }
  48. }
  49. return value;
  50. }
  51. public static void clean(final Object buffer) throws Exception {
  52. AccessController.doPrivileged(new PrivilegedAction() {
  53. public Object run() {
  54. try {
  55. Method getCleanerMethod = buffer.getClass().getMethod("cleaner", new Class[0]);
  56. getCleanerMethod.setAccessible(true);
  57. sun.misc.Cleaner cleaner = (sun.misc.Cleaner) getCleanerMethod.invoke(buffer, new Object[0]);
  58. cleaner.clean();
  59. } catch (Exception e) {
  60. e.printStackTrace();
  61. }
  62. return null;
  63. }
  64. });
  65. }
  66. }