Hash String via SHA-256 in Java

Hash String via SHA-256 in Java

You can hash a string using the SHA-256 algorithm in Java using the java.security.MessageDigest class. Here's an example of how to do it:

import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class SHA256Example { public static void main(String[] args) { String inputString = "Hello, World!"; try { // Create a MessageDigest instance for SHA-256 MessageDigest digest = MessageDigest.getInstance("SHA-256"); // Get the bytes of the input string byte[] inputBytes = inputString.getBytes(); // Update the digest with the input bytes byte[] hashBytes = digest.digest(inputBytes); // Convert the hash bytes to a hexadecimal string StringBuilder hexString = new StringBuilder(); for (byte b : hashBytes) { String hex = Integer.toHexString(0xff & b); if (hex.length() == 1) { hexString.append('0'); } hexString.append(hex); } String sha256Hash = hexString.toString(); System.out.println("SHA-256 Hash: " + sha256Hash); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } } 

In this example:

  1. We create an instance of the MessageDigest class with the SHA-256 algorithm using MessageDigest.getInstance("SHA-256").

  2. We convert the input string "Hello, World!" into bytes using inputString.getBytes().

  3. We update the digest object with the input bytes using digest.digest(inputBytes).

  4. We convert the resulting hash bytes to a hexadecimal string for easy display.

  5. The SHA-256 hash is printed to the console.

Make sure to handle the NoSuchAlgorithmException that can be thrown when requesting the SHA-256 algorithm.


More Tags

xcopy android-shape comparator apache-commons-config android-ndk razor-2 kubernetes-helm android-bitmap code-first infix-notation

More Java Questions

More Trees & Forestry Calculators

More Electrochemistry Calculators

More Tax and Salary Calculators

More Biology Calculators