Java SHA-256 : Hacker Rank Solution : Digit Wood

Java
,

Cryptographic hash functions are mathematical operations run on digital data; by comparing the computed hash (i.e., the output produced by executing a hashing algorithm) to a known and expected hash value, a person can determine the data’s integrity. For example, computing the hash of a downloaded file and comparing the result to a previously published hash result can show whether the download has been modified or tampered with. In addition, cryptographic hash functions are extremely collision-resistant; in other words, it should be extremely difficult to produce the same hash output from two different input values using a cryptographic hash function.

Secure Hash Algorithm 2 (SHA-2) is a set of cryptographic hash functions designed by the National Security Agency (NSA). It consists of six identical hashing algorithms (i.e., SHA-256, SHA-512, SHA-224, SHA-384, SHA-512/224, SHA-512/256) with a variable digest size. SHA-256 is a 256-bit (32 byte) hashing algorithm which can calculate a hash code for an input of up to 264 – 1 bits. It undergoes 64 rounds of hashing and calculates a hash code that is a 64-digit hexadecimal number.

Given a string, s, print its SHA-256 hash value.

Input Format

A single alphanumeric string denoting s.

Sample Input 0

Sample Output 0

Sample Input 1

Sample Output 1

SOLUTION : –

import java.io.*;
import java.util.*;
import java.security.*;
import java.nio.charset.*;

/* Reference: Baeldung: SHA-256 and SHA3-256 */
/* https://www.baeldung.com/sha-256-hashing-java */

public class Solution {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String originalString = sc.nextLine();
        
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] encodedhash = digest.digest(
                originalString.getBytes(StandardCharsets.UTF_8));
            System.out.println(bytesToHex(encodedhash));
        }
        catch (NoSuchAlgorithmException e) {
            System.out.println(e);
        }
    }
    
    private static String bytesToHex(byte[] hash) {
        StringBuilder hexString = new StringBuilder(2 * hash.length);
        for (int i = 0; i < hash.length; i++) {
            String hex = Integer.toHexString(0xff & hash[i]);
            if(hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }
}

FOLLOW FOR MORE QUESTIONS AND SOLUTIONS | DIGIT WOOD

Leave a Reply

Your email address will not be published. Required fields are marked *