Forums » Bugs & Problems Search

MD5 of file New Reply

Author Post
Posts: 5
Registered: Aug 19, 2011

If I calculate the MD5 of a file, I get a different MD5 then what Echoprint reports on a file upload. Can somebody point out how the MD5 is calculated? Thanks, Ed

Posts: 713
Registered: Sep 08, 2008

eltmon - here's some Java code that calculates the MD5

public static String md5(File f) throws IOException {
    byte[] buffer = new byte[8192];
    int read = 0;
    InputStream is = null;
    try {
        MessageDigest digest = MessageDigest.getInstance("MD5");
        is = new BufferedInputStream(new FileInputStream(f));
        while ((read = is.read(buffer)) > 0) {
            digest.update(buffer, 0, read);
        }
        byte[] md5sum = digest.digest();
        BigInteger bigInt = new BigInteger(1, md5sum);
        String output = bigInt.toString(16);
        // the MD5 needs to be 32 characters long.
        return prepad(output, 32, '0');
    } catch (NoSuchAlgorithmException e) {
        throw new IOException("Can't find md5 algorithm");
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

Here's some Python that calculates the MD5

hashlib.md5(file_object.read()).hexdigest()

Hope this helps

Paul

Reply to this Thread

You must log in to post a reply.