HackerRank Java- SHA-256
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.
Given a string, s, print its SHA-256 hash value.
- import java.util.Scanner;
- import java.security.MessageDigest;
- import java.security.NoSuchAlgorithmException;
-
- public class Solution {
- public static void main(String[] args) throws NoSuchAlgorithmException {
-
- Scanner scan = new Scanner(System.in);
- String str = scan.next();
- scan.close();
-
- /* Encode the String using SHA-256 */
- MessageDigest md = MessageDigest.getInstance("SHA-256");
- md.update(str.getBytes());
- byte[] digest = md.digest();
-
- /* Print the encoded value in hexadecimal */
- for (byte b : digest) {
- System.out.format("%02x", b);
- }
- }
- }