S H A256 HackerRank Solution

In the realm of data security, hashing is a crucial technique. It transforms an input (or 'message') into a fixed-size string of bytes, which typically looks like a random sequence of characters. The 'message' can be of any length but the 'hash' has a fixed length. This program is about generating the SHA-256 hash, a specific type of hash, of a given string in Java.

Secure your next interview 🎯

CodeRankGPT is a tool powered by GPT-4 that quietly assists you during your coding interview, providing the solutions you need.
In real-time and absolutely undetectable 🥷

Here is the S H A256 HackerRank Solution HackerRank solution using CodeRankGPT:

The program uses Java's built-in MessageDigest class to generate the SHA-256 hash. It first reads a string from the user. Then, it calls the getSHAHEX method, which creates an instance of MessageDigest with the SHA-256 algorithm. The method then converts the string into bytes and feeds it to the digest. The digest, in turn, generates the hash. The hash is a byte array, so the method converts each byte into a hexadecimal string and appends them together to form the final hash string. If any hexadecimal string is of length 1, it prepends a '0' to it to ensure that every byte is represented by two hexadecimal characters.


/**
 * 
 */
package com.javaaid.hackerrank.solutions.languages.java.advanced;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Scanner;

/**
 *
 */
public class JavaSHA256 {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String s = sc.next();
		System.out.println(getSHAHEX(s));
		sc.close();
	}

	private static String getSHAHEX(String s) {
		StringBuffer sb = new StringBuffer();
		try {
			MessageDigest digest = MessageDigest.getInstance("SHA-256");
			byte[] result = digest.digest(s.getBytes());
			for (int i = 0; i < result.length; i++) {
				String hex = Integer.toHexString(0xff & result[i]);
				if (hex.length() == 1)
					sb.append('0');
				sb.append(hex);
			}

		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}

		return sb.toString();
	}

}

If you have a HackerRank coding test coming up, you can use CodeRankGPT to your advantage. It will assist you during your interview and help ensure you get the job.

AI is here now, and other candidates might be using it to get ahead and win the job. 🧐

Built on Unicorn Platform