Back
+30 XP
Concept

PNG Chunk Reader & CRC Checksum Validator

Portable Network Graphics (PNG) files stream chunks containing a 4-byte length, 4-byte type code, variable data payload, and a 4-byte CRC-32 checksum. Validating PNGs requires verifying the 8-byte file signature and calculating CRC-32 over chunk types and data.

python
import zlib

# CRC32 is computed over Chunk Type + Chunk Data:
calculated_crc = zlib.crc32(chunk_type + chunk_data) & 0xFFFFFFFF

# PNG Chunk Reader & CRC Checksum Validator The PNG specification is one of the cleanest binary file formats ever engineered. It begins with an 8-byte magic sequence (`\x89PNG\r\n\x1a\n`), followed by contiguous blocks called **Chunks**. 🖼️🛡️ Every chunk has 4 parts: 1. **Length (4 bytes)**: Big-endian `uint32` indicating the size of Chunk Data. 2. **Chunk Type (4 bytes)**: ASCII identifier (`IHDR`, `IDAT`, `PLTE`, `IEND`). 3. **Chunk Data (`Length` bytes)**: Raw payload. 4. **CRC-32 (4 bytes)**: Big-endian `uint32` checksum computed strictly over `Chunk Type + Chunk Data`. ```python import struct import zlib # Unpack length and chunk type length, ctype = struct.unpack_from(">I4s", stream, offset) # Validate CRC: calc_crc = zlib.crc32(ctype + data) & 0xFFFFFFFF ``` ## Pop Quiz Over which exact byte segments of a PNG chunk is the CRC-32 checksum calculated? - [ ] The 4-byte Chunk Type code followed immediately by the Chunk Data bytes. - [ ] The full chunk starting from the 4-byte length through the end of the CRC bytes. - [ ] The uncompressed raw pixel values before Deflate algorithm compression. - [ ] Only the 4-byte ASCII chunk name without data payload. ## Real-World Challenge Implement `parse_png_chunks(data: bytes) -> list[tuple[str, bytes]]`. - Reject payloads lacking the 8-byte PNG signature with `ValueError`. - Traverse chunks, validating that the declared CRC matches `zlib.crc32(chunk_type + chunk_data) & 0xFFFFFFFF`. - Raise `ValueError` if a checksum mismatch occurs. Return a list of `(chunk_type_str, chunk_data_bytes)`. <details> <summary>Solution</summary> ```python import struct import zlib PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n" def parse_png_chunks(data: bytes) -> list[tuple[str, bytes]]: if not data.startswith(PNG_SIGNATURE): raise ValueError("Invalid PNG header signature") offset = 8 total_len = len(data) chunks = [] while offset < total_len: if offset + 8 > total_len: raise ValueError("Truncated chunk header") length, chunk_type = struct.unpack_from(">I4s", data, offset) offset += 8 chunk_data = data[offset : offset + length] offset += length if offset + 4 > total_len: raise ValueError("Truncated chunk CRC field") expected_crc, = struct.unpack_from(">I", data, offset) offset += 4 actual_crc = zlib.crc32(chunk_type + chunk_data) & 0xFFFFFFFF if actual_crc != expected_crc: raise ValueError( f"CRC mismatch in chunk {chunk_type.decode(errors='replace')}: " f"expected {expected_crc}, got {actual_crc}" ) chunks.append((chunk_type.decode("ascii", errors="replace"), chunk_data)) return chunks # Verification # 1. Build synthetic valid PNG ihdr_payload = struct.pack(">IIBBBBB", 16, 16, 8, 6, 0, 0, 0) ihdr_crc = zlib.crc32(b"IHDR" + ihdr_payload) & 0xFFFFFFFF ihdr_chunk = struct.pack(">I4s", len(ihdr_payload), b"IHDR") + ihdr_payload + struct.pack(">I", ihdr_crc) iend_crc = zlib.crc32(b"IEND") & 0xFFFFFFFF iend_chunk = struct.pack(">I4s", 0, b"IEND") + struct.pack(">I", iend_crc) valid_png = PNG_SIGNATURE + ihdr_chunk + iend_chunk parsed = parse_png_chunks(valid_png) assert [name for name, _ in parsed] == ["IHDR", "IEND"] # 2. Corrupted CRC detection corrupt_png = bytearray(valid_png) corrupt_png[-1] ^= 0xFF # Flip bit in CRC has_crc_error = False try: parse_png_chunks(bytes(corrupt_png)) except ValueError: has_crc_error = True assert has_crc_error is True ``` </details>