How to hash some String with SHA-256 in Java?

How to hash some String with SHA-256 in Java?

You can hash a string with SHA-256 in Java using the MessageDigest class from the Java Security package. Here's how you can do it:

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

In this example:

  1. We specify the input string that we want to hash (inputString).

  2. We create a MessageDigest instance using the SHA-256 algorithm by calling MessageDigest.getInstance("SHA-256").

  3. We convert the input string to bytes using UTF-8 encoding (inputString.getBytes(StandardCharsets.UTF_8)).

  4. We calculate the SHA-256 hash by calling digest.digest(inputBytes) on the MessageDigest instance.

  5. We convert the resulting hash bytes to a hexadecimal representation, which is a common way to represent hashes. The loop iterates through each byte, converts it to a hexadecimal string, and appends it to a StringBuilder.

  6. Finally, we print the SHA-256 hash.

When you run this code, it will calculate the SHA-256 hash of the input string and display the hexadecimal representation of the hash.


More Tags

slide zip4j webrequest pca access-denied reportviewer pattern-matching whatsapi android-proguard merge

More Java Questions

More General chemistry Calculators

More Mortgage and Real Estate Calculators

More Investment Calculators

More Animal pregnancy Calculators