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

2
  • Would be helpful to see what the expected answer/result should be … Commented Mar 18, 2020 at 7:12
  • In the picture, you can see the expected output of the program Commented Mar 18, 2020 at 12:31

1 Answer 1

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');  
}  
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.