Video in progress
How do you compute the SHA-256 hash of a multi-gigabyte file without filling memory?
You read the file in chunks and feed each chunk to MessageDigest.update, or wrap the stream in a DigestInputStream and read to the end. Memory holds only the buffer and the digest state. You turn the result into text with HexFormat (Java 17).
📖 Answer
Files.readAllBytes + digest(bytes) works on a small file, but not on a 4 GB archive. A digest is a streaming algorithm itself and doesn't need the whole file:
static String sha256(Path file) throws IOException, NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-256");
try (InputStream in = new DigestInputStream(Files.newInputStream(file), md)) {
in.transferTo(OutputStream.nullOutputStream()); // Java 11+
}
return HexFormat.of().formatHex(md.digest());
}
The most useful part is computing the hash while the data is passing through, without a separate read. For example, while writing an uploaded file to storage:
try (var in = new DigestInputStream(upload.getInputStream(), md)) {
Files.copy(in, target);
}
String hash = HexFormat.of().formatHex(md.digest());
That way you don't read the file twice.
Three more points:
MessageDigestis not thread-safe; take a new instance for each computation;- to detect corruption quickly (network, disk),
CRC32Cis enough and much faster; if you need protection against deliberate tampering, use SHA-256; - if you just need to compare two files,
Files.mismatch(a, b)in Java 12+ returns the offset of the first differing byte (or-1), so no hash is needed.
Sign up to mark studied questions and save your progress.