MD5.java 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package com.usai.util;
  2. import java.security.MessageDigest;
  3. import java.io.FileInputStream;
  4. import java.io.InputStream;
  5. public class MD5 {
  6. private static final char HEX_DIGITS[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  7. 'A', 'B', 'C', 'D', 'E', 'F' };
  8. public static void main(String[] args)
  9. {
  10. System.out.println(md5sum("/init.rc"));
  11. }
  12. public static String toHexString(byte[] b) {
  13. StringBuilder sb = new StringBuilder(b.length * 2);
  14. for (int i = 0; i < b.length; i++) {
  15. sb.append(HEX_DIGITS[(b[i] & 0xf0) >>> 4]);
  16. sb.append(HEX_DIGITS[b[i] & 0x0f]);
  17. }
  18. return sb.toString();
  19. }
  20. public static String md5sum(String filename) {
  21. InputStream fis;
  22. byte[] buffer = new byte[1024];
  23. int numRead = 0;
  24. MessageDigest md5;
  25. try{
  26. fis = new FileInputStream(filename);
  27. md5 = MessageDigest.getInstance("MD5");
  28. while((numRead=fis.read(buffer)) > 0) {
  29. md5.update(buffer,0,numRead);
  30. }
  31. fis.close();
  32. return toHexString(md5.digest());
  33. } catch (Exception e) {
  34. System.out.println("error");
  35. return null;
  36. }
  37. }
  38. }