CKTIS / Java
MessageDigest — computing and comparing hashes
MessageDigest computes one-way hashes of data. Learn how to select SHA-256, process bytes, understand the reset after digest, and compare results with isEqual.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] hash = md.digest(input);
boolean equal = MessageDigest.isEqual(hash, expected);MessageDigest in java.security computes a one-way hash of bytes rather than encrypting data. SHA-256 returns 256 bits, or 32 bytes. Hexadecimal text is only a representation of the result; explicitly select an encoding such as StandardCharsets.UTF_8 when converting text to bytes.
MessageDigest.getInstance("SHA-256") obtains an implementation from a cryptographic service provider. An unsupported requested algorithm causes NoSuchAlgorithmException; Java SE 21 requires SHA-256 support.
The instance call md.digest(input) adds input to any data already accumulated and completes the computation. For chunked processing, call update(...) followed by digest(). Completing the computation resets the object to its initial state: the next call does not continue the previous message.
MessageDigest.isEqual(a, b) compares digest lengths and contents. Do not replace it with ==, which compares array references. Do not treat this method as an unconditional constant-time guarantee for every argument and environment. A hash alone does not authenticate a sender and is not encryption.
This documentation covers Java SE 21, the repository runtime. The production runtime has not been attested.
Examples
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HexFormat;
public class DigestExample {
public static void main(String[] args) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] actual = md.digest("abc".getBytes(StandardCharsets.UTF_8));
byte[] expected = HexFormat.of().parseHex(
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad");
System.out.println(HexFormat.of().formatHex(actual));
System.out.println(MessageDigest.isEqual(actual, expected));
}
}Result
ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad true
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.