XorShift32 Stream Cipher for Tree Documents

Medium · Software Engineering Fundamentals · Software Engineer · Onsite

Problem Statement

Build a deterministic 32-bit shift-XOR stream generator from scratch, then pair it with a lossless tree serializer to mask and unmask hierarchical documents.

Do not call Python's random, secrets, or cryptography modules for random generation or encryption; compute every generator step directly with integer bit shifts, bitwise XOR (^), and 32-bit bitmasks.

Milestone 1 — 32-Bit XorShift Generator (XorShift32)

Implement XorShift32 using MASK32 = 0xFFFFFFFF:

  • XorShift32(seed: int): trims seed to an unsigned 32-bit state via seed & MASK32. Raise ValueError whenever that 32-bit state equals 0 (for example 0 or 2**32), since shifting and XORing zero never leaves zero.
  • next(self) -> int: advances the internal 32-bit state through Marsaglia's classic (13, 17, 5) update—XOR with left-shift 13 (trimmed to 32 bits), XOR with right-shift 17, and XOR with left-shift 5 (trimmed to 32 bits)—saving the updated 32-bit state and returning it as an integer in 1 .. 2**32 - 1.

Milestone 2 — Keystream Masking & Tree Cipher

Documents are modeled with the @dataclass Node(name: str, text: Optional[str] = None, children: List[Node] = ...):

  • Two Node trees are equal if and only if every corresponding node has the same name, the same text (None is distinct from ""), and the same ordered children.
  • xor_with_keystream(data: bytes, key: int) -> bytes: creates a fresh XorShift32(key) and processes data in 4-byte blocks. Each rng.next() call yields 4 keystream bytes in little-endian order (value.to_bytes(4, "little")), XORed byte-by-byte against data (dropping unused keystream bytes on a partial final block). Calling xor_with_keystream a second time with the same key restores data.
  • encrypt(document: Node, key: int) -> bytes: converts document into an unambiguous byte representation and masks those bytes via xor_with_keystream(..., key).
  • decrypt(ciphertext: bytes, key: int) -> Node: unmasks ciphertext via xor_with_keystream(..., key) and reconstructs an identical Node tree. Raise ValueError if key is invalid or if the unmasked bytes do not decode to a valid Node document.

Examples

Example 1

Input:
  rng = XorShift32(7)
  [rng.next(), rng.next()]
  XorShift32(0)

Output:
  [1892583, 470389255]
  raises ValueError

Walk-through: Starting from 0x00000007, XORing (x << 13) & 0xFFFFFFFF produces 0x0000E007, x >> 17 is 0, and XORing (x << 5) & 0xFFFFFFFF (0x001C00E0) yields 0x001CE0E7 = 1,892,583. Advancing a second time yields 0x1C099207 = 470,389,255. Passing 0 (or any multiple of 2**32) reduces to 0 and raises ValueError.

Example 2

Input:
  stream_head = xor_with_keystream(b"\x00\x00\x00\x00\x00", 7)
  restored = xor_with_keystream(stream_head, 7)

Output:
  stream_head == b"\xe7\xe0\x1c\x00\x07"
  restored == b"\x00\x00\x00\x00\x00"

Walk-through: XORing five zero bytes reveals the first 5 keystream bytes for key = 7: the 4 little-endian bytes of 0x001CE0E7 (e7 e0 1c 00) followed by the least-significant byte of 0x1C099207 (07), discarding the remaining 3 bytes of the second 32-bit word. Running xor_with_keystream again with key = 7 cancels every mask byte back to b"\x00\x00\x00\x00\x00".

Example 3

Input:
  doc = Node("invoice", None, [
      Node("vendor", "Northwind"),
      Node("notes", ""),
      Node("item", '2x "bolt" [M8]'),
  ])
  blob = encrypt(doc, 42)
  out = decrypt(blob, 42)

Output:
  out == doc
  out.text is None and out.children[1].text == ""

Walk-through: encrypt flattens and encodes the four-node invoice tree—preserving None vs. "" as well as quotes and brackets inside '2x "bolt" [M8]'—and masks the UTF-8 byte stream under XorShift32(42). decrypt(blob, 42) replays the identical keystream from byte 0 and rebuilds an equal Node tree, whereas decrypting with a wrong key such as 43 fails validation.

