Section 15.38

Prefix-free encoding

Definition

A prefix-free encoding, also called a prefix code, writes each value as a string of symbols, called a codeword, such that no codeword is a prefix of another: no codeword is the beginning of a different, longer codeword. A reader can therefore tell where a codeword ends as soon as its last symbol arrives, without looking further, and codewords written one after another split back into codewords in exactly one way. Fixed-width fields, length-prefixed fields and self-delimiting codes are all prefix-free encodings.

The idea

A payment request carries two text fields, an account number and an amount. The sender protects the request with a message authentication code §5.7 (MAC): a short tag computed from a secret key and the bytes of the message. If the sender simply concatenates the fields, writing one directly after the other, the request (account 12, amount 345) becomes the bytes 12345, and so does the request (account 123, amount 45). The tag is computed over bytes, so it is valid for both readings. An attacker who captured one tagged request can present it as the other, and the receiver’s check passes.

The flaw is that the receiver cannot tell where the first field ends. An encoding in which every field announces its own end removes the choice. In a prefix-free encoding, once the reader has read a complete codeword, no longer codeword can still be under way, so the reader stops there and the next symbol begins the next codeword. Telephone country calling codes work this way: no country code is the beginning of another, so the telephone network knows where the country code ends without any separator. The picture covers only the country code; the rest of a telephone number follows national rules.

How it works

Four techniques make the boundaries of variable-width fields recoverable.

A message made of several fields is decoded field by field.

  1. Read the next field’s length, or its self-delimiting header.

  2. Check that the stated length is no larger than the number of bytes that remain. If it is larger, reject the message.

  3. Take exactly that many bytes as the field’s content, and move past them.

  4. After the last field the format defines, check that no bytes remain. Leftover bytes mean that the message is malformed, and it is rejected.

The format’s specification must also fix the byte order §4.21 of every length that takes more than one byte, the unit in which lengths count (bytes, not characters or items), the largest allowed length, and the number, order and types of the fields.

Decoding in one way is not the same as encoding in one way. A prefix-free code guarantees that every byte string splits into codewords in at most one way. A canonical encoding guarantees, in addition, that each value has exactly one encoding. LEB128 is prefix-free but not canonical: the value 1 can be written as the single byte 01 or as the two bytes 81 00. UTF-8 forbids such overlong forms, and DER (Distinguished Encoding Rules), the encoding rules of ASN.1 (Abstract Syntax Notation One) that allow exactly one encoding per value, exist for the same reason. A signature, a hash or a duplicate check over encoded bytes needs both properties.

Worked example

Encode each field as one length byte, which allows 0 to 255 bytes of content, followed by the content in ASCII, in which the characters 1 to 5 are the bytes 31 to 35 in hexadecimal.

The two encodings have the same length but differ in their first byte. A tag computed over one therefore does not verify for the other, except by the chance of a guessed tag.

Decode 02 31 32 03 33 34 35, which is 7 bytes. Read the length byte 02: 7−1=67 - 1 = 6 bytes remain, and 2≤62 \le 6, so take 31 32, the text 12, which leaves 6−2=46 - 2 = 4 bytes. Read 03: 4−1=34 - 1 = 3 bytes remain, and 3≤33 \le 3, so take 33 34 35, the text 345, which leaves 0 bytes. Both fields are complete and nothing is left over. The input 05 31 32 is rejected at its first step: it announces 5 bytes, but only 3−1=23 - 1 = 2 remain.

A self-delimiting integer: encode 300 in LEB128. In binary, 300 is 1 0010 1100, since 256+32+8+4=300256 + 32 + 8 + 4 = 300. Its low 7 bits, 010 1100, are 32+8+4=4432 + 8 + 4 = 44. More bits remain, so the top bit of the first byte is set, which gives 44+128=17244 + 128 = 172, the byte AC in hexadecimal. The remaining bits are 300 divided by 128 and rounded down, which is 2, written as the byte 02 with top bit 0; that top bit marks the end. The codeword is AC 02, and a reader stops after 02 without looking at the bytes that follow.

Stated precisely

Let CC be a set of codewords, each a non-empty finite string of symbols. A string uu is a prefix of a string vv when vv consists of uu followed by zero or more further symbols, and a proper prefix when at least one further symbol follows. CC is prefix-free when no codeword in CC is a proper prefix of another codeword in CC.

Unique decoding: if CC is prefix-free and u1u2…up=v1v2…vqu_1 u_2 \dots u_p = v_1 v_2 \dots v_q with every uiu_i and every vjv_j in CC, then p=qp = q and ui=viu_i = v_i for every ii. The reason: u1u_1 and v1v_1 both begin the same string, so the shorter of the two is a prefix of the longer. A proper prefix is forbidden, so u1=v1u_1 = v_1. Remove it from both sides and repeat. Because codewords are non-empty, neither side can run out while the other still has symbols.

