Question

I'm new to java and really need some help. I created a command line tool in order to get an MD5 hash of a file. This worked so I then tailored my code to put it in GUI form. The two programs give different hashes of the same file which is confusing. I have looked into UTF-8 but as far as I can tell that would only work for strings and not a file instance. Can anyone tell me why they are providing different hash values and point me in the right direction?

First method (command line)...

    public static void main(String args[]) throws IOException, NoSuchAlgorithmException {

    System.out.println("Please enter file path: \n");

    BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
    String dir = stdin.readLine();
    File file = new File(dir);

    FileInputStream iStream = null;

    try {iStream = new FileInputStream(file);}
    catch (FileNotFoundException e) {      
        String MD5Output = "There has been an error: " + e.toString();   
    }

    byte[] dataBytes = new byte[1024];

    MessageDigest md = MessageDigest.getInstance("MD5");

    int numRead = iStream.read(dataBytes);
        md.update(dataBytes, 0, numRead);

        iStream.close();

        dataBytes = md.digest();

    md.update(dataBytes);
    System.out.println("MD5: " + new BigInteger(1, md.digest()).toString(16));

}

Second method (built for gui)...

    public void doMD5() throws IOException, NoSuchAlgorithmException {

    File file = new File(jTxtMD51.getText());

    FileInputStream iStream = null;

    try {iStream = new FileInputStream(file);}
    catch (FileNotFoundException e) {      
        String MD5Output = "There has been an error: " + e.toString();   
    }

    byte[] dataBytes = new byte[1024];

    MessageDigest md = MessageDigest.getInstance("MD5");

    int numRead = iStream.read(dataBytes);
        md.update(dataBytes, 0, numRead);

        iStream.close();

        byte[] MD5checksum = md.digest();

    md.update(dataBytes);

    BigInteger bigInt = new BigInteger(1, md.digest());
    String MD5Hash = bigInt.toString(16);

    jTextOutput.append("MD5 is : " + MD5Hash);

}
Was it helpful?

Solution

you only make one read call from the stream. you need to loop when reading an InputStream (assuming you want to read the whole thing, which you generally want). additionally, you seem to make 2 calls to digest.update() using the same bytes.

also, typically when a hash value is printed, since it is a binary value, it is printed using base64 encoding.

OTHER TIPS

In addition to @jtahlborn's comment, you don't need the md.update(databytes); call in both methods, and your second method should have this at the end:

BigInteger bigInt = new BigInteger(1, MD5checksum);

You first method doesn't do this second call to digest(), whose values changes when you make the call to update()

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top