MessageDigest in Java: SHA-256, SHA-512 & MD5 Hashing
A cryptographic hash turns any input into a short fixed-size fingerprint. The same input always gives the same digest, and any change gives a completely different one. Java computes hashes with java.security.MessageDigest.
Contents
What a cryptographic hash is
A hash function turns input of any length into a fixed-size output, the digest. A cryptographic hash adds three guarantees: given a digest, you cannot find an input that produces it (preimage resistance); given an input, you cannot find a second input with the same digest (second-preimage resistance); and you cannot find any two inputs with the same digest (collision resistance). Because of the birthday paradox, a collision in an n-bit hash takes about 2n/2 attempts, so a 256-bit hash gives 128-bit collision security.
SHA-256 and the other SHA-2 functions use the Merkle-Damgard construction: the message is padded, including its length, and split into 512-bit or 1024-bit blocks, and a compression function mixes each block into an internal state. The final state is the digest. A side effect is length extension: anyone who knows SHA-256(secret + message) can compute the hash of a longer message without knowing the secret, which is why hash(secret + data)
| Algorithm | Output | In the JDK since | Status |
|---|---|---|---|
| MD5 | 128 bits | 1.1 | Broken: collisions can be produced in seconds. Only for non-security checksums |
| SHA-1 | 160 bits | 1.1 | Broken for collisions (2017); do not use for signatures or certificates |
| SHA-256, SHA-384, SHA-512 | 256 to 512 bits | 1.4 | Secure; SHA-256 is the common default |
| SHA-224, SHA-512/224, SHA-512/256 | 224, 256 bits | 8 (SHA-224), 9 | Secure; truncated variants |
| SHA3-224 to SHA3-512 | 224 to 512 bits | 9 (JEP 287) | Secure; the sponge design |
MessageDigestgetInstanceSUN
Computing digests
MessageDigest.getInstance(name)digest(bytes)HexFormat
The program hashes the string "abc" because the standards that define these algorithms publish its expected digests as test vectors. A match proves the code (and the JDK) computes the real algorithm, not just something that looks like a hash. It then changes one letter, and feeds the input in two pieces.
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HexFormat;
public class Digests {
static String hex(String algorithm, byte[] input) throws NoSuchAlgorithmException {
return HexFormat.of().formatHex(MessageDigest.getInstance(algorithm).digest(input));
}
public static void main(String[] args) throws Exception {
byte[] abc = "abc".getBytes(StandardCharsets.UTF_8);
// Published test vectors for the input "abc" (FIPS 180 / RFC 1321 / FIPS 202)
String[][] known = {
{"MD5", "900150983cd24fb0d6963f7d28e17f72"},
{"SHA-1", "a9993e364706816aba3e25717850c26c9cd0d89d"},
{"SHA-256", "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"},
{"SHA3-256", "3a985da74fe225b2045c172d6bd390bd855f086e3e9d525b46bfe24511431532"},
};
for (String[] k : known) {
String actual = hex(k[0], abc);
System.out.printf("%-8s %3d bits matches test vector: %b%n", k[0],
actual.length() * 4, actual.equals(k[1]));
}
System.out.println("SHA-256(\"abc\") = " + hex("SHA-256", abc));
// Avalanche effect: one changed letter flips about half of the output bits
byte[] h1 = MessageDigest.getInstance("SHA-256").digest(abc);
byte[] h2 = MessageDigest.getInstance("SHA-256").digest(
"abd".getBytes(StandardCharsets.UTF_8));
int differentBits = 0;
for (int i = 0; i < h1.length; i++) {
differentBits += Integer.bitCount((h1[i] ^ h2[i]) & 0xFF);
}
System.out.println("\"abc\" vs \"abd\": " + differentBits + " of 256 bits differ");
// Feeding the input in pieces gives the same result as one call
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update("a".getBytes(StandardCharsets.UTF_8));
md.update("bc".getBytes(StandardCharsets.UTF_8));
System.out.println("incremental update equals one-shot: "
+ HexFormat.of().formatHex(md.digest()).equals(hex("SHA-256", abc)));
// Comparing digests: use the constant-time method
System.out.println("MessageDigest.isEqual(h1, h1.clone()): "
+ MessageDigest.isEqual(h1, h1.clone()));
}
}
Output:
MD5 128 bits matches test vector: true
SHA-1 160 bits matches test vector: true
SHA-256 256 bits matches test vector: true
SHA3-256 256 bits matches test vector: true
SHA-256("abc") = ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
"abc" vs "abd": 122 of 256 bits differ
incremental update equals one-shot: true
MessageDigest.isEqual(h1, h1.clone()): true
- All four algorithms match their published vectors. The output size is fixed per algorithm, whatever the input size.
- Changing
to"abc" changed 122 of the 256 bits, close to the half you expect from a good hash (the avalanche effect). Similar inputs give unrelated digests, so a digest reveals nothing about how close two inputs are."abd" can be called many times beforeupdate ; the result equals hashing everything at once. This is how large inputs are hashed in chunks.digest- Compare digests with
, which takes the same time whatever the content.MessageDigest.isEqual stops at the first difference, which can leak information through timing when the digest acts as a secret, as with MACs.Arrays.equals
Providers, running hashes and reset
A MessageDigestdigest()
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import java.util.HexFormat;
import java.util.TreeSet;
public class Algorithms {
public static void main(String[] args) throws Exception {
// Every MessageDigest algorithm the installed providers offer
System.out.println("available: " + new TreeSet<>(Security.getAlgorithms("MessageDigest")));
MessageDigest sha = MessageDigest.getInstance("SHA-256");
System.out.println("SHA-256 comes from provider " + sha.getProvider().getName()
+ ", digest length " + sha.getDigestLength() + " bytes");
try {
MessageDigest.getInstance("SHA-257");
} catch (NoSuchAlgorithmException e) {
System.out.println("unknown name: " + e.getMessage());
}
// clone() keeps the state, so a running hash can be read without ending it
HexFormat hex = HexFormat.of();
MessageDigest running = MessageDigest.getInstance("SHA-256");
String[] chunks = {"first chunk;", "second chunk;", "third chunk;"};
for (String c : chunks) {
running.update(c.getBytes(StandardCharsets.UTF_8));
MessageDigest snapshot = (MessageDigest) running.clone();
System.out.println("after \"" + c + "\" -> " + hex.formatHex(snapshot.digest())
.substring(0, 16) + "...");
}
// digest() resets the object: a second call hashes the empty input
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update("abc".getBytes(StandardCharsets.UTF_8));
String first = hex.formatHex(md.digest());
String second = hex.formatHex(md.digest());
System.out.println("first digest() " + first.substring(0, 16) + "... (\"abc\")");
System.out.println("second digest() " + second.substring(0, 16)
+ "... (empty input: e3b0c442... is SHA-256 of nothing)");
// Truncated SHA-512 variants have their own initial values
String t = hex.formatHex(MessageDigest.getInstance("SHA-512/256")
.digest("abc".getBytes(StandardCharsets.UTF_8)));
String cut = hex.formatHex(MessageDigest.getInstance("SHA-512")
.digest("abc".getBytes(StandardCharsets.UTF_8))).substring(0, 64);
System.out.println("SHA-512/256 equals the first 256 bits of SHA-512: " + t.equals(cut));
}
}
Output:
available: [MD2, MD5, SHA-1, SHA-224, SHA-256, SHA-384, SHA-512, SHA-512/224, SHA-512/256, SHA3-224, SHA3-256, SHA3-384, SHA3-512]
SHA-256 comes from provider SUN, digest length 32 bytes
unknown name: SHA-257 MessageDigest not available
after "first chunk;" -> d0f96795265a877a...
after "second chunk;" -> 82801163f23eed1a...
after "third chunk;" -> 8d775a9ea58eabf5...
first digest() ba7816bf8f01cfea... ("abc")
second digest() e3b0c44298fc1c14... (empty input: e3b0c442... is SHA-256 of nothing)
SHA-512/256 equals the first 256 bits of SHA-512: false
listed 13 names, including the obsolete MD2. A misspelled name throwsSecurity.getAlgorithms("MessageDigest") , a checked exception, so algorithm names are best kept in constants.NoSuchAlgorithmException copied the running state, so the program could print the digest so far after each chunk while the original continued. This is how a log or stream can publish intermediate checksums.clone() finishes the hash and resets the object. The second call returneddigest() , the well-known SHA-256 of zero bytes. Seeing that value in a log almost always means a digest was read twice, or an empty input was hashed by mistake.e3b0c442...- SHA-512/256 is not simply the first half of SHA-512: it starts from different initial values, so the outputs differ. The truncated variants run at SHA-512's speed while producing a SHA-256-sized digest.
Encoding traps
A digest is computed over bytes, and most hashing bugs are about how text becomes bytes or how bytes become text. The program uses "café", whose é
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Base64;
import java.util.HexFormat;
public class EncodingTraps {
public static void main(String[] args) throws Exception {
MessageDigest md = MessageDigest.getInstance("SHA-256");
HexFormat hex = HexFormat.of();
// 1. A string has no hash; its bytes do, and the bytes depend on the charset
String word = "café";
byte[] utf8 = word.getBytes(StandardCharsets.UTF_8);
byte[] latin1 = word.getBytes(StandardCharsets.ISO_8859_1);
System.out.println("\"café\" as UTF-8: " + utf8.length + " bytes, SHA-256 "
+ hex.formatHex(md.digest(utf8)).substring(0, 16) + "...");
System.out.println("\"café\" as ISO-8859-1: " + latin1.length + " bytes, SHA-256 "
+ hex.formatHex(md.digest(latin1)).substring(0, 16) + "...");
// 2. Different text encodings of the same digest
byte[] d = md.digest("abc".getBytes(StandardCharsets.UTF_8));
System.out.println("hex: " + hex.formatHex(d) + " (" + hex.formatHex(d)
.length() + " chars)");
System.out.println("Base64: " + Base64.getEncoder().encodeToString(d) + " ("
+ Base64.getEncoder().encodeToString(d).length() + " chars)");
// 3. The BigInteger shortcut drops leading zeros
int i = 0;
byte[] h;
do { // find an input whose digest starts with 0
h = md.digest(("message " + i++).getBytes(StandardCharsets.UTF_8));
} while ((h[0] & 0xF0) != 0);
String viaBigInteger = new BigInteger(1, h).toString(16);
System.out.println("\"message " + (i - 1) + "\" HexFormat: " + hex.formatHex(h));
System.out.println("\"message " + (i - 1) + "\" BigInteger: " + viaBigInteger + " ("
+ viaBigInteger.length() + " chars)");
// 4. Hashing concatenated fields is ambiguous without separators
String a = hex.formatHex(md.digest(("ab" + "c").getBytes(StandardCharsets.UTF_8)));
String b = hex.formatHex(md.digest(("a" + "bc").getBytes(StandardCharsets.UTF_8)));
System.out.println("hash(\"ab\"+\"c\") == hash(\"a\"+\"bc\"): " + a.equals(b));
}
}
Output:
"café" as UTF-8: 5 bytes, SHA-256 850f7dc43910ff89...
"café" as ISO-8859-1: 4 bytes, SHA-256 dafd66c0b98965e6...
hex: ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad (64 chars)
Base64: ungWv48Bz+pBQUDeXa4iI7ADYaOWF3qctBD/YfIAFa0= (44 chars)
"message 35" HexFormat: 006c08439391f6ddc40844a41eb8faf8051e94e463c67fe4df744391115b1330
"message 35" BigInteger: 6c08439391f6ddc40844a41eb8faf8051e94e463c67fe4df744391115b1330 (62 chars)
hash("ab"+"c") == hash("a"+"bc"): true
- "café" is 5 bytes in UTF-8 and 4 in ISO-8859-1, so the two digests have nothing in common. A server and a client that hash "the same string" with different default charsets will never agree; always pass the charset to
.getBytes - The same 32-byte digest is 64 characters in hex and 44 in Base64. Both are fine, but the two sides must agree on one.
, a common snippet, dropped the leading zeros of "message 35"'s digest and returned 62 characters instead of 64. Comparisons with a correct 64-character checksum then fail about once in 16 inputs.new BigInteger(1, hash).toString(16) (Java 17) always writes two characters per byte.HexFormat- Hashing
and"ab" + "c" gave the same digest, because both are the bytes "abc". When hashing several fields, add a separator that cannot appear in them, or prefix each field with its length."a" + "bc"
File checksums
To verify a download, compute its SHA-256 and compare it with the checksum the publisher lists. DigestInputStream
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.util.HexFormat;
import java.util.Random;
public class FileChecksum {
public static void main(String[] args) throws Exception {
Path file = Files.createTempFile("download", ".bin");
byte[] data = new byte[5000000];
new Random(1).nextBytes(data);
Files.write(file, data);
// Stream the file through the digest instead of loading it whole
MessageDigest md = MessageDigest.getInstance("SHA-256");
try (InputStream in = new DigestInputStream(Files.newInputStream(file), md)) {
in.transferTo(OutputStream.nullOutputStream());
}
String streamed = HexFormat.of().formatHex(md.digest());
String whole = HexFormat.of().formatHex(
MessageDigest.getInstance("SHA-256").digest(Files.readAllBytes(file)));
System.out.println("streamed digest equals in-memory digest: " + streamed.equals(whole));
// A published checksum detects any change, even one bit
String published = streamed;
data[2500000] ^= 1;
Files.write(file, data);
String after = HexFormat.of().formatHex(
MessageDigest.getInstance("SHA-256").digest(Files.readAllBytes(file)));
System.out.println("after flipping 1 bit, still matches: " + after.equals(published));
System.out.println("first 16 hex digits before/after: " + published.substring(0, 16)
+ " / " + after.substring(0, 16));
// Speed: why plain SHA-256 must not be used for passwords
MessageDigest fast = MessageDigest.getInstance("SHA-256");
byte[] pw = "correct horse".getBytes(StandardCharsets.UTF_8);
long start = System.nanoTime();
int n = 1000000;
for (int i = 0; i < n; i++) {
fast.digest(pw);
}
double seconds = (System.nanoTime() - start) / 1e9;
System.out.println("more than 500,000 password guesses per second on one core: "
+ (n / seconds > 500000));
Files.delete(file);
}
}
Output:
streamed digest equals in-memory digest: true
after flipping 1 bit, still matches: false
first 16 hex digits before/after: 093887a60f07e0c3 / 6597cf99a6db17ac
more than 500,000 password guesses per second on one core: true
- The streamed and the in-memory digest are the same.
- One changed bit out of 40 million produces a completely different checksum, so corruption or tampering is detected. Note that a checksum only helps if it comes from a trusted source; an attacker who can change the file can usually change a checksum next to it, which is why signatures (see
RSA signatures ) orHMAC are used when authenticity matters. - SHA-256 is designed to be fast: this one core computed well over half a million hashes per second, and GPUs manage billions. That is ideal for checksums but terrible for passwords, because it makes guessing fast too. Store passwords with a slow, salted function such as PBKDF2, bcrypt or Argon2; see
SecureRandom and PBKDF2 .
MessageDigestgetInstance
How fast is each algorithm?
Hash speed matters for checksums of large files and for deduplication. The program hashes 64 MB of random bytes with five algorithms, one warm-up round and then the best of 3 rounds, and counts how many small SHA-256 hashes one core computes in half a second. This is a rough comparison on a 2-CPU Linux virtual machine with JDK 21 whose processor has the SHA instruction set extensions.
import java.security.MessageDigest;
import java.util.Random;
public class DigestSpeed {
public static void main(String[] args) throws Exception {
byte[] data = new byte[64 * 1024 * 1024];
new Random(42).nextBytes(data);
String[] algorithms = {"MD5", "SHA-1", "SHA-256", "SHA-512", "SHA3-256"};
long[] best = new long[algorithms.length];
java.util.Arrays.fill(best, Long.MAX_VALUE);
for (int round = 0; round < 4; round++) { // round 0 is a warm-up
for (int i = 0; i < algorithms.length; i++) {
MessageDigest md = MessageDigest.getInstance(algorithms[i]);
long t0 = System.nanoTime();
md.digest(data);
long t = System.nanoTime() - t0;
if (round > 0) {
best[i] = Math.min(best[i], t);
}
}
}
System.out.println("hashing 64 MB of random data, best of 3 rounds:");
for (int i = 0; i < algorithms.length; i++) {
System.out.printf(" %-8s %5.0f MB/s%n", algorithms[i], 64 / (best[i] / 1e9));
}
// Small inputs: how many SHA-256 hashes of a 16-byte value per second
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] small = new byte[16];
long count = 0;
long end = System.nanoTime() + 500000000L;
while (System.nanoTime() < end) {
small[0]++;
md.digest(small);
count++;
}
System.out.printf("SHA-256 of 16-byte inputs: about %,d per second on one core%n",
count * 2 / 100000 * 100000);
}
}
Output of the hashing speed run:
hashing 64 MB of random data, best of 3 rounds:
MD5 720 MB/s
SHA-1 1141 MB/s
SHA-256 1111 MB/s
SHA-512 635 MB/s
SHA3-256 369 MB/s
SHA-256 of 16-byte inputs: about 8,500,000 per second on one core
- SHA-1 and SHA-256 ran at close to a gigabyte per second, faster than MD5. HotSpot replaces their compression functions with intrinsics that use the processor's SHA instructions, so on this machine there is no speed reason left to choose MD5. Without those instructions, SHA-512 is usually faster than SHA-256 on 64-bit processors, because it processes 128-byte blocks with 64-bit arithmetic.
- SHA3-256 was the slowest, well under half of SHA-256's speed here. It is a sound choice when a design calls for SHA-3, not a faster one.
- Millions of small hashes per second on one core is exactly why a plain hash must not store passwords: an attacker guessing passwords gets the same speed, and a GPU is far faster. Password hashing is covered on the
SecureRandom and PBKDF2 page .
Which digest to use
| Situation | Use |
|---|---|
| File checksums, content addressing, deduplication | SHA-256 |
| Interoperating with an existing format | Whatever it specifies, even MD5 or SHA-1, but never for security decisions |
| A design that requires SHA-3, or protection from length extension | SHA3-256 |
| Proving who created data, or that it was not altered by an attacker | |
| Passwords | PBKDF2, bcrypt or Argon2, never a plain digest |
| Hash tables and non-security checks | hashCode() |
Whatever the algorithm: hash bytes with an explicit charset, print with HexFormatMessageDigest.isEqual