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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1DigestInputStream lets you hash data as you read it, avoiding loading the whole file into memory.
- 2Try-with-resources guarantees the stream closes even when reading throws.
- 3Bytes must be masked with 0xff before hex conversion because Java bytes are signed.
Related explainers
java
@Component @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
ruby
class LogAggregator BUCKET_FORMAT = "%Y-%m-%dT%H:%M" def initialize(entries)
Bucketing log entries by the minute in Ruby
aggregation
hashing
enumerable
Intermediate
5 steps
java
package com.acme.billing.config; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties;
Feature-flagged beans with Spring @ConditionalOnProperty
feature-flags
conditional-beans
strategy-pattern
Intermediate
5 steps
java
public static Map<String, String> parseCookieHeader(String header) { Map<String, String> cookies = new LinkedHashMap<>(); if (header == null || header.isBlank()) { return cookies;
Parsing an HTTP Cookie header in Java
string-parsing
http
url-decoding
Intermediate
6 steps
ruby
class ApplicationController < ActionController::Base EXPERIMENTS = { checkout_button_color: %w[control blue green], onboarding_flow: %w[control streamlined]
How A/B test cohorts are assigned in Rails
a-b-testing
cookies
hashing
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/streaming-a-sha-256-file-checksum-in-java-explained-java-5db4/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.