Syntax
MessageDigest.getInstance("SHA-256").digest(bytes)Examples
SHA-256 Content Digests
Save as Main.java and run with a Java 17+ JDK: java Main.java.
import java.security.MessageDigest;
import java.nio.charset.StandardCharsets;
import java.util.HexFormat;
public class Main {
public static void main(String[] args) throws Exception {
byte[] hash = MessageDigest.getInstance("SHA-256")
.digest("abc".getBytes(StandardCharsets.UTF_8));
System.out.println(HexFormat.of().formatHex(hash));
}
}- Expected output: ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
- SHA-256 returns 32 bytes, displayed here as 64 hexadecimal characters. HexFormat requires Java 17 or newer.
Best practices
- Use a password-specific hashing scheme rather than a raw digest for password storage.
- A plain hash does not authenticate its sender; use an appropriate MAC or signature when required.
Runtime & versions
Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Java Language Specification