CheckedInputStream With Adler32 Checksum
Compute and verify rolling Adler32 checksums in-flight with CheckedOutputStream and CheckedInputStream, catching single-bit stream tampering.
Code
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.zip.Adler32;
import java.util.zip.CheckedInputStream;
import java.util.zip.CheckedOutputStream;
public class StreamChecksumGuard {
static long computeOnRead(byte[] payload) throws IOException {
try (CheckedInputStream in = new CheckedInputStream(new ByteArrayInputStream(payload), new Adler32())) {
in.transferTo(OutputStream.nullOutputStream());
return in.getChecksum().getValue();
}
}
public static void main(String[] args) throws IOException {
byte[] message = "ledger-entry:acct=42,amount=9500".getBytes(StandardCharsets.UTF_8);
ByteArrayOutputStream raw = new ByteArrayOutputStream();
long writeSum;
try (CheckedOutputStream out = new CheckedOutputStream(raw, new Adler32())) {
out.write(message);
writeSum = out.getChecksum().getValue();
}
byte[] wire = raw.toByteArray();
long readSum = computeOnRead(wire);
System.out.println("writeSum=" + writeSum + " readSum=" + readSum + " match=" + (writeSum == readSum));
// Flip a single bit in transit and verify Adler32 detects the corruption
wire[8] ^= 0x01;
long tamperedSum = computeOnRead(wire);
System.out.println("tamperedSum=" + tamperedSum + " match=" + (writeSum == tamperedSum));
}
}Walkthrough notes — CheckedInputStream With Adler32 Checksum
The code’s whole job belongs to the class StreamChecksumGuard.
Resources are declared in a try-with-resources header, so they close on every exit path without a finally block.
Watch out for
- All symbols called live natively inside the language runtime with zero fetches.
Using it
The demo output is labeled (writeSum=, tamperedSum=); each label names the call that printed it.
Key statements
return in.getChecksum().getValue();
Interactive Tools for This Topic
ISBN ValidatorValidate ISBN-10 and ISBN-13 identifiers with checksum verification, hyphen-tolerant input, and conversion between the two forms.Luhn Checksum ValidatorValidate numeric identifiers with the Luhn algorithm and see the checksum sum and suggested final digit on failure.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.
FAQ
- What does CheckedInputStream With Adler32 Checksum print when run?
- Run it as a complete program — the output lines carry labels such as `writeSum=`, `tamperedSum=`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.