/plugins/Beauty/tags/beauty-0.5.0/test/test/beauty/util/MD5Sum.java

# · Java · 64 lines · 35 code · 7 blank · 22 comment · 4 complexity · cc0753e6387b0d55d3fb1b42cc49f80e MD5 · raw file

  1. package beauty.util;
  2. import java.io.*;
  3. import java.security.MessageDigest;
  4. // calculates an MD5 sum
  5. public class MD5Sum {
  6. static final byte[] HEX_CHARS = { (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f' } ;
  7. /**
  8. * Calculate the MD5 sum of an input stream. The stream will be closed when
  9. * this method returns.
  10. * @param an input stream
  11. * @return MD5 sum of the given stream
  12. */
  13. public static String sum(InputStream stream) throws Exception {
  14. byte[] buffer = new byte[1024];
  15. MessageDigest messageDigest = MessageDigest.getInstance("MD5");
  16. int numRead;
  17. do {
  18. numRead = stream.read(buffer);
  19. if (numRead > 0) {
  20. messageDigest.update(buffer, 0, numRead);
  21. }
  22. } while (numRead != - 1);
  23. stream.close();
  24. return toHex(messageDigest.digest());
  25. }
  26. /**
  27. * Calculates the MD5 sum of the contents of the given file.
  28. * @param file The file to find the sum for.
  29. * @return MD5 sum of the contents of the given file.
  30. */
  31. public static String sum(File file) throws Exception {
  32. return sum(new FileInputStream(file));
  33. }
  34. /**
  35. * Calculates the MD5 sum of the contents of the given string.
  36. * @param string The string to find the sum for.
  37. * @return MD5 sum of the contents of the given string.
  38. */
  39. public static String sum(String string) throws Exception {
  40. return sum(new ByteArrayInputStream(string.getBytes()));
  41. }
  42. /**
  43. * Converts the given byte array to a hex string.
  44. * @param raw The byte array to convert.
  45. * @return The byte array represented as a string.
  46. */
  47. public static String toHex(byte[] raw) throws UnsupportedEncodingException {
  48. byte[] hex = new byte[2 * raw.length];
  49. int index = 0;
  50. for (byte b : raw) {
  51. int c = b & 0xFF;
  52. hex[index++] = HEX_CHARS[ c >>> 4];
  53. hex[index++] = HEX_CHARS[ c & 0xF];
  54. }
  55. return new String(hex, "ASCII");
  56. }
  57. }