DigestInputStream Hashes While Reading
Wrap an InputStream in DigestInputStream so every chunk read feeds the MessageDigest, and confirm the streaming digest equals a one-shot update.
Code
import java.io.ByteArrayInputStream;
import java.io.DigestInputStream;
import java.security.MessageDigest;
import java.util.HexFormat;
public class StreamingDigest {
public static void main(String[] args) throws Exception {
// 包装输入流:流经的字节同步喂给 MessageDigest,读完即可取摘要
MessageDigest streaming = MessageDigest.getInstance("SHA-256");
try (DigestInputStream in = new DigestInputStream(
new ByteArrayInputStream("payload-to-hash".getBytes()), streaming)) {
byte[] chunk = new byte[4];
while (in.read(chunk) != -1) {
// 数据消费与哈希累积同一次读循环完成
}
}
System.out.println("streaming = " + HexFormat.of().formatHex(streaming.digest()));
// 对照:对同一字节序列一次性 update + digest
MessageDigest direct = MessageDigest.getInstance("SHA-256");
direct.update("payload-to-hash".getBytes());
System.out.println("direct = " + HexFormat.of().formatHex(direct.digest()));
}
}How it works
Everything happens inside the class StreamingDigest.
Iteration happens inside while (in.read(chunk) != -1) — everything outside it runs once. Resources are declared in a try-with-resources header, so they close on every exit path without a finally block.
Points of care
- It runs on exactly what the toolchain already ships — nothing extra.
Putting it to use
The demo output is labeled (streaming =, direct =), so the output doubles as a step-by-step trace of what the file did.
The core lines of the flow
MessageDigest streaming = MessageDigest.getInstance("SHA-256");
MessageDigest direct = MessageDigest.getInstance("SHA-256");
direct.update("payload-to-hash".getBytes());
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.HMAC GeneratorCompute an HMAC-SHA-256, SHA-384, or SHA-512 signature for a message and key using the Web Crypto API, with hex and Base64 output.
FAQ
- What does DigestInputStream Hashes While Reading print when run?
- Run it as a complete program — the output lines carry labels such as `streaming =`, `direct =`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.