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); } } } 