-2

I can generate md5 with this function :

private void generateMd5() throws NoSuchAlgorithmException, IOException {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] hash = md.digest(pathFile.getBytes());
        nomGestionnaire.setText(String.valueOf(String.format("%032X", new BigInteger(1, hash))));

    }

My problem is when I compare my md5 generate with another md5 generator I don't have the same value. Is it normal ? It's like my generator doesn't generate a real md5 ?

Test with this file : aaa.txt (content : aaa)

My generator : A4FA953DB4BC7772E5AF67BD706B9110

other generator : 47bce5c74f589f4867dbd57e9ca9f808

EDIT :

FileChooser fileChooser = new FileChooser();
File selectedFile = new 
File(String.valueOf(fileChooser.showOpenDialog(primaryStage)));
nameFile = selectedFile.getName();
pathFile = selectedFile.getPath();

2 Answers2

2

I guess there's some error on the input. Unfortunately the and file you provided is not complete. So I did I first wrote a Java method that does a basic md5. Then I did some forensics to guess and fix the code. Both deliver correct MD5: 47BCE5C74F589F4867DBD57E9CA9F808

    public static String getMD5(String filename)
        throws NoSuchAlgorithmException, IOException {
    MessageDigest md = MessageDigest.getInstance("MD5");
    md.update(Files.readAllBytes(Paths.get(filename)));
    byte[] digest = md.digest();
    String myChecksum = DatatypeConverter.printHexBinary(digest).toUpperCase();
    return myChecksum;
}



public static String generateMd5(String pathToFile) throws NoSuchAlgorithmException, IOException {
    MessageDigest md = MessageDigest.getInstance("MD5");
    byte[] hash = md.digest(Files.readAllBytes(Paths.get(pathToFile)));
    return String.valueOf(String.format("%032X", new BigInteger(1, hash)));
}
supernova
  • 1,762
  • 1
  • 14
  • 31
0

I faced this problem before, it is probably an encoding problem (from that file path). I put it like this in my project, and it's working just fine since then. I'll provide you with a sample, so probably you get an idea from this:

public String hash(String stringToHash){
    MessageDigest messageDigest = MessageDigest.getInstance("MD5");
    // here you init the message digit singleton with the wanted algorithm
    messageDigest.update(stringToHash.getBytes());
    //now you updated it, with the bytes of your string
    byte[] digest = messageDigest.digest();
    String result = DatatypeConverter.printHexBinary(digest);
    // finally you converted the result (hex) to String (you hashed string)
    // you may want to use toLowerCase() so you make it case insensitive
    return result;
}

NOTE: you have many way to hash using md5, I really prefer using the Apache Commons as an easy way, you may want to check this out MD5 Hashing using Apache Commons. You also can do that using Google Guava : MD5 Hashing using Google Guava.

Xrio
  • 393
  • 4
  • 15