a Java, Jython & Python Comparison
 

Each program runs from the commandline and computes a MD5 hash (message digest) for a specified file. 

Java:

import java.io.*;
import java.security.*;

import sun.misc.*;

public class Masher {
    public static void main(String[] args) throws Exception {
        // Check arguments.
        if (args.length != 1) {
            System.out.println("Usage: Masher filename");
            return;
        }

        // Obtain a message digest object.
        MessageDigest md = MessageDigest.getInstance("MD5");

        // Calculate the digest for the given file.
        FileInputStream in = new FileInputStream(args[0]);
        byte[] block = new byte[8192];
        int length;
        while ((length = in.read(block)) != -1)
            md.update(block, 0, length);
        byte[] raw = md.digest();

        // Print out the digest in base64.
        BASE64Encoder encoder = new BASE64Encoder();
        String hexhash = encoder.encode(raw);
        System.out.println(hexhash);
    }
}

Jython:

from java.security import MessageDigest
from sun.misc      import BASE64Encoder
import sys

# Check arguments.
if len(sys.argv) != 2:
    print 'Usage: jython masher.jy '
    sys.exit()

# Obtain a message digest object.
md = MessageDigest.getInstance('MD5')

# Calculate the digest for the given file.
fin = open(sys.argv[1], 'rb')
for block in fin.read(8192):
    md.update(block)
raw = md.digest()

# Print out the digest in base64.
b64encoder = BASE64Encoder()
hexhash = b64encoder.encode(raw)
print hexhash

       

Python:

import md5, base64, sys



# Check arguments.
if len(sys.argv) != 2:
    print 'Usage: python masher.py '
    sys.exit()

# Obtain a message digest object.
md = md5.md5()

# Calculate the digest for the given file.
fin = open(sys.argv[1], 'rb')
for block in fin.read(8192):
    md.update(block)
raw = md.digest()

# Print out the digest in base64.
hexhash = base64.encodestring(raw)
print hexhash


Larry Bugbee, Last updated: 05 April 2003