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.

JavaSecurity Boundaries

Code

snippet
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

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 =`.