Search code examples
javastringsubstringshasha512

Java SHA-512 function only producing a 508 bit output?


I have a data points that I loop through and hash. I am using a Java implementation of the SHA-512 to hash my data. The hash should produce a 128 character string, but occasionally it will produce a 127 character string that results in my code having out of bounds exceptions.

The code usually produces an incorrect length hash 1 out of every 20 different hashes calculated.

This is the code I am using to implement the hash, which is from https://www.geeksforgeeks.org/sha-512-hash-in-java/

public static String SHA512(String input) 
{ 
    try { 
        // getInstance() method is called with algorithm SHA-512 
        MessageDigest md = MessageDigest.getInstance("SHA-512"); 

        // digest() method is called 
        // to calculate message digest of the input string 
        // returned as array of byte 
        byte[] messageDigest = md.digest(input.getBytes()); 

        // Convert byte array into signum representation 
        BigInteger no = new BigInteger(1, messageDigest); 

        // Convert message digest into hex value 
        String hashtext = no.toString(16); 

        // Add preceding 0s to make it 32 bit 
        while (hashtext.length() < 32) { 
            hashtext = "0" + hashtext; 
        } 

        // return the HashText 
        return hashtext; 
    } 

    // For specifying wrong message digest algorithms 
    catch (NoSuchAlgorithmException e) { 
        throw new RuntimeException(e); 
    } 
} 

Here is a hash of correct length (128 char) produced by the code listed above: ca36f8a40a6211d49e77f84ca37182813fba853fba732e29d18414c739b85f856fd3af702a2cd23174eeaedf2d99a044b0ae0ddea17de7bbb33e3b62cfec5236

Here is a hash of incorrect length (127 char) produced by the code listed above: d2d3cb7a7f60a0fd673c86fb82eb515c4f2f40f0308df7b3c838b78c510125967191ad9afe0e4f8e5fb59ed190bc6652d3e4805c886fc1e62213a3284cca661


Solution

  • Changing the while loop condition from < 32 to < 128 fixes it. It makes sense because the code should produce a 128 hex digit string (512 bits), not a 32 hex digit string (128 bits). It seems that it may be an error listed in the OP's code.