Algorithmadvanced
Privacy-preserving record linkage with Bloom filters
Also called Bloom filter record linkage, PPRL.
Encodes the q-grams of each identifier into a keyed Bloom filter and links records across parties by the Dice similarity of the filters.
- Time
- O((n + r) l (q + k) + n r m / w) worst
- Space
- O((n + r) m / w) extra
- Where
- k = the number of hash functions; l = the longest identifier; m = the filter length in bits; n = the records of the first party; q = the q-gram length; r = the records of the second party; w = the word size
- Model
- Word RAM
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Rainer Schnell, Tobias Bachteler, Joerg Reiher, 2009
Two data owners, such as a hospital and a cancer registry, want to find the records that belong to the same person, but they may not share names or birth dates. Exact pseudonyms do not work, because names are often misspelled and one wrong letter changes a keyed hash completely. The method of Schnell, Bachteler and Reiher (2009) encodes each identifier as a Bloom filter: it splits the identifier into q-grams, such as the bigrams of a name, and sets bits of an -bit vector for each q-gram, at positions from HMAC under keys that only the data owners know. Similar names share most q-grams, so their filters share most bits. A third party, the linkage unit, receives only the filters and compares every pair by the Dice coefficient . It reports the pairs at or above a threshold. The method is fast and tolerant of errors. It is not secure in a cryptographic sense: the encoding is deterministic, and published attacks recover q-grams from the filters through their frequencies.
In plain words
Two offices each have a list of people. They want to know which people are on both lists, but neither may show its names. Names are also typed with mistakes, so "Smith" and "Smyth" should still match.
Each office cuts every name into pairs of letters. For each pair, a secret rule that both offices share picks a few boxes in a long row, and the office ticks them. It sends only the rows of ticks to a third office. Names that look alike have most letter pairs in common, so their rows have most ticks in the same boxes. The third office counts the shared ticks for every pair of rows and reports the pairs that share enough. It never sees a name, and without the secret rule it cannot directly check a guessed name. But the ticks still carry patterns, so the rows must be protected too.
The problem
Party holds records and party holds records , each with an identifier such as a name. The goal is the set of pairs that refer to the same person, with errors in the identifiers allowed. A linkage unit does the comparison. The usual adversary model, as in the taxonomy of Vatsalan, Christen and Verykios (2013), is honest-but-curious: follows the protocol but tries to learn identifiers from what it receives. and share the keys and the parameters, and does not know the keys.
The output is a list of candidate pairs with their similarity. Deciding which candidates are true matches is the usual record linkage problem of entity resolution, for example with the Fellegi-Sunter model on several fields. The threshold , the filter length and the number of hash functions are chosen by the users. Schnell et al. use 30 bits and 2 hash functions in their worked example and fix no threshold.
The algorithm
Lines L1 to L5 run at each data owner, on its own records. Lines L6 to L10 run at the linkage unit, which sees only the filters.
PPRL-LINK(A, B, K1, K2, k, m, q, theta)- 1
for each record x of A and of B, at its owner, compute F_x as follows - 2
G ← the q-grams of NORMALIZE(x), padded with q - 1 blanks on each side - 3
F_x ← m zero bits - 4
for each g in G and each i in 0 .. k - 1 do - 5
set bit (h1(g) + i · h2(g)) mod m of F_x, where h1 = HMAC-SHA1 under K1 and h2 = HMAC-MD5 under K2 - 6
M ← an empty list - 7
for each pair (a, b) in A × B do - 8
s ← 2 |F_a ∧ F_b| / (|F_a| + |F_b|) - 9
if s ≥ theta then append (a, b, s) to M - 10
return M
Line L5 is double hashing. Kirsch and Mitzenmacher (2008) showed that, for set membership, it has the same asymptotic false positive rate as independent hash functions. The pad at line L2 marks the first and last letters, so the bigram "_s" says that a name starts with "s".
Example
Take , , , the made-up keys demo-key-1 and demo-key-2, and the names smith, smyth and jones. The bigrams and their positions are:
| name | bigrams and bit positions | bits set |
|---|---|---|
| smith | s: 15, 4; sm: 12, 12; mi: 18, 0; it: 9, 4; th: 5, 20; h: 8, 20 | 0, 4, 5, 8, 9, 12, 15, 18, 20 |
| smyth | s: 15, 4; sm: 12, 12; my: 7, 22; yt: 11, 19; th: 5, 20; h: 8, 20 | 4, 5, 7, 8, 11, 12, 15, 19, 20, 22 |
| jones | j: 26, 4; jo: 23, 22; on: 14, 16; ne: 6, 9; es: 9, 28; s: 21, 9 | 4, 6, 9, 14, 16, 21, 22, 23, 26, 28 |
- smith and smyth share 4 of their 6 bigrams each, so the Dice coefficient of the bigram sets is . Their filters have 9 and 10 bits and share 6, so the Dice coefficient of the filters is .
- smith and jones share no bigram, but their filters share bits 4 and 9 by collision, and their Dice coefficient is . smyth and jones share bits 4 and 22 and get .
- With , the linkage of smith and jones against smyth and Jones returns (smith, smyth) with and (jones, Jones) with 1, because the normalization at line L2 changes "Jones" to lower case.
- With and , the same keys give for smith and smyth and for smith and jones. A longer filter has fewer collisions.
The bigram "sm" sets one bit only, because its is a multiple of 30. Bits 4 and 20 are each set by two bigrams of smith. The test file checks all these values.
Correctness
The filter of an identifier is the union of the positions of its q-grams, so it depends only on the set of q-grams. Equal normalized identifiers give equal filters with Dice coefficient 1. Every q-gram that two identifiers share contributes the same bits to both filters, so shared q-grams always give shared bits. Collisions can add more shared bits, so the Dice coefficient of the filters is an estimate of the Dice coefficient of the q-gram sets, never below what the shared q-grams give. The linkage loop compares each pair once and returns exactly the pairs at or above . If the keyed hash functions are pseudorandom, a party without the keys cannot compute the filter of a guessed name. The full proof is in proofs/correctness.md.
Proof: The Bloom filter encoding keeps the shared q-grams, and the linkage returns exactly the pairs at or above the thresholdfull
Fix the keys , the number of hash functions , the filter length and the q-gram length . Lines L1 to L10 are those of the page. For a string , let be the set of q-grams of line L2, taken after normalization and padding. For a q-gram , let and , read as integers, and let
We identify a Bloom filter with the set of positions of its 1 bits. For a set of q-grams, write .
Lemma 1 (the encoding). Lines L2 to L5 produce the filter , and . If or is not empty, the filter is not empty.
Proof. Line L3 starts with the empty set. Lines L4 and L5 add the positions for each , and nothing else, so at the end the filter is the union . The order of the q-grams does not matter, because union is commutative and idempotent. Each has between 1 and elements, which gives the upper bound. The padded string has length , which is at least if or , so then has at least one q-gram and the filter at least one bit.
Theorem 1 (equal identifiers). If two strings have the same normalized form, or more generally the same q-gram set, then their filters are equal, and if the filter is not empty, their Dice coefficient at line L8 is 1.
Proof. By Lemma 1 the filter depends only on . For a nonempty filter , .
Theorem 2 (shared q-grams give shared bits). For any two strings , . So the number of common bits is at least .
Proof. is monotone: implies . Apply it to and .
The converse fails: a position can be in both filters because two different q-grams map to it. This is why the Dice coefficient of the filters is only an estimate of the Dice coefficient of the q-gram sets, and it is never smaller than the value from shared q-grams alone. How close the estimate is depends on , and the number of q-grams, and it is a measured property.
Theorem 3 (the linkage). Line L10 returns exactly the pairs with , each with its coefficient, in the order of line L7.
Proof. Line L1 computes the filter of every record by Lemma 1. Line L7 visits each pair once. Line L8 computes exactly, with rational arithmetic in the implementation. Line L9 appends the pair if and only if the value is at least . Nothing else changes .
Theorem 4 (what the keys give). Assume that and under the secret keys are pseudorandom functions. Then, to a party without the keys, the map is indistinguishable from a map that draws two independent uniform integers for each q-gram and applies the same double hashing. In particular, such a party cannot compute the filter of a guessed identifier and compare it with a given filter.
Proof sketch. A distinguisher between the two maps that makes queries on q-grams gives a distinguisher between the HMAC outputs and random functions with the same advantage, because is computed from and by a fixed public map.
Remark. Theorem 4 is about guessing single identifiers. It does not say that the filters hide the identifiers. The encoding is deterministic, so the same q-gram always sets the same bits, and the frequencies of bit patterns over many records follow the frequencies of q-grams in the population. The published attacks on Bloom filter encodings use this, as the survey of Vidanage, Ranbaduge, Christen and Schnell (2022) describes. This is why the page lists hardening methods, and why the keys alone are not a privacy guarantee.
Complexity
Let and be the numbers of records, the length of the longest identifier, the q-gram length, the number of hash functions, the filter length and the word size of the word RAM.
- Encoding one identifier takes time for the q-grams and for the bit positions, counting one HMAC call as one step, so in all.
- One Dice coefficient takes word operations, with a population count per word. The full comparison of all pairs takes .
- The filters need words.
The comparison of all pairs dominates for large files. In practice, blocking reduces it: only pairs that agree on a coarse key, or whose filters fall into the same bucket of a MinHash style index, are compared. Blocking can miss true matches, and its loss is a measured property.
Properties
- Error tolerance. One wrong letter changes at most q-grams, so similar strings get similar filters. How the filter Dice tracks the q-gram Dice depends on , and the length of the identifiers, and it is measured on data.
- One-sided error from collisions. Shared q-grams always give shared bits. Collisions only add shared bits, so the filter Dice is never lower than the part due to shared q-grams. This is a theorem.
- No exact privacy guarantee. The linkage unit cannot compute the filter of a guessed identifier without the keys. This is a theorem if HMAC is a pseudorandom function. It does not mean that the filters hide the identifiers: the encoding is deterministic, and the frequencies of bit patterns follow those of q-grams. The attacks on this are published, as the taxonomy of Vidanage, Ranbaduge, Christen and Schnell (2022) describes.
- The linkage unit learns the similarity of every pair. This is part of the output, and it is leaked by design.
Variants and improvements
- Record-level filters. Encode several fields, such as first name, last name and birth date, into one filter, with a separate key or a different for each field. It gives one similarity per record, and as a heuristic it makes frequency analysis harder than one filter per field.
- Hardening. Later work adds random noise to the bits, balances the number of 1 bits between filters, or folds a filter onto itself by XOR. Each method trades linkage quality for resistance to some attacks; the taxonomy of attacks discusses which attack each one stops.
- Other similarities. The Jaccard similarity satisfies for the Dice coefficient , so it ranks the pairs in the same order. The Hamming distance gives the same order only for filters with equal numbers of 1 bits.
- Cryptographic protocols. For exact matching on equal pseudonyms, private set intersection or secure multiparty computation give proved security. Protocols for approximate matching with proved security usually cost much more than Bloom filter encodings.
- Without a linkage unit. In two-party variants, one data owner compares the filters. That party then holds both filters and the keys, so the protection is weaker.
When to use it
Use Bloom filter linkage when two or more data owners must link records with typing errors, under a legal setting that forbids sharing identifiers with the linkage unit, and when the cost of a cryptographic protocol is too high for the size of the files. Use the Fellegi-Sunter model or a classifier on the similarity of several fields to decide matches. Do not treat the filters as anonymous data. They need the same access control as pseudonymized identifiers, and the linkage unit must be trusted not to attack them. If exact matching on clean identifiers is enough, use keyed pseudonymization or a set intersection protocol instead.
Pitfalls
- A filter that is too short at line L3. With few bits, unrelated names share many bits by collision, as smith and jones do in the example with 30 bits, and the threshold must rise until true matches with errors fail it.
- that is a multiple of at line L5. All positions of that q-gram are then the same bit, as for "sm" in the example. This weakens the filter for that q-gram. A safer form maps to a value in first.
- Missing normalization at line L2. Case, spaces, accents and the order of name parts change the q-grams. Agree on one normalization for all parties.
- One filter per field with the same key everywhere. A filter of a single common field, such as a first name, repeats across many records, and its frequency then matches the frequency of the name in the population. Use record-level encodings, field-specific keys and hardening.
- Reusing the keys across projects. Filters from two projects with the same keys can be joined by anyone who holds both. Use new keys for each project.
- Treating the threshold as a privacy parameter. trades false matches against missed matches. It has no effect on privacy, and its value is a choice tested on data.
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.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/privacy-preserving-record-linkage/. The authors are listed in prov/KHENH3.jsonl.
"""Privacy-preserving record linkage with Bloom filters, after Schnell, Bachteler and Reiher (2009).
Each data owner normalizes an identifier, splits it into q-grams padded with q - 1
copies of a pad character on each side, and sets k bits for each q-gram in a bit
vector of length m. Bit i of a q-gram g is (h1(g) + i * h2(g)) mod m, where h1 is
HMAC-SHA1 and h2 is HMAC-MD5 under two secret keys. A Bloom filter is a Python int
used as a bit vector. The linkage unit compares filters by the Dice coefficient
2 |a and b| / (|a| + |b|) and keeps the pairs at or above a threshold.
The keys must come from a cryptographic source of randomness and must stay secret
from the linkage unit. This encoding is known to leak information through the
frequencies of q-grams; see the page for the defenses.
"""
import hashlib
import hmac
from fractions import Fraction
from typing import Sequence
def normalize(s: str) -> str:
"""Lower case, with runs of white space replaced by one space and the ends trimmed."""
return " ".join(s.lower().split())
def qgrams(s: str, q: int = 2, pad: str = "_") -> list[str]:
"""The distinct q-grams of s padded with q - 1 pad characters on each side, in order of first use.
Precondition: q >= 1 and pad is one character. Cost: O(q len(s)).
"""
if q < 1 or len(pad) != 1:
raise ValueError("need q >= 1 and a pad of one character")
t = pad * (q - 1) + s + pad * (q - 1)
seen: dict[str, None] = {}
for i in range(len(t) - q + 1):
seen.setdefault(t[i : i + q], None)
return list(seen)
def _h(key: bytes, g: str, algo: str) -> int:
return int.from_bytes(hmac.new(key, g.encode("utf-8"), algo).digest(), "big")
def positions(g: str, key1: bytes, key2: bytes, k: int, m: int) -> list[int]:
"""The k bit positions of the q-gram g by double hashing with HMAC-SHA1 and HMAC-MD5."""
a = _h(key1, g, "sha1")
b = _h(key2, g, "md5")
return [(a + i * b) % m for i in range(k)]
def encode(s: str, key1: bytes, key2: bytes, k: int, m: int, q: int = 2) -> int:
"""The Bloom filter of the identifier s, as an int with m bits.
Precondition: k >= 1, m >= 1, q >= 1. Cost: O(len(s) (q + k)) HMAC calls and bit operations.
"""
if k < 1 or m < 1:
raise ValueError("need k >= 1 and m >= 1")
grams = qgrams(normalize(s), q) # @line L2
f = 0 # @line L3
for g in grams: # @line L4
for p in positions(g, key1, key2, k, m):
f |= 1 << p # @line L5
return f
def dice(a: int, b: int) -> Fraction:
"""The Dice coefficient of two bit vectors, 0 if both are empty. Cost: O(m / w) word operations."""
total = a.bit_count() + b.bit_count()
if total == 0:
return Fraction(0)
return Fraction(2 * (a & b).bit_count(), total)
def link(
left: Sequence[str],
right: Sequence[str],
key1: bytes,
key2: bytes,
k: int,
m: int,
theta: Fraction,
q: int = 2,
) -> list[tuple[int, int, Fraction]]:
"""All pairs (i, j, s) with s = dice(encode(left[i]), encode(right[j])) >= theta, in order of i and j.
In a real linkage, each data owner encodes its own records with the shared keys,
and only the filters go to the linkage unit, which runs the comparison loop.
Precondition: 0 <= theta <= 1. Cost: O((n + r) l (q + k)) for encoding n + r
identifiers of length at most l, and O(n r m / w) for the comparisons.
"""
fl = [encode(s, key1, key2, k, m, q) for s in left] # @line L1
fr = [encode(s, key1, key2, k, m, q) for s in right]
matches: list[tuple[int, int, Fraction]] = [] # @line L6
for i, a in enumerate(fl): # @line L7
for j, b in enumerate(fr):
s = dice(a, b) # @line L8
if s >= theta: # @line L9
matches.append((i, j, s))
return matches # @line L10
test_privacy_preserving_record_linkage.py 124 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/privacy-preserving-record-linkage/. The authors are listed in prov/KHENH3.jsonl.
import hashlib
import hmac
import random
from fractions import Fraction as F
from privacy_preserving_record_linkage import dice, encode, link, normalize, positions, qgrams
# Made-up keys for the tests only. A real linkage draws its keys from a cryptographic source.
K1 = b"demo-key-1"
K2 = b"demo-key-2"
SYLLABLES = ["ka", "lo", "mi", "ne", "ru", "sa", "to", "vi", "ze", "po", "an", "el", "or"]
def made_up_name(rng: random.Random) -> str:
return "".join(rng.choice(SYLLABLES) for _ in range(rng.randint(2, 4)))
def typo(rng: random.Random, s: str) -> str:
i = rng.randrange(len(s))
return s[:i] + rng.choice("abcdefghijklmnopqrstuvwxyz") + s[i + 1 :]
def oracle_bits(s: str, k: int, m: int, q: int = 2) -> set[int]:
"""An independent encoding: the set of bit positions, from a set of q-grams."""
t = "_" * (q - 1) + " ".join(s.lower().split()) + "_" * (q - 1)
grams = {t[i : i + q] for i in range(len(t) - q + 1)}
bits = set()
for g in grams:
h1 = int(hmac.new(K1, g.encode(), hashlib.sha1).hexdigest(), 16)
h2 = int(hmac.new(K2, g.encode(), hashlib.md5).hexdigest(), 16)
bits |= {(h1 + i * h2) % m for i in range(k)}
return bits
def oracle_dice(x: set[int], y: set[int]) -> F:
return F(2 * len(x & y), len(x) + len(y)) if x or y else F(0)
def test_page_example() -> None:
assert qgrams("smith") == ["_s", "sm", "mi", "it", "th", "h_"]
assert qgrams("ab", q=3) == ["__a", "_ab", "ab_", "b__"]
assert normalize(" Smith Jones ") == "smith jones"
assert positions("sm", K1, K2, 2, 30) == [12, 12]
smith, smyth, jones = (encode(s, K1, K2, 2, 30) for s in ("smith", "smyth", "jones"))
assert {i for i in range(30) if smith >> i & 1} == {0, 4, 5, 8, 9, 12, 15, 18, 20}
assert {i for i in range(30) if smyth >> i & 1} == {4, 5, 7, 8, 11, 12, 15, 19, 20, 22}
assert {i for i in range(30) if jones >> i & 1} == {4, 6, 9, 14, 16, 21, 22, 23, 26, 28}
assert dice(smith, smyth) == F(12, 19)
assert dice(smith, jones) == F(4, 19)
assert dice(smyth, jones) == F(1, 5)
assert link(["smith", "jones"], ["smyth", "Jones"], K1, K2, 2, 30, F(3, 5)) == [(0, 0, F(12, 19)), (1, 1, F(1))]
# A longer filter with more hash functions.
a, b = encode("smith", K1, K2, 15, 1000), encode("smyth", K1, K2, 15, 1000)
assert dice(a, b) == F(61, 89)
def test_against_oracle() -> None:
rng = random.Random(41)
for _ in range(500):
k = rng.randint(1, 6)
m = rng.choice([16, 30, 64, 200])
x = made_up_name(rng)
y = typo(rng, x) if rng.random() < 0.5 else made_up_name(rng)
fx, fy = encode(x, K1, K2, k, m), encode(y, K1, K2, k, m)
ox, oy = oracle_bits(x, k, m), oracle_bits(y, k, m)
assert {i for i in range(m) if fx >> i & 1} == ox
assert fx < 1 << m
assert dice(fx, fy) == oracle_dice(ox, oy)
def test_link_against_brute_force() -> None:
rng = random.Random(2009)
for _ in range(20):
left = [made_up_name(rng) for _ in range(rng.randint(1, 8))]
right = [typo(rng, s) if rng.random() < 0.6 else made_up_name(rng) for s in left]
rng.shuffle(right)
theta = F(rng.randint(3, 9), 10)
want = []
for i, s in enumerate(left):
for j, t in enumerate(right):
d = oracle_dice(oracle_bits(s, 10, 500), oracle_bits(t, 10, 500))
if d >= theta:
want.append((i, j, d))
assert link(left, right, K1, K2, 10, 500, theta) == want
def test_properties() -> None:
rng = random.Random(7)
for _ in range(200):
s = made_up_name(rng)
f = encode(s, K1, K2, 15, 500)
# Equal identifiers after normalization give equal filters and Dice 1.
assert encode(" " + s.upper() + " ", K1, K2, 15, 500) == f
assert dice(f, f) == 1
# At most k bits per q-gram.
assert f.bit_count() <= 15 * len(qgrams(s))
# The bits of the shared q-grams are shared bits.
t = typo(rng, s)
g = encode(t, K1, K2, 15, 500)
for gram in set(qgrams(s)) & set(qgrams(t)):
for p in positions(gram, K1, K2, 15, 500):
assert f >> p & 1 and g >> p & 1
assert 0 <= dice(f, g) <= 1 and dice(f, g) == dice(g, f)
# Other keys give other filters.
assert encode("smith", b"other-key-1", K2, 2, 30) != encode("smith", K1, K2, 2, 30)
assert dice(0, 0) == 0
def test_bad_parameters() -> None:
for args in ((0, 30, 2), (2, 0, 2)):
try:
encode("smith", K1, K2, args[0], args[1], args[2])
except ValueError:
pass
else:
raise AssertionError("expected ValueError")
try:
qgrams("smith", q=0)
except ValueError:
pass
else:
raise AssertionError("expected ValueError")
History
Burton Bloom introduced the Bloom filter in 1970 for set membership with a small rate of false positives. Linkage on encrypted or hashed identifiers needs exact agreement of the identifiers. Schnell, Bachteler and Reiher (2009) proposed Bloom filters of bigrams with keyed double hashing, in the form of Kirsch and Mitzenmacher, to allow errors, and evaluated the linkage quality on simulated and real data. Vatsalan, Christen and Verykios (2013) placed the method in a taxonomy of PPRL techniques. Since then, several attacks on Bloom filter encodings and several hardening methods have been published, and Vidanage et al. (2022) gave a taxonomy of the attacks.
References
- Rainer Schnell, Tobias Bachteler and Joerg Reiher, Privacy-preserving record linkage using Bloom filters, BMC Medical Informatics and Decision Making 9, article 41, 2009, the encoding of padded bigrams into a Bloom filter by double hashing with HMAC-SHA1 and HMAC-MD5, the Dice coefficient of filters, the worked example with 2 hash functions and 30 bits, and the evaluation on simulated and real data
- Dinusha Vatsalan, Peter Christen and Vassilios S. Verykios, A taxonomy of privacy-preserving record linkage techniques, Information Systems 38(6), 2013, pp. 946 to 969, the parties, the adversary models and the classes of PPRL techniques
- Anushka Vidanage, Thilina Ranbaduge, Peter Christen and Rainer Schnell, A taxonomy of attacks on privacy-preserving record linkage, Journal of Privacy and Confidentiality 12(1), 2022, the classes of published attacks on PPRL encodings and the conditions they need
- Burton H. Bloom, Space/time trade-offs in hash coding with allowable errors, Communications of the ACM 13(7), 1970, pp. 422 to 426, the Bloom filter
- Adam Kirsch and Michael Mitzenmacher, Less hashing, same performance, building a better Bloom filter, Random Structures and Algorithms 33(2), 2008, pp. 187 to 218, bit positions by double hashing g_i = h_1 + i h_2 and its false positive rate
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag KHENH3 Edit this page History Report an error Markdown