Algorithm Search⌘K

Algorithmcore

Context-triggered piecewise hashing

Also called CTPH, fuzzy hashing.

Cuts a file where a rolling hash of the last 7 bytes hits a trigger value, hashes each piece to one character, and compares files by the edit distance of these strings.

Time
O(n log n) worstO(n) average · best
Space
O(s) extra
Where
n = the number of bytes of the file; s = the maximum signature length (64)
Properties
not cryptographicdeterministiclocality preservingofflineiterative
Origin
Andrew Tridgell, Jesse Kornblum, 2006

Context-triggered piecewise hashing (CTPH) gives a file a short signature, such that two files that differ by a few local edits get similar signatures. A rolling hash over the last 7 bytes decides where a piece ends, as in Rabin fingerprinting. Each piece is hashed to one character, and the signature is the string of these characters. Two signatures are compared by an edit distance and give a score from 0 to 100. Kornblum (2006) published the method as ssdeep, based on Andrew Tridgell's spamsum. Forensic examiners and malware analysts use it to find files that are almost the same, for example two builds of one program, and it is one of the inputs of the malware detection problem. The examples and the code of this page use random byte strings and short sentences only.

In plain words

A cryptographic hash changes completely when one byte of a file changes. That is right for a password check, and wrong when you want to find files that are almost the same.

CTPH cuts the file into pieces and hashes each piece. The trick is where the cuts go. A small window slides over the file, and a cut goes where the hash of the window has a special value. The cut points depend only on the bytes near them. So after an edit, the cuts soon fall on the same bytes as before, and only the pieces near the edit change.

Each piece gives one character. Two files that share most pieces share most characters, in the same order. The score counts how much of the two strings is common.

The problem

The input is a byte string xx of length nn. The output is a signature (b,s1,s2)(b, s_1, s_2): a block size bb, a string s1s_1 of at most S=64S = 64 characters for block size bb, and a string s2s_2 of at most 32 characters for block size 2b2b. A second function takes two signatures and returns a score from 0 (no evidence of similarity) to 100 (the strings are equal). The aim is that a local edit of xx changes only a few characters of the signature, while two unrelated files almost never share a run of 7 characters. This is a form of near-duplicate detection for byte strings, where the MinHash method of web pages is the analogue for sets of words.

The algorithm

