1

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

Avishka Dambawinna
  • 1,180
  • 1
  • 13
  • 29

1 Answers1

3

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');  
}  
user207421
  • 305,947
  • 44
  • 307
  • 483
pero_hero
  • 2,881
  • 3
  • 10
  • 24