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

To hash a string using SHA-256 in Java, you can use the MessageDigest class from the java.security package.

Here's an example of how you can hash a string using SHA-256 in Java:

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Main {
  public static void main(String[] args) {
    String input = "Hello, world!";

    // get an instance of the SHA-256 message digest algorithm
    MessageDigest md = MessageDigest.getInstance("SHA-256");

    // compute the hash of the input string
    byte[] hash = md.digest(input.getBytes());

    // convert the hash to a hexadecimal string
    StringBuilder hexString = new StringBuilder();
    for (byte b : hash) {
      hexString.append(String.format("%02x", b));
    }

    // print the hash
    System.out.println(hexString);
  }
}

This code gets an instance of the SHA-256 message digest algorithm using the getInstance method. It then uses the digest method to compute the hash of the input string, and converts the hash to a hexadecimal string using a StringBuilder object. Finally, it prints the hash to the console.

Note that the digest method returns a byte array, so you will need to convert the hash to a more readable format (such as a hexadecimal string) if you want to print it or compare it with other hashes.