The constants are a window of 7 bytes, Bmin⁡=3B_{\min} = 3, S=64S = 64, a Base64 alphabet B64 of 64 characters, and the FNV prime p=0x01000193p = \texttt{0x01000193} with the start value 0x28021967\texttt{0x28021967} for the piece hash. The rolling hash keeps three 32-bit values: h1h_1, the sum of the window; h2h_2, the sum weighted 7, 6, ..., 1 from the newest byte; and h3h_3, a shift-and-XOR value. Its output is r=h1+h2+h3 mod 232r = h_1 + h_2 + h_3 \bmod 2^{32}. The piece hash step is h←(h⋅p mod 232)⊕ch \leftarrow (h \cdot p \bmod 2^{32}) \oplus c.

  1. CTPH-SIGNATURE(x) ▷ x has n bytes
  2. 1b ← B_min; while b·S < n do b ← 2b
  3. 2loop
  4. 3s1 ← "", s2 ← "", h1 ← h2 ← INIT, reset the rolling hash
  5. 4for each byte c of x do
  6. 5r ← ROLL(c); h1 ← h1·p xor c; h2 ← h2·p xor c
  7. 6if r mod b = b - 1 and |s1| < S - 1 then append B64[h1 mod 64] to s1; h1 ← INIT
  8. 7if r mod 2b = 2b - 1 and |s2| < S/2 - 1 then append B64[h2 mod 64] to s2; h2 ← INIT
  9. 8if bytes were read since the last cut of s1 (of s2) then append B64[h1 mod 64] to s1 (B64[h2 mod 64] to s2)
  10. 9if b > B_min and |s1| < S/2 then b ← b/2; continue
  11. 10return (b, s1, s2)
  12. CTPH-COMPARE((b, s1, s2), (b', t1, t2))
  13. 11if b = b' then return max(SCORE(s1, t1), SCORE(s2, t2))
  14. 12if b' = 2b then return SCORE(s2, t1)
  15. 13if b = 2b' then return SCORE(s1, t2)
  16. 14return 0 ▷ no strings of a common block size
  17. SCORE(u, v)
  18. 15cut each run of more than 3 equal characters in u and in v to 3
  19. 16if u and v have no common substring of length 7 then return 0
  20. 17d ← |u| + |v| - 2·LCS(u, v) ▷ the insert and delete distance
  21. 18return ⌊100·(|u| + |v| - d) / (|u| + |v|)⌋

Line L1 picks the smallest block size b=3⋅2kb = 3 \cdot 2^k with b⋅64≥nb \cdot 64 \ge n, so that about 64 triggers are expected. Lines L4 to L7 make one pass. A trigger for bb fires on average once in bb bytes, and line L6 closes the current piece there. Line L7 does the same for 2b2b, so s2s_2 has about half as many characters. The caps keep the strings short: after S−1S - 1 cuts, the rest of the file goes into the last piece, and line L8 emits it. If the pass gave fewer than 32 characters, the guess of bb was too large for this file, and line L9 halves bb and runs the pass again.

Two signatures can only be compared on strings of one block size, because a character means "a piece of about bb bytes". Lines L11 to L13 find the common block size. If the sizes differ by a factor of 4 or more, the score is 0. SCORE removes long runs, which come from repeated content such as padding, and then requires a common substring of 7 characters. This rule removes most chance matches between unrelated files. The score is ⌊200 LCS(u,v)/(∣u∣+∣v∣)⌋\lfloor 200\,\mathrm{LCS}(u,v)/(|u|+|v|) \rfloor, where LCS is the length of a longest common subsequence.

ssdeep uses a weighted edit distance and a different scale, and it caps the score of small block sizes. This page uses the plain form above. The code follows the structure of spamsum and ssdeep, but it does not claim output that is identical to ssdeep.

Example

Take xx = the quick brown fox (19 bytes). Line L1 gives b=3b = 3, because 3⋅64≥193 \cdot 64 \ge 19. The rolling values rr after each byte give 3-triggers (r mod 3=2r \bmod 3 = 2) at positions 2, 6, 11 and 12, and one 6-trigger (r mod 6=5r \bmod 6 = 5) at position 2.

piece bytes ends at rr at the end r mod 3r \bmod 3 character
1 the p = 2 124445 2 U
2 qui p = 6 3594639422 2 k
3 ck br p = 11 2483362040 2 L
4 o p = 12 2158072664 2 K
5 wn fox end of file (line L8) 1497864676 1 X

So s1s_1 = UkLKX. For 2b=62b = 6 the only cut is after the, so s2s_2 = UV: the first character is U again, because the piece the is the same. The signature is (3,UkLKX,UV)(3, \texttt{UkLKX}, \texttt{UV}). Line L9 does not halve, because b=Bmin⁡b = B_{\min}.

The string the quick brown cat has the signature (3,UkLK0,U+)(3, \texttt{UkLK0}, \texttt{U+}). The first four pieces are the same and only the last character changed. But the score is 0, because neither string has 7 characters (line L16). Even the identical signature UkLKX scores 0 against itself. CTPH is a method for files of some size, not for short strings.

A bigger example, from the test file: a random file of 20000 bytes gets b=384b = 384 (the smallest 3⋅2k3 \cdot 2^k with 64⋅3⋅2k≥2000064 \cdot 3 \cdot 2^k \ge 20000) and strings of 61 and 26 characters. Flip one byte at offset 5000, two bytes at offset 12000, and insert 13 bytes at offset 16000. Each of the three edits changes one character of s1s_1 and one of s2s_2. For s1s_1, LCS = 58, so the score is ⌊200⋅58/122⌋=95\lfloor 200 \cdot 58 / 122 \rfloor = 95. For s2s_2, LCS = 23 and the score is ⌊200⋅23/52⌋=88\lfloor 200 \cdot 23/52 \rfloor = 88. Line L11 returns 95. Two independent random files of 8000 bytes score 0 in all the tests.

Correctness

The key fact is that the rolling hash after byte pp is a function of xp−6…xpx_{p-6} \ldots x_p only: h1=∑j=06xp−jh_1 = \sum_{j=0}^{6} x_{p-j}, h2=∑j=06(7−j) xp−jh_2 = \sum_{j=0}^{6} (7-j)\,x_{p-j}, and h3h_3 is the XOR of xp−jx_{p-j} shifted by 5j5j places, cut to 32 bits. So the cut decision at pp depends only on the 7 bytes that end at pp. If an edit replaces x[i…j]x[i \ldots j], every cut before ii and every cut after j+6j + 6 is still a cut, shifted by the change in length. Pieces that lie fully outside this zone keep their bytes and their character. So the two strings have the form A M BA\,M\,B and A M′ BA\,M'\,B, with MM and M′M' about as long as the number of cuts near the edit plus one, as long as no cap is reached. The loop stops because bb halves only while b>Bmin⁡b > B_{\min}, and the score is symmetric, lies in [0,100][0, 100], and is 100 only for equal strings. The full proof is in the proofs folder.

Proof: CTPH cuts a file only on local context, so a local edit changes only a few signature charactersfull

We write x=x0x1…xn−1x = x_0 x_1 \ldots x_{n-1} for the input bytes and set xp=0x_p = 0 for p<0p < 0. All arithmetic on the hash values is modulo 2322^{32}. The block size bb is fixed inside one pass of lines L3 to L8. A position pp is a bb-trigger of xx if the value rpr_p that line L5 computes after byte xpx_p satisfies rp mod b=b−1r_p \bmod b = b - 1.

Lemma 1 (the rolling hash is a function of the last 7 bytes). After line L5 has read xpx_p, the three parts of the rolling hash are

h1=∑j=06xp−j,h2=∑j=06(7−j) xp−j,h3=⨁j=06(xp−j⋅25j mod 232),h_1 = \sum_{j=0}^{6} x_{p-j}, \qquad h_2 = \sum_{j=0}^{6} (7 - j)\, x_{p-j}, \qquad h_3 = \bigoplus_{j=0}^{6} \left( x_{p-j} \cdot 2^{5j} \bmod 2^{32} \right),

so rp=h1+h2+h3r_p = h_1 + h_2 + h_3 depends only on xp−6…xpx_{p-6} \ldots x_p.

Proof. By induction on pp. Before the first byte all parts are 0 and the window holds zeros, which is the formula for p=−1p = -1 with the convention xq=0x_q = 0 for q<0q < 0. Assume the formulas after xp−1x_{p-1}. The window slot p mod 7p \bmod 7 holds xp−7x_{p-7}, the byte that leaves. The update of h2h_2 uses the old h1h_1:

h2′=∑j=06(7−j) xp−1−j−∑j=06xp−1−j+7xp=7xp+∑j=06(6−j) xp−1−j=∑i=06(7−i) xp−i,h_2' = \sum_{j=0}^{6} (7-j)\, x_{p-1-j} - \sum_{j=0}^{6} x_{p-1-j} + 7 x_p = 7 x_p + \sum_{j=0}^{6} (6-j)\, x_{p-1-j} = \sum_{i=0}^{6} (7-i)\, x_{p-i},

where the last step puts i=j+1i = j + 1 and drops the term i=7i = 7, whose weight is 0. The update of h1h_1 adds xpx_p and subtracts xp−7x_{p-7}, which gives the sum of xp−6…xpx_{p-6} \ldots x_p. The update of h3h_3 shifts every term left by 5 places and XORs in xpx_p. A byte that was read 7 or more steps ago has been shifted by at least 35 places, so the mask 232−12^{32} - 1 removes it. □\square

Lemma 2 (cuts are context triggered). Whether pp is a bb-trigger depends only on xp−6…xpx_{p-6} \ldots x_p and bb.

Proof. Immediate from Lemma 1. □\square

Lemma 3 (what a pass computes). Let t1<t2<⋯t_1 < t_2 < \cdots be the bb-triggers of xx and let t1′<t2′<⋯t'_1 < t'_2 < \cdots be its 2b2b-triggers. When line L8 ends, s1s_1 is the string of the characters B64[H(piece) mod 64]\mathrm{B64}[H(\text{piece}) \bmod 64] for the pieces x[0…t1],x[t1+1…t2],…x[0 \ldots t_1], x[t_1+1 \ldots t_2], \ldots, where the first S−1S-1 pieces end at triggers and one last piece holds the rest of xx if the rest is not empty. Here HH is the piece hash started from HASH_INIT. The same holds for s2s_2 with the 2b2b-triggers and the cap S/2−1S/2 - 1.

Proof. Line L5 updates h1h_1 with every byte, line L6 resets it right after it emits a character, and line L3 sets it to HASH_INIT at the start. So when line L6 emits at a trigger tit_i, h1h_1 is the piece hash of the bytes since the last emission. Line L6 emits at every bb-trigger until ∣s1∣=S−1|s_1| = S - 1 and never after. Line L8 emits the hash of the bytes after the last emission if there are any; the flag open1 of the code is true exactly then. □\square

So ∣s1∣≤S|s_1| \le S and ∣s2∣≤S/2|s_2| \le S/2, which is the postcondition of the code.

Theorem 4 (a local edit is local in the signature). Let x′x' be xx with the part x[i…j]x[i \ldots j] replaced by a string ww, so the bytes before ii are equal and the bytes after jj in xx are the bytes after i+∣w∣−1i + |w| - 1 in x′x'. Fix a block size bb and assume that xx and x′x' both have fewer than S−1S - 1 bb-triggers. Then the strings s1s_1 of xx and of x′x' for this bb have the form A M BA\,M\,B and A M′ BA\,M'\,B, where AA and BB are common, ∣M∣|M| is at most one more than the number of bb-triggers of xx in [i,j+6][i, j+6], and ∣M′∣|M'| is at most one more than the number of bb-triggers of x′x' in [i,i+∣w∣+5][i, i + |w| + 5].

Proof. Let δ=∣w∣−(j−i+1)\delta = |w| - (j - i + 1). For p<ip < i the 7 bytes ending at pp are the same in xx and x′x', so by Lemma 2 the bb-triggers below ii are the same. For p>j+6p > j + 6 the 7 bytes ending at pp in xx are the 7 bytes ending at p+δp + \delta in x′x', so pp is a trigger of xx exactly when p+δp + \delta is a trigger of x′x'. By Lemma 3, with no cap reached, the pieces are the intervals between consecutive triggers, and the last piece runs to the end.

A piece of xx that ends at a trigger below ii is a piece of x′x' with the same bytes, so it gives the same character; these pieces form AA. A piece of xx whose previous trigger is above j+6j + 6 (so it starts after j+7j + 7) has the same bytes as the piece of x′x' that starts δ\delta later, and it also ends at the matching trigger or at the end of the file; these pieces form BB. Every other piece of xx contains a byte of [i,j+6][i, j+6] or starts right after a trigger in that range, and the number of these pieces is at most the number of triggers in [i,j+6][i, j+6] plus one. The same count holds in x′x'. □\square

The same statement holds for s2s_2 with the 2b2b-triggers. So LCS(s,s′)≥∣A∣+∣B∣\mathrm{LCS}(s, s') \ge |A| + |B| and the distance of line L17 on the raw strings is at most ∣M∣+∣M′∣|M| + |M'|. Line L15 removes characters only from runs of more than 3 equal characters, and it does this in the same way inside AA and BB; the bound is a statement about the raw signatures, and the run cut can change it only near the borders of MM and M′M'.

Lemma 5 (termination and cost). CTPH-SIGNATURE stops, and it makes at most 1+log⁡2(b0/Bmin⁡)1 + \log_2 (b_0 / B_{\min}) passes, where b0b_0 is the block size of line L1.

Proof. Line L1 ends because bb doubles and nn is finite. In the loop of line L2, each repeat comes from line L9, which needs b>Bmin⁡b > B_{\min} and halves bb. The block size is always Bmin⁡B_{\min} times a power of 2, so it reaches Bmin⁡B_{\min} after at most log⁡2(b0/Bmin⁡)\log_2(b_0 / B_{\min}) halvings, and then line L9 does not repeat. Each pass reads each byte once and does O(1)O(1) work per byte. □\square

Lemma 6 (the score). For strings uu and vv after line L15, SCORE returns 0 if they share no substring of length 7, and otherwise ⌊200 LCS(u,v)/(∣u∣+∣v∣)⌋\lfloor 200\, \mathrm{LCS}(u, v) / (|u| + |v|) \rfloor. This value is symmetric in uu and vv, lies in [0,100][0, 100], and equals 100 exactly when u=vu = v.

Proof. Line L17 gives ∣u∣+∣v∣−d=2 LCS(u,v)|u| + |v| - d = 2\,\mathrm{LCS}(u, v), which turns line L18 into the formula. LCS is symmetric. Since LCS(u,v)≤min⁡(∣u∣,∣v∣)≤(∣u∣+∣v∣)/2\mathrm{LCS}(u, v) \le \min(|u|, |v|) \le (|u| + |v|)/2, the value is at most 100, with equality exactly when LCS=∣u∣=∣v∣\mathrm{LCS} = |u| = |v|, that is when u=vu = v. If line L16 passes, both strings have length at least 7, so the division is defined. □\square

Theorem 7 (correctness). CTPH-SIGNATURE stops and returns (b,s1,s2)(b, s_1, s_2) as described by Lemma 3 for the block size bb the loop ends with, and CTPH-COMPARE returns a score in [0,100][0, 100] that compares only strings made with the same block size.

Proof. Termination and the form of the output are Lemmas 5 and 3. Line L11 compares s1s_1 with t1t_1 (both of block size bb) and s2s_2 with t2t_2 (both 2b2b). Line L12 handles bB=2bAb_B = 2 b_A, where s2s_2 of the first signature and t1t_1 of the second both have block size 2bA2 b_A; line L13 is the mirror case. Any other pair of block sizes has no string of a common block size, and line L14 returns 0. Each score is in [0,100][0, 100] by Lemma 6. ■\blacksquare

Complexity

One pass of lines L4 to L8 reads each byte once and does O(1)O(1) word operations per byte, so it takes Θ(n)\Theta(n) time. Line L1 makes at most log⁡2(n/192)+1\log_2(n/192) + 1 doublings, and line L9 can halve as many times, so the worst case is O(nlog⁡n)O(n \log n). The halving is rare in practice: with bb chosen by line L1, about n/bn/b triggers are expected and n/bn/b is between 32 and 64, so one or two passes are typical. This is an observation on random-like data, not a bound. The extra space is the window of 7 bytes and the two strings, O(S)O(S).

CTPH-COMPARE computes at most two LCS tables of at most 64×6464 \times 64 cells, which is O(S2)O(S^2) time, a constant. A search of one signature against NN stored signatures is O(NS2)O(N S^2), and an index of the 7-character substrings of the stored strings cuts this to the candidates that can score above 0.

The model is the word RAM with 32-bit words; all hash arithmetic is modulo 2322^{32}.

Properties

  • Local. A local edit changes only the pieces next to it (the theorem of the proof). This is the property that a cryptographic hash does not have on purpose.
  • Self-synchronizing. After an insertion or a deletion, the cuts move with the bytes, so the rest of the signature is the same. A fixed block size would shift every later block.
  • Deterministic, not random. There is no seed. Two runs on the same file give the same signature.
  • Not a proof of relation. A score of 0 says that the method found no evidence of similarity. It does not say the files are unrelated. A high score is strong evidence for honest edits only.
  • Not robust against an adversary. The trigger rule is public, so a person who changes a file on purpose can make the signature differ. Research on the security of similarity digests is a separate subject.

Variants and improvements

  • Block size choice. Kornblum's paper gives binit=Bmin⁡⋅2⌊log⁡2(n/(S Bmin⁡))⌋b_{init} = B_{\min} \cdot 2^{\lfloor \log_2(n / (S\, B_{\min})) \rfloor}, with a floor. Breitinger and Baier observe that the implementation uses the ceiling, which is what line L1 computes. For a random file of 24000 bytes line L1 gives b=384b = 384.
  • Two passes in all cases. Breitinger and Baier (2011) count the triggers of the four block sizes 2binit2b_{init}, binitb_{init}, binit/2b_{init}/2 and binit/4b_{init}/4 in one pass and store their offsets. A second pass then hashes the pieces of the largest block size that gives at least 32 characters. They report a gain of about 55% in run time on their test image. The same counts show a file with far more triggers than expected, which can be a sign of a file changed on purpose to fill the cap of 64 characters.
  • Bloom filter signatures. Roussev and coauthors replaced the rolling hash by the polynomial hash djb2 and the piece hash by MD5, and put 11 bits of each MD5 value into a Bloom filter. A comparison then counts common bits instead of a string distance. djb2 must be computed again for each window, so this is slower.
  • Set-based digests. MinHash over the piece hashes, or over byte n-grams, estimates the Jaccard similarity of the two sets and works with locality-sensitive hashing for large collections. SimHash gives a fixed-length bit string instead.

When to use it

Use CTPH to find almost identical files in a large collection: versions of one document, two builds of one program, a sample and its repacked copy if the packer kept most bytes. It is cheap, it needs one or two passes, and the signature is less than 100 characters. Do not use it on small files, which have fewer than 7 pieces and never match. Do not use it as evidence against a careful adversary. For files whose content moves around in large blocks, a set-based digest finds more matches than a string distance.

Pitfalls

  • Comparing strings of different block sizes. Writing return SCORE(s1, t1) in place of lines L11 to L14 compares pieces of different average length, and two copies of one file whose sizes are on two sides of a doubling point get a low score. Compare only strings of a common block size, as lines L12 and L13 do.
  • Not resetting the piece hash. Without h1 ← INIT in line L6, each character is the hash of the whole prefix, and one edit changes every later character. Reset the piece hash at each cut.
  • A trigger that depends on the whole prefix. Line L5 must use a rolling hash of the window. A hash such as r ← r·31 + c without removing the old byte makes each cut depend on all earlier bytes, and the signature no longer synchronizes after an edit.
  • Forgetting the last piece. Without line L8, two files that differ only after the last cut get equal signatures.
  • Reading 0 as "different". Line L16 returns 0 for any string shorter than 7 characters, so two identical small files score 0. Check the signature length before you use the score.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

context_triggered_piecewise_hashing.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/context-triggered-piecewise-hashing/. The authors are listed in prov/PW1KEF.jsonl.

"""Context-triggered piecewise hashing (CTPH), after Kornblum (2006) and spamsum.

A rolling hash over the last 7 bytes decides where a piece ends. Each piece
gets a small FNV-style hash, and the low 6 bits of that hash become one
Base64 character of the signature. Two signatures are compared with a score
from 0 to 100 that comes from the longest common subsequence of the two
character strings. The code follows the structure of spamsum and ssdeep but
does not claim output that is identical to ssdeep; the score of SCORE is the
simpler one that the page defines. The code works on byte strings that the
caller gives; it never opens a file.
"""

WINDOW = 7
B_MIN = 3
S = 64
HASH_INIT = 0x28021967
FNV_PRIME = 0x01000193
MASK = 0xFFFFFFFF
B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"

Signature = tuple[int, str, str]


class RollingHash:
    """The rolling hash of spamsum over a window of WINDOW bytes, mod 2^32."""

    def __init__(self) -> None:
        self.h1 = 0  # sum of the bytes in the window
        self.h2 = 0  # sum of the bytes times their weight 7, 6, ..., 1
        self.h3 = 0  # shift and xor of the recent bytes
        self.window = [0] * WINDOW
        self.n = 0

    def roll(self, c: int) -> int:
        """Add byte c, drop the byte that leaves the window, return the hash. Cost: O(1)."""
        self.h2 = (self.h2 - self.h1 + WINDOW * c) & MASK
        self.h1 = (self.h1 + c - self.window[self.n % WINDOW]) & MASK
        self.window[self.n % WINDOW] = c
        self.n += 1
        self.h3 = ((self.h3 << 5) & MASK) ^ c
        return (self.h1 + self.h2 + self.h3) & MASK


def piece_hash(h: int, c: int) -> int:
    """One step of the FNV-style piece hash of spamsum. Cost: O(1)."""
    return ((h * FNV_PRIME) & MASK) ^ c


def ctph_signature(x: bytes) -> Signature:
    """Return (b, s1, s2): the block size and the signatures for b and 2b.

    Precondition: x is a byte string of length n. Postcondition: len(s1) <= S
    and len(s2) <= S // 2. Cost: O(n) per pass and at most
    O(log(n / (B_MIN S)) + 1) passes, so O(n log n) in the worst case.
    """
    n = len(x)
    b = B_MIN  # @line L1
    while b * S < n:
        b *= 2
    while True:  # @line L2
        s1: list[str] = []  # @line L3
        s2: list[str] = []
        h1 = h2 = HASH_INIT
        r = RollingHash()
        open1 = open2 = False
        for c in x:  # @line L4
            v = r.roll(c)  # @line L5
            h1 = piece_hash(h1, c)
            h2 = piece_hash(h2, c)
            open1 = open2 = True
            if v % b == b - 1 and len(s1) < S - 1:  # @line L6
                s1.append(B64[h1 % 64])
                h1, open1 = HASH_INIT, False
            if v % (2 * b) == 2 * b - 1 and len(s2) < S // 2 - 1:  # @line L7
                s2.append(B64[h2 % 64])
                h2, open2 = HASH_INIT, False
        if open1:  # @line L8
            s1.append(B64[h1 % 64])
        if open2:
            s2.append(B64[h2 % 64])
        if b > B_MIN and len(s1) < S // 2:  # @line L9
            b //= 2
            continue
        return b, "".join(s1), "".join(s2)  # @line L10


def ctph_compare(sig_a: Signature, sig_b: Signature) -> int:
    """Similarity score from 0 to 100 of two signatures. Cost: O(S^2), a constant."""
    b, s1, s2 = sig_a
    bb, t1, t2 = sig_b
    if b == bb:  # @line L11
        return max(score(s1, t1), score(s2, t2))
    if bb == 2 * b:  # @line L12
        return score(s2, t1)
    if b == 2 * bb:  # @line L13
        return score(s1, t2)
    return 0  # @line L14


def cut_runs(u: str, k: int = 3) -> str:
    """Cut each run of more than k equal characters down to k. Cost: O(len(u))."""
    out: list[str] = []
    for ch in u:
        if len(out) >= k and all(o == ch for o in out[-k:]):
            continue
        out.append(ch)
    return "".join(out)


def has_common_substring(u: str, v: str, k: int = WINDOW) -> bool:
    """True if u and v share a substring of length k. Cost: O(k (len(u) + len(v)))."""
    subs = {u[i : i + k] for i in range(len(u) - k + 1)}
    return any(v[i : i + k] in subs for i in range(len(v) - k + 1))


def lcs_length(u: str, v: str) -> int:
    """Length of a longest common subsequence, by dynamic programming. Cost: O(len(u) len(v))."""
    prev = [0] * (len(v) + 1)
    for a in u:
        cur = [0]
        for j, c in enumerate(v):
            cur.append(prev[j] + 1 if a == c else max(prev[j + 1], cur[j]))
        prev = cur
    return prev[-1]


def score(u: str, v: str) -> int:
    """Score of two signature strings of one block size, from 0 to 100."""
    u, v = cut_runs(u), cut_runs(v)  # @line L15
    if not has_common_substring(u, v):  # @line L16
        return 0
    d = len(u) + len(v) - 2 * lcs_length(u, v)  # @line L17
    return (100 * (len(u) + len(v) - d)) // (len(u) + len(v))  # @line L18
test_context_triggered_piecewise_hashing.py 159 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/context-triggered-piecewise-hashing/. The authors are listed in prov/PW1KEF.jsonl.

import itertools
import random
from functools import lru_cache

from context_triggered_piecewise_hashing import (
    B64,
    B_MIN,
    FNV_PRIME,
    HASH_INIT,
    MASK,
    S,
    RollingHash,
    ctph_compare,
    ctph_signature,
    score,
)


def rolling_closed_form(x: bytes, p: int) -> int:
    """The rolling hash after byte p, from the last 7 bytes only."""
    last = [x[p - j] if p - j >= 0 else 0 for j in range(7)]
    h1 = sum(last)
    h2 = sum((7 - j) * last[j] for j in range(7)) & MASK
    h3 = 0
    for j in range(7):
        h3 ^= (last[j] << (5 * j)) & MASK
    return (h1 + h2 + h3) & MASK


def fnv_from_scratch(piece: bytes) -> int:
    h = HASH_INIT
    for c in piece:
        h = ((h * FNV_PRIME) & MASK) ^ c
    return h


def signature_for(x: bytes, b: int, cap: int) -> str:
    """Cut x after each trigger position of block size b, up to cap pieces that end at a trigger."""
    values = [rolling_closed_form(x, p) for p in range(len(x))]
    cuts = [p for p, v in enumerate(values) if v % b == b - 1][:cap]
    out, start = [], 0
    for p in cuts:
        out.append(B64[fnv_from_scratch(x[start : p + 1]) % 64])
        start = p + 1
    if start < len(x):
        out.append(B64[fnv_from_scratch(x[start:]) % 64])
    return "".join(out)


def oracle_signature(x: bytes) -> tuple[int, str, str]:
    b = B_MIN
    while b * S < len(x):
        b *= 2
    while True:
        s1 = signature_for(x, b, S - 1)
        s2 = signature_for(x, 2 * b, S // 2 - 1)
        if b > B_MIN and len(s1) < S // 2:
            b //= 2
            continue
        return b, s1, s2


def oracle_score(u: str, v: str) -> int:
    def cut(w: str) -> str:
        return "".join(ch * min(3, len(list(g))) for ch, g in itertools.groupby(w))

    u, v = cut(u), cut(v)
    if not any(u[i : i + 7] == v[j : j + 7] for i in range(len(u) - 6) for j in range(len(v) - 6)):
        return 0

    @lru_cache(maxsize=None)
    def lcs(i: int, j: int) -> int:
        if i == len(u) or j == len(v):
            return 0
        if u[i] == v[j]:
            return 1 + lcs(i + 1, j + 1)
        return max(lcs(i + 1, j), lcs(i, j + 1))

    return (200 * lcs(0, 0)) // (len(u) + len(v))


def random_bytes(rng: random.Random, n: int, alphabet: int = 256) -> bytes:
    return bytes(rng.randrange(alphabet) for _ in range(n))


def test_rolling_hash_depends_on_last_seven_bytes() -> None:
    rng = random.Random(1)
    for _ in range(500):
        x = random_bytes(rng, rng.randrange(1, 40))
        r = RollingHash()
        for p, c in enumerate(x):
            assert r.roll(c) == rolling_closed_form(x, p)


def test_signature_matches_oracle() -> None:
    rng = random.Random(2)
    for t in range(500):
        n = rng.randrange(0, 300) if t < 480 else rng.randrange(300, 2500)
        x = random_bytes(rng, n, rng.choice([2, 4, 256]))
        assert ctph_signature(x) == oracle_signature(x)


def test_signature_lengths_and_block_size() -> None:
    rng = random.Random(3)
    for n in (0, 1, 100, 191, 192, 193, 5000, 24000):
        b, s1, s2 = ctph_signature(random_bytes(rng, n))
        assert len(s1) <= S and len(s2) <= S // 2
        assert b >= B_MIN and (b // B_MIN) & (b // B_MIN - 1) == 0
    assert ctph_signature(random_bytes(random.Random(4), 24000))[0] == 384


def test_score_matches_oracle() -> None:
    rng = random.Random(5)
    for _ in range(500):
        u = "".join(rng.choice("ABCD") for _ in range(rng.randrange(0, 14)))
        v = "".join(rng.choice("ABCD") for _ in range(rng.randrange(0, 14)))
        if rng.random() < 0.5 and len(u) >= 7:
            v = u[: rng.randrange(7, len(u) + 1)] + v
        assert score(u, v) == oracle_score(u, v)


def test_identical_and_short_inputs() -> None:
    x = random_bytes(random.Random(6), 3000)
    sig = ctph_signature(x)
    assert ctph_compare(sig, sig) == 100
    tiny = b"abcde"
    small = ctph_signature(tiny)
    assert len(small[1]) < 7
    assert ctph_compare(small, small) == 0


def test_small_edit_keeps_a_high_score() -> None:
    rng = random.Random(7)
    x = random_bytes(rng, 20000)
    y = bytearray(x)
    for p in (5000, 12000, 12001):
        y[p] ^= 0xFF
    y[16000:16000] = b"inserted text"
    assert ctph_compare(ctph_signature(x), ctph_signature(bytes(y))) >= 80


def test_unrelated_inputs_score_zero() -> None:
    rng = random.Random(8)
    for _ in range(5):
        x, y = random_bytes(rng, 8000), random_bytes(rng, 8000)
        assert ctph_compare(ctph_signature(x), ctph_signature(y)) == 0


def test_neighbouring_block_sizes_are_compared() -> None:
    rng = random.Random(9)
    x = random_bytes(rng, 10000)
    y = x + random_bytes(rng, 4000)
    a, b = ctph_signature(x), ctph_signature(y)
    assert b[0] == 2 * a[0]
    assert ctph_compare(a, b) == score(a[2], b[1]) > 0
    assert ctph_compare(a, (8 * a[0], a[1], a[2])) == 0

History

Andrew Tridgell wrote the rolling checksum of rsync, and then spamsum, which cut e-mail text at points chosen by a rolling hash and compared the strings of piece hashes to find similar spam. Jesse Kornblum adapted spamsum to files of any size and published it as context triggered piecewise hashing at DFRWS 2006, with the tool ssdeep. Breitinger and Baier (2011) described the algorithm in detail, made it faster, and discussed how an active adversary can change a signature. Later work in digital forensics compared ssdeep with other similarity digests.

References

  1. Jesse Kornblum, Identifying almost identical files using context triggered piecewise hashing, Digital Investigation 3S (DFRWS 2006), pages S91 to S97, the whole paper (the rolling hash, the trigger rule, the block size, the two signatures and the comparison)
  2. Frank Breitinger and Harald Baier, Performance issues about context-triggered piecewise hashing, ICDF2C 2011, Springer LNICST, 2012, Section 3.2 (Algorithm 1, the rolling hash; the trigger rule; the block size formula and the halving rule) and Section 4

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • at least three sources
  • a scene preset for the example