Java SHA-256 Program not working properly

Avishka Kavindu B. Dambawinna :

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.

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
import java.security.MessageDigest;  
import java.security.NoSuchAlgorithmException;  
import java.nio.charset.StandardCharsets;
import java.math.BigInteger;

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

pero_hero :

a 32 byte hash means a string of 64 characters as for any byte you need 2 characters:

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=300235&siteId=1