code_junkie

using Java to get a file's md5 checksum?

Nov 12th, 2011
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. MessageDigest md = MessageDigest.getInstance("MD5");
  2. InputStream is = new FileInputStream("file.txt");
  3. try {
  4. is = new DigestInputStream(is, md);
  5. // read stream to EOF as normal...
  6. }
  7. finally {
  8. is.close();
  9. }
  10. byte[] digest = md.digest();
  11.  
  12. FileInputStream fis = new FileInputStream( new File("foo" ) );
  13. String md5 = org.apache.commons.codec.digest.DigestUtils.md5Hex( fis );
  14.  
  15. try {
  16. String s = "TEST STRING";
  17. MessageDigest md5 = MessageDigest.getInstance("MD5");
  18. md5.update(s.getBytes(),0,s.length());
  19. String signature = new BigInteger(1,md5.digest()).toString(16);
  20. System.out.println("Signature: "+signature);
  21.  
  22. } catch (final NoSuchAlgorithmException e) {
  23. e.printStackTrace();
  24. }
  25.  
  26. File myfile = new File("myfile.txt");
  27. long checksum = Files.getChecksum(myfile , new java.util.zip.CRC32());
  28.  
  29. File myfile = new File("myfile.txt");
  30. byte[] digest = Files.getDigest(myfile , MessageDigest.getInstance("SHA-256"));
  31.  
  32. public static String MD5Hash(String toHash) throws RuntimeException {
  33. try{
  34. return String.format("%032x", // produces lower case 32 char wide hexa left-padded with 0
  35. new BigInteger(1, // handles large POSITIVE numbers
  36. MessageDigest.getInstance("MD5").digest(toHash.getBytes())));
  37. }
  38. catch (NoSuchAlgorithmException e) {
  39. // do whatever seems relevant
  40. }
  41. }
  42.  
  43. ...
  44. String signature = new BigInteger(1,md5.digest()).toString(16);
  45. ...
  46.  
  47. String hash = MD5.asHex(MD5.getHash(new File(filename)));
  48.  
  49. <checksum file="${jarFile}" todir="${toDir}"/>
Add Comment
Please, Sign In to add comment