Constraints

  • seed and key may be any Python int (including negative values or integers >= 2**32); seed & 0xFFFFFFFF == 0 must raise ValueError.
  • name and text strings may contain arbitrary Unicode characters, quotes, backslashes, brackets, newlines, or NUL bytes ("\x00").
  • Trees may contain up to 2 * 10^4 nodes, including degenerate single-child chains 20,000 levels deep or wide nodes with 5,000 children (avoid per-level Python recursion).
  • Time and memory for encrypt and decrypt must be O(N + S), where N is the node count and S is the UTF-8 byte length of all names and texts.

Step-by-step walkthrough

  1. Settle the open design choices up front

    A pseudo-random number generator (PRNG) is a deterministic routine that stretches a starting integer (the seed) into a repeatable sequence of numbers that appear random. In a stream cipher, those numbers supply a keystream of mask bytes combined with data via bitwise exclusive-OR (XOR, ^)—the bit operation where matching bits cancel (0 ^ 0 = 0, 1 ^ 1 = 0) and opposite bits yield 1 (0 ^ 1 = 1).

    Lock down the interface decisions before writing code so every boundary is unambiguous:

    • Register width: unsigned 32-bit integers (1 .. 2^32 - 1), driven by George Marsaglia's classic xorshift32 shift triple (13, 17, 5).
    • Tree schema: Node(name: str, text: Optional[str], children: List[Node]), keeping text=None ("absent text") distinct from text="" ("empty text").
    • Ciphertext layout: an opaque bytes blob hiding both structure and text (structure-preserving encryption is examined in the follow-ups).
    • Security context: this problem evaluates fixed-width bit arithmetic, unambiguous tree serialization, and deterministic keystream usage—not real cryptographic secrecy (we will demonstrate why xorshift32 is trivial to break).
    • Arbitrary characters & extreme depth: names and texts may hold quotes, backslashes, brackets, NUL bytes (\x00), or emoji, and chains may reach 20,000+ levels, so neither tree traversal nor JSON encoding may recurse once per level.
    from typing import List, Optional
    from dataclasses import dataclass, field
    
    
    @dataclass
    class Node:
        """One node of the document: a name, optional text (None = no text), ordered children."""
        name: str
        text: Optional[str] = None
        children: List["Node"] = field(default_factory=list)
    
  2. Milestone 1: implement fixed-width XorShift32 and guard the stuck state

    Marsaglia's xorshift32 maintains one 32-bit integer state and scrambles it with three shift-and-XOR steps per call: left by 13, right by 17, and left by 5.

    Three details decide whether it behaves properly in Python:

    1. Trim to 32 bits immediately after every left shift. Unlike C's uint32_t, Python int values expand without bound instead of discarding bits above position 31. Mask with MASK32 = 0xFFFFFFFF right after (x << 13) and (x << 5). Waiting until the end of next() to mask would allow x >> 17 in step 2 to drag overflow bits from positions 32..44 back into the 32-bit window and corrupt the stream.
    2. Forbid the all-zero state. Because 0 << k == 0 and 0 ^ 0 == 0, state 0 is a fixed point that emits 0 forever (leaving XOR-masked data completely unmasked!). After computing seed & MASK32, raise ValueError if the result is 0. Raising is cleaner than silently substituting 1, which would force seeds 0 and 1 onto identical sequences.
    3. Full nonzero cycle. Each individual step x ^= (x << k) & MASK32 is invertible, and for (13, 17, 5) the composite 32×32 linear map cycles through all 2^32 - 1 (4,294,967,295) nonzero 32-bit integers before repeating.
    # Bitmask that trims Python's unbounded ints down to unsigned 32-bit width (0 .. 2**32 - 1)
    MASK32 = 0xFFFFFFFF
    
    
    class XorShift32:
        """Marsaglia's xorshift32 with shifts (13, 17, 5): 32-bit state, outputs 1 .. 2**32 - 1."""
    
        def __init__(self, seed: int):
            # Reduce negative or oversized Python ints modulo 2**32
            state = seed & MASK32
            # State 0 is a fixed point (0 ^ 0 == 0), which would output 0 forever
            if state == 0:
                raise ValueError("seed must not be a multiple of 2**32: state 0 never changes")
            self.state = state
    
        def next(self) -> int:
            x = self.state
            # Mask immediately after every left shift so overflow bits >= 32 never leak into >> 17
            x ^= (x << 13) & MASK32
            x ^= x >> 17
            x ^= (x << 5) & MASK32
            self.state = x
            return x
    

    Notice that seed & MASK32 maps negative Python integers via two's complement (-1 & MASK32 == 0xFFFFFFFF), while seeds separated by multiples of 2^32 reduce to the same 32-bit state.

  3. Trace Example 1 (`seed = 7`) through two steps in hex

    Formatting 32-bit states as 8-digit hexadecimal integers makes every shift and mask transparent:

    Initial seed = 7:
      x                   = 0x00000007
      (x << 13) & MASK32  = 0x0000E000   -->  x ^= ...  -->  x = 0x0000E007
      x >> 17             = 0x00000000   -->  x ^= ...  -->  x = 0x0000E007
      (x << 5)  & MASK32  = 0x001C00E0   -->  x ^= ...  -->  x = 0x001CE0E7 = 1,892,583   (1st output)
    
    Second call starting from x = 0x001CE0E7:
      x << 13 (unmasked)  = 0x3_9C1CE000
      (x << 13) & MASK32  = 0x9C1CE000   -->  x ^= ...  -->  x = 0x9C0000E7
      x >> 17             = 0x00004E00   -->  x ^= ...  -->  x = 0x9C004EE7
      x << 5  (unmasked)  = 0x13_8009DCE0
      (x << 5)  & MASK32  = 0x8009DCE0   -->  x ^= ...  -->  x = 0x1C099207 = 470,389,255 (2nd output)
    

    Look at the second step: both x << 13 (0x3_9C1CE000) and x << 5 (0x13_8009DCE0) spill bits past bit 31, and & MASK32 trims them right away so x >> 17 sees only clean 32-bit bits.

  4. Explain where XorShift32 fits—and why it is never cryptographic

    Interviewers evaluate engineering judgment on when a simple shift-XOR PRNG is appropriate:

    • Good fit: randomized unit/fuzz tests, procedural game content, Monte Carlo simulations, and randomized algorithms—cases needing tiny O(1) updates, zero imports, a 2^32 - 1 period, and deterministic replay.
    • Why XorShift32 fails completely against an adversary:
      1. Raw state exposure: next() returns self.state verbatim. Observing 4 consecutive keystream bytes reveals self.state directly, predicting every subsequent byte without knowing the initial key.
      2. GF(2) linearity: every output bit is a linear XOR combination of seed bits, solvable with 32 linear equations.
      3. Tiny 32-bit key space: ~4.3 billion keys can be exhaustively searched on consumer hardware in seconds.

    Real confidentiality and integrity require an AEAD (Authenticated Encryption with Associated Data) primitive such as AES-GCM or ChaCha20-Poly1305 from a vetted cryptography package.

  5. Milestone 2: flatten the tree into unambiguous JSON records without recursion

    Because XorShift32 emits byte blocks rather than tree operations, we convert the Node tree into a bytes buffer before masking and parse those bytes back into a Node tree after unmasking.

    Two tempting formats fail under edge cases:

    • Ad-hoc separator strings ("name|text|..."): corrupt data whenever name or text contains "|", newlines, or "null".
    • Nested dicts/lists handed straight to json.dumps: raise RecursionError on a 20,000-deep chain because both the converter and Python's json module recurse per tree level.

    Instead, walk the tree in pre-order (parent before children) using an explicit Python list stack, emitting a flat list of 3-item records [parent_index, name, text] serialized as UTF-8 JSON:

    Tree:                                    Flat pre-order records (index 0, 1, 2, 3):
              invoice (text=None)     --->   0: [-1, "invoice", null]
             /       |        \              1: [ 0, "vendor",  "Northwind"]
      vendor       notes       item          2: [ 0, "notes",   ""]
    ("Northwind")   ("")   ('2x "bolt"...')  3: [ 0, "item",    "2x \"bolt\" [M8]"]
    

    Why flat pre-order JSON records handle every requirement cleanly:

    • JSON escapes quotes (\"), backslashes (\\), NUL (\u0000), and arbitrary Unicode automatically, while JSON null vs. "" distinguishes None from empty string "".
    • The JSON structure is always two levels deep ([[...], [...]]), whether the Node hierarchy is 4 or 100,000 levels deep—so neither serialize nor json.dumps ever hits recursion limits.
    • Pushing reversed(node.children) onto the LIFO stack places the first child on top of the stack so it is popped first, preserving exact child ordering.
    import json
    
    
    def serialize(document: Node) -> bytes:
        """Flatten tree into pre-order `[parent_index, name, text]` JSON records (-1 = root)."""
        # records: flat list e.g. [[-1, "memo", null], [0, "item", "Ok"]] (no deep JSON nesting)
        records = []
        # stack: explicit LIFO worklist of (node, parent_record_index) to avoid RecursionError
        stack = [(document, -1)]
        while stack:
            node, parent = stack.pop()
            index = len(records)
            records.append([parent, node.name, node.text])
            # Push children in reverse so the first child sits on top and is popped first
            for child in reversed(node.children):
                stack.append((child, index))
        return json.dumps(records, ensure_ascii=False).encode("utf-8")
    
  6. Rebuild the tree and validate untrusted bytes

    Reconstructing the tree from records takes one forward scan: because pre-order lists every parent ahead of its children, 0 <= parent < index guarantees nodes[parent] is already built when visiting index.

    When decrypt receives the wrong key or corrupted bytes, unmasking yields arbitrary byte patterns. Most fail .decode("utf-8") or json.loads(...) with ValueError, while adversarial inputs might decode to 50,000 nested [ brackets (raising RecursionError inside json.loads) or non-document JSON like [], {}, or [[-1, "x", 5]]. Catch (ValueError, RecursionError) and verify every record's exact types and parent index bounds:

    def valid_record(record, index: int) -> bool:
        """Check that one decoded JSON entry is a well-formed `[parent_idx, name, text]` triple."""
        if not isinstance(record, list) or len(record) != 3:
            return False
        parent, name, text = record
        # Use `type(parent) is not int` because bool is a subclass of int in Python
        if type(parent) is not int or not isinstance(name, str):
            return False
        if text is not None and not isinstance(text, str):
            return False
        # Root (index 0) must have parent -1; every later node must attach to an earlier parent
        if index == 0:
            return parent == -1
        return 0 <= parent < index
    
    
    def deserialize(data: bytes) -> Node:
        """Rebuild the Node tree from UTF-8 JSON records, or raise ValueError on bad bytes."""
        try:
            records = json.loads(data.decode("utf-8"))
        except (ValueError, RecursionError):
            # Wrong keys or corrupted bytes fail UTF-8/JSON decoding or exceed JSON nesting limits
            raise ValueError("not a serialized document (wrong key or corrupted data)")
    
        if not isinstance(records, list) or len(records) == 0:
            raise ValueError("not a serialized document (wrong key or corrupted data)")
    
        # nodes: rebuilt Node objects indexed by their pre-order position 0 .. len(records) - 1
        nodes = []
        for index, record in enumerate(records):
            if not valid_record(record, index):
                raise ValueError(f"bad node record at position {index}")
            parent, name, text = record
            node = Node(name, text)
            if parent >= 0:
                nodes[parent].children.append(node)
            nodes.append(node)
        return nodes[0]
    
  7. XOR the serialized bytes with the 4-byte little-endian keystream

    Each 32-bit word from rng.next() provides 4 keystream bytes in little-endian order (least-significant byte first, so 0x001CE0E7 becomes e7 e0 1c 00). Step across data in 4-byte chunks, XOR each byte with its matching keystream byte, and drop unused bytes on any shorter final block.

    Because (plain_byte ^ mask_byte) ^ mask_byte == plain_byte ^ (mask_byte ^ mask_byte) == plain_byte ^ 0 == plain_byte, the identical xor_with_keystream function performs both encryption and decryption—provided decrypt instantiates a fresh XorShift32(key) from the start of the stream!

    Trace the first 8 bytes of Node("memo", "Ok") serialized as [[-1, "memo", "Ok"]] under key = 7:

    char:       [     [     -     1        ,     sp    "     m
    plain hex:  5b    5b    2d    31       2c    20    22    6d
    keystream:  e7    e0    1c    00       07    92    09    1c   <-- 1892583, 470389255 little-endian
    XOR cipher: bc    bb    31    31       2b    b2    2b    71
    XOR again:  5b    5b    2d    31       2c    20    22    6d   <-- original bytes restored!
    
    def xor_with_keystream(data: bytes, key: int) -> bytes:
        """XOR `data` with XorShift32(key), 4 little-endian bytes per call. Self-inverse."""
        rng = XorShift32(key)
        out = bytearray(len(data))
        for start in range(0, len(data), 4):
            # Pull 4 keystream bytes (least-significant byte first) from one 32-bit output
            block = rng.next().to_bytes(4, "little")
            # Drop any leftover keystream bytes if the final data block has fewer than 4 bytes
            chunk_size = min(4, len(data) - start)
            for j in range(chunk_size):
                out[start + j] = data[start + j] ^ block[j]
        return bytes(out)
    
    
    def encrypt(document: Node, key: int) -> bytes:
        """Part 2: serialize the tree into UTF-8 bytes, then XOR with the keystream."""
        plaintext = serialize(document)
        return xor_with_keystream(plaintext, key)
    
    
    def decrypt(ciphertext: bytes, key: int) -> Node:
        """Part 2: XOR with the same keystream from the start, then rebuild the tree."""
        plaintext = xor_with_keystream(ciphertext, key)
        return deserialize(plaintext)
    
  8. Complete solution

    from typing import List, Optional
    from dataclasses import dataclass, field
    import json
    
    # Bitmask that trims Python's unbounded ints down to unsigned 32-bit width (0 .. 2**32 - 1)
    MASK32 = 0xFFFFFFFF
    
    
    @dataclass
    class Node:
        """One node of the document: a name, optional text (None = no text), ordered children."""
        name: str
        text: Optional[str] = None
        children: List["Node"] = field(default_factory=list)
    
    
    class XorShift32:
        """Marsaglia's xorshift32 with shifts (13, 17, 5): 32-bit state, outputs 1 .. 2**32 - 1."""
    
        def __init__(self, seed: int):
            # Reduce negative or oversized Python ints modulo 2**32
            state = seed & MASK32
            # State 0 is a fixed point (0 ^ 0 == 0), which would output 0 forever
            if state == 0:
                raise ValueError("seed must not be a multiple of 2**32: state 0 never changes")
            self.state = state
    
        def next(self) -> int:
            x = self.state
            # Mask immediately after every left shift so overflow bits >= 32 never leak into >> 17
            x ^= (x << 13) & MASK32
            x ^= x >> 17
            x ^= (x << 5) & MASK32
            self.state = x
            return x
    
    
    def xor_with_keystream(data: bytes, key: int) -> bytes:
        """XOR `data` with XorShift32(key), 4 little-endian bytes per call. Self-inverse."""
        rng = XorShift32(key)
        out = bytearray(len(data))
        for start in range(0, len(data), 4):
            # Pull 4 keystream bytes (least-significant byte first) from one 32-bit output
            block = rng.next().to_bytes(4, "little")
            # Drop any leftover keystream bytes if the final data block has fewer than 4 bytes
            chunk_size = min(4, len(data) - start)
            for j in range(chunk_size):
                out[start + j] = data[start + j] ^ block[j]
        return bytes(out)
    
    
    def serialize(document: Node) -> bytes:
        """Flatten tree into pre-order `[parent_index, name, text]` JSON records (-1 = root)."""
        # records: flat list e.g. [[-1, "memo", null], [0, "item", "Ok"]] (no deep JSON nesting)
        records = []
        # stack: explicit LIFO worklist of (node, parent_record_index) to avoid RecursionError
        stack = [(document, -1)]
        while stack:
            node, parent = stack.pop()
            index = len(records)
            records.append([parent, node.name, node.text])
            # Push children in reverse so the first child sits on top and is popped first
            for child in reversed(node.children):
                stack.append((child, index))
        return json.dumps(records, ensure_ascii=False).encode("utf-8")
    
    
    def valid_record(record, index: int) -> bool:
        """Check that one decoded JSON entry is a well-formed `[parent_idx, name, text]` triple."""
        if not isinstance(record, list) or len(record) != 3:
            return False
        parent, name, text = record
        # Use `type(parent) is not int` because bool is a subclass of int in Python
        if type(parent) is not int or not isinstance(name, str):
            return False
        if text is not None and not isinstance(text, str):
            return False
        # Root (index 0) must have parent -1; every later node must attach to an earlier parent
        if index == 0:
            return parent == -1
        return 0 <= parent < index
    
    
    def deserialize(data: bytes) -> Node:
        """Rebuild the Node tree from UTF-8 JSON records, or raise ValueError on bad bytes."""
        try:
            records = json.loads(data.decode("utf-8"))
        except (ValueError, RecursionError):
            # Wrong keys or corrupted bytes fail UTF-8/JSON decoding or exceed JSON nesting limits
            raise ValueError("not a serialized document (wrong key or corrupted data)")
    
        if not isinstance(records, list) or len(records) == 0:
            raise ValueError("not a serialized document (wrong key or corrupted data)")
    
        # nodes: rebuilt Node objects indexed by their pre-order position 0 .. len(records) - 1
        nodes = []
        for index, record in enumerate(records):
            if not valid_record(record, index):
                raise ValueError(f"bad node record at position {index}")
            parent, name, text = record
            node = Node(name, text)
            if parent >= 0:
                nodes[parent].children.append(node)
            nodes.append(node)
        return nodes[0]
    
    
    def encrypt(document: Node, key: int) -> bytes:
        """Part 2: serialize the tree into UTF-8 bytes, then XOR with the keystream."""
        plaintext = serialize(document)
        return xor_with_keystream(plaintext, key)
    
    
    def decrypt(ciphertext: bytes, key: int) -> Node:
        """Part 2: XOR with the same keystream from the start, then rebuild the tree."""
        plaintext = xor_with_keystream(ciphertext, key)
        return deserialize(plaintext)
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of masking a tree document with a pseudo-random number generator (PRNG)—a deterministic formula turning an integer seed into a repeatable number stream—like a two-step packing line: first flatten the branching tree onto a numbered manifest of UTF-8 bytes, then XOR every byte on that manifest against a synchronized keystream (a sequence of mask bytes). Because XORing the identical mask byte a second time cancels straight out ((plain ^ mask) ^ mask == plain), decrypt simply starts a fresh generator from the shared key, unmasks the byte buffer, and rebuilds the Node hierarchy from the manifest.

Shortcut approaches fail in three subtle places. First, Python integers never discard high bits on left shift (<<), so skipping & 0xFFFFFFFF after left shifts lets overflow bits bleed back in during >> 17, while accepting seed 0 freezes the stream at 0 forever. Second, custom string delimiters like "name|text" break as soon as user text contains "|", and recursive serialization or nested JSON crashes with RecursionError on deep single-child chains (20,000+ levels).

Walk through a concrete round trip on Node("memo", "Ok") with key = 7:

  • Flatten & encode: iterative pre-order traversal emits [[-1, "memo", "Ok"]] (20 UTF-8 bytes beginning with 5b 5b 2d 31 for "[[-1").
  • Generate keystream & XOR: XorShift32(7).next() shifts and XORs 7 (0x00000007) by (13, 17, 5) to produce 1892583 (0x001CE0E7), whose 4 little-endian bytes (least-significant byte first) are e7 e0 1c 00; XORing 5b 5b 2d 31 with e7 e0 1c 00 yields ciphertext bytes bc bb 31 31, continuing in 4-byte blocks across all 20 bytes.
  • Decrypt & rebuild: decrypt initializes a fresh XorShift32(7), regenerates e7 e0 1c 00 ..., XORs bc bb 31 31 back to 5b 5b 2d 31 ("[[-1"), parses the JSON record list, verifies parent indices, and returns Node("memo", "Ok").

Complexity

  • XorShift32.next(): O(1) time and O(1) space. Every call executes three bit shifts, three XORs, and two 32-bit bitmasks on one integer regardless of stream length.
  • encrypt and decrypt: O(N + S) time, where N is the node count and S is the serialized UTF-8 byte length. serialize visits each of the N nodes once on an explicit stack and pushes each child reference once, json.dumps / json.loads runs linearly in S (S scales with total name and text bytes plus constant JSON framing per node), and xor_with_keystream calls next() ceil(S / 4) times while touching each of the S bytes once.
  • Space: O(N + S) heap memory for the N flat records / Node objects and S-byte buffers, with O(1) call-stack depth because neither our stack loop nor flat two-level JSON recurses per tree level.

Edge cases

  • Zero and multiple-of-2^32 seeds (0, 2^32, 3 * 2^32): seed & 0xFFFFFFFF evaluates to 0 and raises ValueError before the generator can enter the stuck state.
  • Negative seeds (-1): -1 & 0xFFFFFFFF wraps to 0xFFFFFFFF (2^32 - 1), matching XorShift32(2**32 - 1) identically.
  • text=None vs. text="": JSON encodes None as null and "" as "", keeping invoice.text is None distinct from notes.text == "" in Example 3.
  • Special characters in names or text: quotes ("), backslashes (\), brackets (]), "null", newlines, NUL bytes (\x00), CJK characters, and emoji all survive via JSON escaping and UTF-8 encoding. (Note: lone UTF-16 surrogates like "\ud800" cannot be encoded in strict UTF-8 and raise UnicodeEncodeError; ensure_ascii=True handles raw surrogates if ever required.)
  • Byte lengths not divisible by 4: chunk_size = min(4, len(data) - start) drops unused trailing keystream bytes cleanly on both Example 2 (5 bytes) and arbitrary documents.
  • Deep (20,000+ levels) and wide (5,000+ children) trees: explicit-stack traversal and flat 2-level JSON prevent RecursionError (note that Python's default dataclass == still recurses when comparing two 20,000-deep Node instances—use an iterative stack check for deep equality).
  • Wrong keys and crafted ciphertexts: corrupted UTF-8, invalid JSON, deep-bracket RecursionError inside json.loads, boolean parent spoofing (True in place of 1), or forward/cyclic parent indices (not 0 <= parent < index) all raise ValueError.

Common mistakes

  • Forgetting & 0xFFFFFFFF after left shifts in Python, letting self.state grow without bound instead of staying 32 bits wide.
  • Applying & 0xFFFFFFFF only once at the end of next(): (x << 13) leaves high bits in positions 32..44 that x >> 17 shifts back into bits 15..27, producing wrong outputs.
  • Allowing seed = 0 (or seed = 2**32), which outputs 0 forever and returns plaintext unmasked.
  • Reusing the same XorShift32 object across encrypt and decrypt without re-seeding, XORing ciphertext against subsequent stream blocks instead of starting at block 0.
  • XORing Python character code points (ord(ch) ^ byte) instead of UTF-8 bytes, breaking on any character above U+00FF.
  • Checking isinstance(parent, int) rather than type(parent) is int during validation (isinstance(True, int) evaluates to True in Python).
  • Serializing nested dicts/lists recursively, hitting RecursionError on deep chains.
  • Presenting XorShift32 XOR masking as cryptographically secure without pointing out known-plaintext state recovery and malleability.

Follow-up questions

  • If two distinct trees are masked under the exact same seed, what information leaks to an eavesdropper holding both ciphertexts, and how do you fix the protocol? Reusing a keystream creates a classic two-time pad failure: c1 XOR c2 == (p1 XOR k) XOR (p2 XOR k) == p1 XOR p2, canceling the mask stream completely so shared prefixes XOR to zero bytes and guessing any substring of p1 exposes p2 at those offsets. With XorShift32, even a single ciphertext is broken because every serialized tree starts with the fixed 4-byte header b"[[-1", immediately exposing output #1—which equals XorShift32's entire internal state (demonstrated below). Real stream encryption prevents reuse by pairing a secret key with a fresh per-message nonce (a public "number used once," e.g., 96 or 192 bits) inside a cryptographic cipher such as ChaCha20-Poly1305 (a 32-bit seed space is also far too small for random nonces, hitting a 50% collision birthday bound—the point where random draws start colliding—after roughly sqrt(2 * ln(2) * 2^32) ≈ 77,000 messages).
def recover_plaintext_without_key(ciphertext: bytes) -> bytes:
    """Break any XorShift32 ciphertext using the known 4-byte header b'[[-1'."""
    known_header = b"[[-1"
    first_block = bytearray(4)
    for i in range(4):
        first_block[i] = ciphertext[i] ^ known_header[i]
    # Because XorShift32.next() sets self.state = output, seeding with output #1 yields #2, #3, ...
    leaked_state = int.from_bytes(first_block, "little")
    remaining_plain = xor_with_keystream(ciphertext[4:], leaked_state)
    return known_header + remaining_plain
  • Suppose callers want the tree hierarchy left intact while masking only node names and text strings—how would you build that, and what metadata still leaks? Walk the tree in a deterministic order (such as iterative pre-order) pulling bytes from one continuous cipher stream (or deriving a distinct per-node nonce) to mask each UTF-8 node.name and non-None node.text, storing hex or base64 strings on a mirrored Node skeleton while preserving None as None. Never re-initialize the generator with the same seed per node—otherwise repeated tag names like "item" produce identical ciphertexts! Even with a strong cipher, structure-preserving encryption still reveals total node count, exact parent-child topology, exact UTF-8 byte lengths of every name and text, and which nodes have text=None, often letting an observer identify known templates.

  • How can the recipient verify that no bytes of the ciphertext were flipped or truncated on the wire? Unauthenticated XOR stream ciphers are malleable (an attacker can flip targeted bits in ciphertext to flip the exact same bits in decrypted plaintext without knowing the key—for example, XORing the byte encoding '2' in '2x "bolt"' with ord('2') ^ ord('9') = 0x0b turns the decrypted string into '9x "bolt"' while keeping valid JSON!). Structural checks in deserialize only catch accidental garbage, not surgical edits or clean tail truncation on record boundaries. To detect tampering, add Encrypt-then-MAC using a MAC (Message Authentication Code—a keyed cryptographic tag such as HMAC-SHA256 computed under a separate authentication key over nonce || ciphertext and checked in constant time via hmac.compare_digest before deserializing), or adopt an AEAD cipher (AES-GCM or ChaCha20-Poly1305) that authenticates and encrypts together.

  • What happens when a document chain reaches 100,000 nested child levels, and where could recursion still sneak in? Both serialize and deserialize already execute in O(N + S) time and heap memory with O(1) Python call-stack usage because serialize uses an explicit stack list and json.dumps / json.loads only sees a flat 2-level array [[parent, name, text], ...], avoiding both Python's 1,000-frame call limit and json's nesting cap (~10,000 levels). Recursion can still sneak into caller operations on Node itself: @dataclass-generated Node.__eq__ and Node.__repr__ recurse down children, raising RecursionError at 100,000 levels unless replaced with explicit-stack __eq__ and __repr__ methods. If total serialized size also outgrows RAM, stream length-prefixed node records directly through a stateful keystream object chunk by chunk instead of building one monolithic JSON buffer.

Alternative approaches

  • Length-prefixed binary records instead of JSON: pack a 4-byte node count followed per node by (parent_i32, name_len_u32, name_bytes, has_text_u8, text_len_u32, text_bytes) via struct.pack. Binary framing eliminates JSON escaping overhead, provided deserialize bounds-checks every length field against remaining buffer bytes so wrong-key garbage cannot request multi-gigabyte allocations.
  • Wider shift-register PRNGs (xorshift64, xorshift128+, xoshiro256**): expand state width to 64–256 bits for much longer cycles and stronger statistical properties in simulations—while still relying on ChaCha20-Poly1305 or AES-GCM whenever real security is needed.

Follow-up questions

Similar questions

More Baseten interview questions

All 8 Baseten questions →