The length-prefixed code is prefix-free. Let xx be a byte string of at most 255 bytes, let |x||x| be its length in bytes, and define E(x)=len(x)‖xE(x) = \mathrm{len}(x) \mathbin{\Vert} x, where len(x)\mathrm{len}(x) is the single byte holding |x||x| and a‖ba \mathbin{\Vert} b means aa followed by bb. If E(x)E(x) were a prefix of E(y)E(y), their first bytes would agree, so |x|=|y||x| = |y|. Then E(x)E(x) and E(y)E(y) both have 1+|x|1 + |x| bytes, and a prefix as long as the whole string is the whole string, so E(x)=E(y)E(x) = E(y) and x=yx = y. By unique decoding, the tuple encoding E(x1)‖…‖E(xk)E(x_1) \mathbin{\Vert} \dots \mathbin{\Vert} E(x_k) with a fixed number kk of fields maps different tuples to different byte strings. The argument assumes a decoder that accepts exactly this format: it rejects a length larger than the remaining input, and it rejects leftover bytes.

Kraft’s inequality limits how short the codewords of a prefix-free code can be: over an alphabet of DD symbols (D=2D = 2 for bits, 256 for bytes), the codeword lengths l1,…,lml_1, \dots, l_m satisfy ∑i=1mD−li≤1\sum_{i=1}^{m} D^{-l_i} \le 1. So a binary prefix-free code cannot have three codewords of length 1, since 3×2−1=1.5>13 \times 2^{-1} = 1.5 > 1, while {0,10,11}\{0, 10, 11\} meets the limit exactly: 2−1+2−2+2−2=12^{-1} + 2^{-2} + 2^{-2} = 1. Prefix-freeness is sufficient for unique decoding but not necessary. The code {0,01}\{0, 01\} is not prefix-free, because 0 begins 01, yet every string of its codewords splits in only one way; its reader must look ahead to find where a codeword ends, which a prefix-free code never requires.

Limits and common mistakes

Prefix-free fields do not by themselves make a message unambiguous. The decoder must know how many fields there are and of which types. If the number of fields can vary, the message needs a count, an overall length or an end marker.

The same bytes can mean different things in two kinds of message. A tag computed over the encoded fields must also cover the message type and its context, for example through a domain label §5.22: a fixed string, naming the purpose, that is included in the authenticated bytes. This practice is called domain separation.

Unique decoding is not unique encoding. Overlong integers, leading zeros, repeated fields, different Unicode normalization forms §15.19 of the same text, and optional trailing bytes each give one value several encodings. A hash or signature then differs for equal values, and a duplicate check misses repeats. Require a canonical encoding, or compare decoded values.

A length prefix is data an attacker controls. Check it against the remaining bytes and against a maximum before copying or reserving memory, with an overflow-safe range check §4.17: a comparison written so that its own arithmetic cannot overflow.

A delimiter without an escaping rule is not prefix-free. A comma inside a field breaks a line of comma-separated values, and a zero byte inside a C string ends the string early.

Prefix-freeness concerns parsing only. It says nothing about whether the sender may ask for what the message requests.

Questions answered

How do lengths or self-delimiting encodings separate adjacent variable-width fields?

They tell the reader where each field ends before the reader reaches the next field, so the bytes split into fields in exactly one way. A length prefix states, in a fixed number of bytes at the start of the field, how many bytes of content follow; the reader takes exactly that many bytes, and the next byte begins the next field. A self-delimiting encoding marks its end inside the field itself: in LEB128 (Little Endian Base 128) integers, the top bit of each byte says whether another byte follows, and in UTF-8 the first byte of a character states how many bytes the character occupies. Both make the set of encoded fields prefix-free: no complete encoded field is the beginning of a longer one.

For example, with one length byte per field, the tuples (12, 345) and (123, 45) encode as 02 31 32 03 33 34 35 and 03 31 32 33 02 34 35, which differ, whereas plain concatenation gives 12345 for both. The separation holds only if the decoder rejects a length larger than the remaining bytes and rejects leftover bytes, and if the format fixes the number, order and types of the fields. When the message is authenticated, the authenticated bytes must also include the message type and its context.

Related entries: Authentication coverage (§5.41), Canonical JSON (§12.28), Deserialization (§4.29), Overflow-safe range check (§4.17), Length-prefix framing (§4.30), Type-length-value (TLV) (§4.31), Domain separation (§5.22), Unicode code points, scalar values, code units, and byte encodings (§12.48).