MessageDigest SHA-256 HexFormat
Hash strings with MessageDigest SHA-256, render bytes with HexFormat, and compare digests with constant-time MessageDigest.isEqual.
Code
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HexFormat;
public class ArtifactFingerprint {
public static void main(String[] args) throws NoSuchAlgorithmException {
MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
HexFormat hex = HexFormat.of();
byte[] first = sha256.digest("release-2026-11-11".getBytes(StandardCharsets.UTF_8));
System.out.println("fingerprint: " + hex.formatHex(first));
// 同一输入摘要稳定:可用于校验下载产物
byte[] again = sha256.digest("release-2026-11-11".getBytes(StandardCharsets.UTF_8));
System.out.println("stable: " + MessageDigest.isEqual(first, again));
// 一个字符不同,摘要完全不同
byte[] tampered = sha256.digest("release-2026-11-12".getBytes(StandardCharsets.UTF_8));
System.out.println("tampered differs: " + !MessageDigest.isEqual(first, tampered));
}
}How the snippet works
The working surface is the class ArtifactFingerprint — everything else is wiring.
Applying it
The demo output is labeled (fingerprint:, stable:, tampered differs:), so every printed line maps back to its originating operation.
Statements that matter
byte[] tampered = sha256.digest("release-2026-11-12".getBytes(StandardCharsets.UTF_8));
byte[] first = sha256.digest("release-2026-11-11".getBytes(StandardCharsets.UTF_8));
byte[] again = sha256.digest("release-2026-11-11".getBytes(StandardCharsets.UTF_8));
Interactive Tools for This Topic
bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.SHA-256 Hash GeneratorGenerate SHA-256 cryptographic hashes from text input using the Web Crypto API. Compare hashes and verify data integrity with hexadecimal digest output.
FAQ
- What does MessageDigest SHA-256 HexFormat print when run?
- Invoke the file as-is — the `fingerprint:`, `stable:`, `tampered differs:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.