java 36 lines · 7 steps

Streaming a SHA-256 file checksum in Java

Compute a file's SHA-256 hash by feeding its bytes through a DigestInputStream, then render the result as hex.

Explained by highlit
1public final class FileChecksum {
2 
3 private static final char[] HEX = "0123456789abcdef".toCharArray();
4 
5 private FileChecksum() {
6 }
7 
8 public static String sha256(Path file) throws IOException {
9 MessageDigest digest;
10 try {
11 digest = MessageDigest.getInstance("SHA-256");
12 } catch (NoSuchAlgorithmException e) {
13 throw new IllegalStateException("SHA-256 not available", e);
14 }
15 
16 try (InputStream in = Files.newInputStream(file);
17 DigestInputStream dis = new DigestInputStream(in, digest)) {
18 byte[] buffer = new byte[8192];
19 while (dis.read(buffer) != -1) {
20 // draining the stream feeds the digest
21 }
22 }
23 
24 return toHex(digest.digest());
25 }
26 
27 private static String toHex(byte[] bytes) {
28 char[] out = new char[bytes.length * 2];
29 for (int i = 0; i < bytes.length; i++) {
30 int b = bytes[i] & 0xff;
31 out[i * 2] = HEX[b >>> 4];
32 out[i * 2 + 1] = HEX[b & 0x0f];
33 }
34 return new String(out);
35 }
36}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1DigestInputStream lets you hash data as you read it, avoiding loading the whole file into memory.
  2. 2Try-with-resources guarantees the stream closes even when reading throws.
  3. 3Bytes must be masked with 0xff before hex conversion because Java bytes are signed.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Streaming a SHA-256 file checksum in Java — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code