Cluxter - 2014-12-11

The GetTextHash() function is:

public String GetTextHash(String text, String algorithm){
    try {
        MessageDigest md = MessageDigest.getInstance(algorithm);
        byte[] messageDigest = md.digest(text.getBytes());
        BigInteger number = new BigInteger(1, messageDigest);
        return number.toString(16);
    }
    catch(NoSuchAlgorithmException e){}
    return "";
}

The parameter given to the .toString() method defines the radix, here 16 since we want an hexadecimal representation.

However this method has no clue about how many numbers it should consider. As we know integer numbers never have useless zeros at their beginning (this is precisely the difference with strings). Consequently if the hash begins with one or several zeros, they won't be converted to text and they will be missing in the string.

Solution: we should define for each algorithm the number of characters expected for the hash this algorithm will return (example: 32 characters for MD5). Then instead of returning "number.toString(16)", we should check and add the number of missing zeros at the beginning of the string to reach the expected length.

Be aware that we face the same problem with the GetFileHash() function:

public String GetFileHash(String filename, String algorithm){
    try {
        MessageDigest digest = MessageDigest.getInstance(algorithm);
        InputStream is = new FileInputStream(new File(filename));
        byte[] buffer = new byte[8192];
        int read = 0;
        String output = null;
        try {
             while( (read = is.read(buffer)) > 0){
                 digest.update(buffer, 0, read);
             }
             byte[] md5sum = digest.digest();
             BigInteger bigInt = new BigInteger(1, md5sum);
             output = bigInt.toString(16);
        }
        catch(IOException e) {
            throw new RuntimeException("Não foi possivel processar o arquivo.", e);
        }
        finally {
            try {
                is.close();
            }
            catch(IOException e) {
                throw new RuntimeException("Não foi possivel fechar o arquivo", e);
            }
        }
    return output;
    }
    catch(FileNotFoundException e ){}
    catch(NoSuchAlgorithmException e){}
    return "";
}

I've never coded in Java nor in oriented object paradigm so I will let someone else write the right code for the time being.