Avishka Dambawinna
Avishka Dambawinna

Reputation: 1215

Java SHA-256 Program provides wrong Hash

I was solving challenges on Hackerrank.com and I met with this challenge about the java SHA-256 Cryptographic hash functions. here

I wrote the following piece of code as a solution. But some test cases are failing for my solution. Hoping to know what's wrong with my code.

public class Solution {
    public static String toHexString(byte[] hash) 
    { 
        BigInteger number = new BigInteger(1, hash);  
        StringBuilder hexString = new StringBuilder(number.toString(16));  

        while (hexString.length() < 32)  
        {  
            hexString.insert(0, '0');  
        }  

        return hexString.toString();  
    } 

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String input = sc.next();
        try 
        { 
            MessageDigest md = MessageDigest.getInstance("SHA-256"); 
            System.out.println(toHexString(md.digest(input.getBytes(StandardCharsets.UTF_8))));
        } 
        // For specifying wrong message digest algorithms  
        catch (NoSuchAlgorithmException e) {  
              throw new RuntimeException(e);
        }  

    }
}

This is one test case that is failing.7

Upvotes: 1

Views: 628

Answers (1)

pero_hero
pero_hero

Reputation: 3204

A 32-byte hash means a string of 64 characters. Each byte contains 2 hex digits, so you need 2 characters per byte:

while (hexString.length() < 64)  
{  
    hexString.insert(0, '0');  
}  

Upvotes: 3

Related Questions