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): trimsseedto an unsigned 32-bit state viaseed & MASK32. RaiseValueErrorwhenever that 32-bit state equals0(for example0or2**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-shift13(trimmed to 32 bits), XOR with right-shift17, and XOR with left-shift5(trimmed to 32 bits)—saving the updated 32-bit state and returning it as an integer in1 .. 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
Nodetrees are equal if and only if every corresponding node has the samename, the sametext(Noneis distinct from""), and the same orderedchildren. xor_with_keystream(data: bytes, key: int) -> bytes: creates a freshXorShift32(key)and processesdatain 4-byte blocks. Eachrng.next()call yields 4 keystream bytes in little-endian order (value.to_bytes(4, "little")), XORed byte-by-byte againstdata(dropping unused keystream bytes on a partial final block). Callingxor_with_keystreama second time with the samekeyrestoresdata.encrypt(document: Node, key: int) -> bytes: convertsdocumentinto an unambiguous byte representation and masks those bytes viaxor_with_keystream(..., key).decrypt(ciphertext: bytes, key: int) -> Node: unmasksciphertextviaxor_with_keystream(..., key)and reconstructs an identicalNodetree. RaiseValueErrorifkeyis invalid or if the unmasked bytes do not decode to a validNodedocument.
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
seedandkeymay be any Pythonint(including negative values or integers>= 2**32);seed & 0xFFFFFFFF == 0must raiseValueError.nameandtextstrings may contain arbitrary Unicode characters, quotes, backslashes, brackets, newlines, or NUL bytes ("\x00").- Trees may contain up to
2 * 10^4nodes, including degenerate single-child chains20,000levels deep or wide nodes with5,000children (avoid per-level Python recursion). - Time and memory for
encryptanddecryptmust beO(N + S), whereNis the node count andSis the UTF-8 byte length of all names and texts.
Step-by-step walkthrough
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 yield1(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 classicxorshift32shift triple(13, 17, 5). - Tree schema:
Node(name: str, text: Optional[str], children: List[Node]), keepingtext=None("absent text") distinct fromtext=""("empty text"). - Ciphertext layout: an opaque
bytesblob 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
xorshift32is trivial to break). - Arbitrary characters & extreme depth: names and texts may hold quotes, backslashes, brackets, NUL bytes (
\x00), or emoji, and chains may reach20,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)- Register width: unsigned 32-bit integers (
Milestone 1: implement fixed-width XorShift32 and guard the stuck state
Marsaglia's
xorshift32maintains one 32-bit integerstateand scrambles it with three shift-and-XOR steps per call: left by13, right by17, and left by5.Three details decide whether it behaves properly in Python:
- Trim to 32 bits immediately after every left shift. Unlike C's
uint32_t, Pythonintvalues expand without bound instead of discarding bits above position31. Mask withMASK32 = 0xFFFFFFFFright after(x << 13)and(x << 5). Waiting until the end ofnext()to mask would allowx >> 17in step 2 to drag overflow bits from positions32..44back into the 32-bit window and corrupt the stream. - Forbid the all-zero state. Because
0 << k == 0and0 ^ 0 == 0, state0is a fixed point that emits0forever (leaving XOR-masked data completely unmasked!). After computingseed & MASK32, raiseValueErrorif the result is0. Raising is cleaner than silently substituting1, which would force seeds0and1onto identical sequences. - Full nonzero cycle. Each individual step
x ^= (x << k) & MASK32is invertible, and for(13, 17, 5)the composite 32×32 linear map cycles through all2^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 xNotice that
seed & MASK32maps negative Python integers via two's complement (-1 & MASK32 == 0xFFFFFFFF), while seeds separated by multiples of2^32reduce to the same 32-bit state.- Trim to 32 bits immediately after every left shift. Unlike C's
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) andx << 5(0x13_8009DCE0) spill bits past bit 31, and& MASK32trims them right away sox >> 17sees only clean 32-bit bits.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, a2^32 - 1period, and deterministic replay. - Why
XorShift32fails completely against an adversary:- Raw state exposure:
next()returnsself.stateverbatim. Observing 4 consecutive keystream bytes revealsself.statedirectly, predicting every subsequent byte without knowing the initial key. GF(2)linearity: every output bit is a linear XOR combination of seed bits, solvable with 32 linear equations.- Tiny 32-bit key space: ~4.3 billion keys can be exhaustively searched on consumer hardware in seconds.
- Raw state exposure:
Real confidentiality and integrity require an AEAD (Authenticated Encryption with Associated Data) primitive such as
AES-GCMorChaCha20-Poly1305from a vetted cryptography package.- Good fit: randomized unit/fuzz tests, procedural game content, Monte Carlo simulations, and randomized algorithms—cases needing tiny
Milestone 2: flatten the tree into unambiguous JSON records without recursion
Because
XorShift32emits byte blocks rather than tree operations, we convert theNodetree into abytesbuffer before masking and parse thosebytesback into aNodetree after unmasking.Two tempting formats fail under edge cases:
- Ad-hoc separator strings (
"name|text|..."): corrupt data whenevernameortextcontains"|", newlines, or"null". - Nested dicts/lists handed straight to
json.dumps: raiseRecursionErroron a20,000-deep chain because both the converter and Python'sjsonmodule 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 JSONnullvs.""distinguishesNonefrom empty string"". - The JSON structure is always two levels deep (
[[...], [...]]), whether theNodehierarchy is4or100,000levels deep—so neitherserializenorjson.dumpsever 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")- Ad-hoc separator strings (
Rebuild the tree and validate untrusted bytes
Reconstructing the tree from
recordstakes one forward scan: because pre-order lists every parent ahead of its children,0 <= parent < indexguaranteesnodes[parent]is already built when visitingindex.When
decryptreceives the wrong key or corrupted bytes, unmasking yields arbitrary byte patterns. Most fail.decode("utf-8")orjson.loads(...)withValueError, while adversarial inputs might decode to50,000nested[brackets (raisingRecursionErrorinsidejson.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]XOR the serialized bytes with the 4-byte little-endian keystream
Each 32-bit word from
rng.next()provides4keystream bytes in little-endian order (least-significant byte first, so0x001CE0E7becomese7 e0 1c 00). Step acrossdatain 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 identicalxor_with_keystreamfunction performs both encryption and decryption—provideddecryptinstantiates a freshXorShift32(key)from the start of the stream!Trace the first 8 bytes of
Node("memo", "Ok")serialized as[[-1, "memo", "Ok"]]underkey = 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)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"]](20UTF-8 bytes beginning with5b 5b 2d 31for"[[-1"). - Generate keystream & XOR:
XorShift32(7).next()shifts and XORs7(0x00000007) by(13, 17, 5)to produce1892583(0x001CE0E7), whose 4 little-endian bytes (least-significant byte first) aree7 e0 1c 00; XORing5b 5b 2d 31withe7 e0 1c 00yields ciphertext bytesbc bb 31 31, continuing in 4-byte blocks across all20bytes. - Decrypt & rebuild:
decryptinitializes a freshXorShift32(7), regeneratese7 e0 1c 00 ..., XORsbc bb 31 31back to5b 5b 2d 31("[[-1"), parses the JSON record list, verifies parent indices, and returnsNode("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.encryptanddecrypt: O(N + S) time, whereNis the node count andSis the serialized UTF-8 byte length.serializevisits each of theNnodes once on an explicit stack and pushes each child reference once,json.dumps/json.loadsruns linearly inS(Sscales with total name and text bytes plus constant JSON framing per node), andxor_with_keystreamcallsnext()ceil(S / 4)times while touching each of theSbytes once.- Space: O(N + S) heap memory for the
Nflat records /Nodeobjects andS-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^32seeds (0,2^32,3 * 2^32):seed & 0xFFFFFFFFevaluates to0and raisesValueErrorbefore the generator can enter the stuck state. - Negative seeds (
-1):-1 & 0xFFFFFFFFwraps to0xFFFFFFFF(2^32 - 1), matchingXorShift32(2**32 - 1)identically. text=Nonevs.text="": JSON encodesNoneasnulland""as"", keepinginvoice.text is Nonedistinct fromnotes.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 raiseUnicodeEncodeError;ensure_ascii=Truehandles 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 (5bytes) and arbitrary documents. - Deep (
20,000+levels) and wide (5,000+children) trees: explicit-stack traversal and flat 2-level JSON preventRecursionError(note that Python's default dataclass==still recurses when comparing two20,000-deepNodeinstances—use an iterative stack check for deep equality). - Wrong keys and crafted ciphertexts: corrupted UTF-8, invalid JSON, deep-bracket
RecursionErrorinsidejson.loads, boolean parent spoofing (Truein place of1), or forward/cyclic parent indices (not 0 <= parent < index) all raiseValueError.
Common mistakes
- Forgetting
& 0xFFFFFFFFafter left shifts in Python, lettingself.stategrow without bound instead of staying 32 bits wide. - Applying
& 0xFFFFFFFFonly once at the end ofnext():(x << 13)leaves high bits in positions32..44thatx >> 17shifts back into bits15..27, producing wrong outputs. - Allowing
seed = 0(orseed = 2**32), which outputs0forever and returns plaintext unmasked. - Reusing the same
XorShift32object acrossencryptanddecryptwithout 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-8bytes, breaking on any character aboveU+00FF. - Checking
isinstance(parent, int)rather thantype(parent) is intduring validation (isinstance(True, int)evaluates toTruein Python). - Serializing nested dicts/lists recursively, hitting
RecursionErroron deep chains. - Presenting
XorShift32XOR 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 ofp1exposesp2at those offsets. WithXorShift32, even a single ciphertext is broken because every serialized tree starts with the fixed 4-byte headerb"[[-1", immediately exposing output#1—which equalsXorShift32'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 asChaCha20-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 roughlysqrt(2 * ln(2) * 2^32) ≈ 77,000messages).
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.nameand non-Nonenode.text, storing hex or base64 strings on a mirroredNodeskeleton while preservingNoneasNone. 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 havetext=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
ciphertextto flip the exact same bits in decrypted plaintext without knowing the key—for example, XORing the byte encoding'2'in'2x "bolt"'withord('2') ^ ord('9') = 0x0bturns the decrypted string into'9x "bolt"'while keeping valid JSON!). Structural checks indeserializeonly 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 asHMAC-SHA256computed under a separate authentication key overnonce || ciphertextand checked in constant time viahmac.compare_digestbefore deserializing), or adopt an AEAD cipher (AES-GCMorChaCha20-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
serializeanddeserializealready execute inO(N + S)time and heap memory withO(1)Python call-stack usage becauseserializeuses an explicitstacklist andjson.dumps/json.loadsonly sees a flat 2-level array[[parent, name, text], ...], avoiding both Python's1,000-frame call limit andjson's nesting cap (~10,000levels). Recursion can still sneak into caller operations onNodeitself:@dataclass-generatedNode.__eq__andNode.__repr__recurse downchildren, raisingRecursionErrorat100,000levels 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)viastruct.pack. Binary framing eliminates JSON escaping overhead, provideddeserializebounds-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 onChaCha20-Poly1305orAES-GCMwhenever real security is needed.
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?
- 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?
- How can the recipient verify that no bytes of the ciphertext were flipped or truncated on the wire?
- What happens when a document chain reaches 100,000 nested child levels, and where could recursion still sneak in?
Similar questions
- Crash-Safe Log-Structured Key-Value Engine
- Single-Pass S-Expression Parser with Error Positions
- Bounded Thread-Pool Batch Executor
- Noisy Pod Alert Normalization and Outlier Replica Detection
- Multi-Tenant LLM Serving and Scheduling Platform
- Distributed Log Ingestion and Search Platform
More Baseten interview questions
- Distributed Log Ingestion and Search Platform Medium
- Single-Pass S-Expression Parser with Error Positions Medium
- Crash-Safe Log-Structured Key-Value Engine Hard Pro
- Noisy Pod Alert Normalization and Outlier Replica Detection Medium Pro
- Multi-Tenant LLM Serving and Scheduling Platform Hard Pro
- Bounded Thread-Pool Batch Executor Hard Pro
- Concurrent Chunked File Downloader with SHA-256 Verification Medium Pro