This guide shows how to redact protected health information (PHI) in HL7 v2 messages with Philter. Philter does not read HL7 messages directly, so a small script parses each message, handles each field by what it holds, and sends only the free text to Philter:
- Structured fields with a known meaning, such as the patient’s name (
PID-5) and birth date (PID-7), are replaced by rule, with no detection. A rule replaces a malformed or partial value that a detector could miss. - Identifiers that link records, such as the patient identifier list (
PID-3), get a keyed pseudonym, so messages for one patient still link after redaction. - Free-text fields, such as observation values (
OBX-5) and notes (NTE-3), go to Philter, which finds names, phone numbers, email addresses, dates, and other identifiers inside the text.
Everything runs in your own environment: Philter is open source and self-hosted, and no message leaves your network.
Redaction is probabilistic. Detection in free text reduces how much PHI gets through, but it does not catch every instance, so validate the output against your own messages before you rely on it.
Start Philter and load a policy
Start Philter and wait until it is healthy:
export PHILTER_ENCRYPTION_KEY="$(openssl rand -base64 32)"
export PHILTER_API_KEY="sk_$(openssl rand -hex 16)"
docker run -d --name philter -p 8080:8080 \
-e PHILTER_ENCRYPTION_KEY \
-e PHILTER_BOOTSTRAP_API_KEY="$PHILTER_API_KEY" \
-v philter-data:/opt/philter/data \
philterd/philter:4.0.1
until curl -skf https://localhost:8080/api/health > /dev/null; do sleep 2; done
Philter’s built-in default policy finds only person names, SSNs, and email addresses. Load the HIPAA Safe Harbor policy from the policy library instead, which also covers phone numbers, dates, addresses, and the other Safe Harbor identifiers:
curl -sfLO https://raw.githubusercontent.com/philterd/pii-redaction-policies/main/policies/philterd/healthcare/hipaa-safe-harbor.json
curl -sk -X POST "https://localhost:8080/api/policies?name=hipaa-safe-harbor" \
-H "Authorization: Bearer $PHILTER_API_KEY" \
-H "Content-Type: application/json" \
--data-binary @hipaa-safe-harbor.json
The script
redact_hl7.py uses only the Python standard library. It reads the delimiters from each message’s MSH segment, decodes HL7 escape sequences before sending text to Philter, and encodes them again afterwards, so a & in a note stays \T\ in the output.
import hashlib
import hmac
import os
import ssl
import sys
import urllib.request
PHILTER_URL = os.environ.get("PHILTER_URL", "https://localhost:8080")
PHILTER_API_KEY = os.environ["PHILTER_API_KEY"]
PSEUDONYM_KEY = os.environ["PSEUDONYM_KEY"].encode()
POLICY = os.environ.get("PHILTER_POLICY", "default")
# Philter's default certificate is self-signed. Use your own certificate in production.
TLS = ssl.create_default_context()
TLS.check_hostname = False
TLS.verify_mode = ssl.CERT_NONE
# Structured fields replaced without detection: (segment, field) -> how.
CLEAR = "clear"
YEAR_ONLY = "year"
FIELD_RULES = {
("PID", 5): CLEAR, # patient name
("PID", 6): CLEAR, # mother's maiden name
("PID", 7): YEAR_ONLY, # date of birth
("PID", 11): CLEAR, # address
("PID", 13): CLEAR, # home phone
("PID", 14): CLEAR, # business phone
("PID", 19): CLEAR, # SSN
("NK1", 2): CLEAR, # next of kin name
("NK1", 4): CLEAR, # next of kin address
("NK1", 5): CLEAR, # next of kin phone
}
# Free-text fields sent to Philter for detection.
TEXT_FIELDS = {("OBX", 5), ("NTE", 3)}
TEXT_VALUE_TYPES = {"TX", "ST", "FT"} # OBX-2 values whose OBX-5 is text
def philter(text):
request = urllib.request.Request(
f"{PHILTER_URL}/api/filter?p={POLICY}",
data=text.encode("utf-8"),
headers={"Authorization": f"Bearer {PHILTER_API_KEY}", "Content-Type": "text/plain"},
)
with urllib.request.urlopen(request, context=TLS) as response:
return response.read().decode("utf-8")
def pseudonym(value):
# The same identifier always gets the same stand-in, so messages for one patient still link.
return hmac.new(PSEUDONYM_KEY, value.encode("utf-8"), hashlib.sha256).hexdigest()[:16]
class Delimiters:
def __init__(self, msh):
self.field = msh[3]
self.component, self.repetition, self.escape, self.subcomponent = msh[4:8]
def decode(self, text):
e = self.escape
codes = {"F": self.field, "S": self.component, "T": self.subcomponent,
"R": self.repetition, "E": self.escape}
out, i = [], 0
while i < len(text):
end = text.find(e, i + 1) if text[i] == e else -1
if end != -1 and text[i + 1:end] in codes:
out.append(codes[text[i + 1:end]])
i = end + 1
else:
out.append(text[i])
i += 1
return "".join(out)
def encode(self, text):
e = self.escape
text = text.replace(e, f"{e}E{e}")
for char, code in ((self.field, "F"), (self.component, "S"),
(self.subcomponent, "T"), (self.repetition, "R")):
text = text.replace(char, f"{e}{code}{e}")
return text
def redact_message(message):
segments = message.strip("\r\n").replace("\n", "\r").split("\r")
d = Delimiters(segments[0])
redacted = []
for segment in segments:
fields = segment.split(d.field)
name = fields[0]
# MSH-1 is the field separator itself, so MSH field n is at index n - 1.
offset = 1 if name == "MSH" else 0
for n in range(1, len(fields) + offset):
i = n - offset
if i < 1 or i >= len(fields) or not fields[i]:
continue
rule = FIELD_RULES.get((name, n))
if rule == CLEAR:
fields[i] = ""
elif rule == YEAR_ONLY:
fields[i] = fields[i][:4]
elif name == "PID" and n == 3:
ids = []
for repetition in fields[i].split(d.repetition):
components = repetition.split(d.component)
components[0] = pseudonym(components[0])
ids.append(d.component.join(components))
fields[i] = d.repetition.join(ids)
elif (name, n) in TEXT_FIELDS:
if name == "OBX" and fields[2] not in TEXT_VALUE_TYPES:
continue
fields[i] = d.repetition.join(
d.encode(philter(d.decode(r))) for r in fields[i].split(d.repetition))
redacted.append(d.field.join(fields))
return "\r".join(redacted) + "\r"
if __name__ == "__main__":
with open(sys.argv[1], newline="") as f:
sys.stdout.write(redact_message(f.read()).replace("\r", "\n"))
Run it
Given message.hl7, an ORU message with invented data (segments end with a carriage return, shown here on separate lines):
MSH|^~\&|LAB|GENERAL HOSPITAL|EHR|GENERAL HOSPITAL|20261201083000||ORU^R01|MSG00001|P|2.5.1
PID|1||MRN12345^^^GENHOSP^MR||Doe^Jane^Q||19800214|F|||123 Main St^^Springfield^IL^62701||(217) 555-0142||||||123-45-6789
NK1|1|Doe^John|SPO|123 Main St^^Springfield^IL^62701|(217) 555-0199
OBR|1||ORD789|CBC^Complete blood count
OBX|1|TX|NOTE^Clinical note||Patient Jane Doe reports fatigue. Her husband John Doe can be reached at (217) 555-0199 or john.doe@example.com.||||||F
OBX|2|NM|HGB^Hemoglobin||13.2|g/dL|12.0-16.0||||F
NTE|1||Discussed results with Dr. Alan Smith on 11/30/2026. CBC \T\ CMP ordered for follow-up.
Run the script with the Safe Harbor policy and a secret key for the pseudonyms:
export PSEUDONYM_KEY="example-secret-change-me"
PHILTER_POLICY=hipaa-safe-harbor python3 redact_hl7.py message.hl7
The first request loads the person-name model and takes a few seconds. Later requests are fast.
Output:
MSH|^~\&|LAB|GENERAL HOSPITAL|EHR|GENERAL HOSPITAL|20261201083000||ORU^R01|MSG00001|P|2.5.1
PID|1||131f18ea8c5e15b1^^^GENHOSP^MR||||1980|F|||||||||||
NK1|1||SPO||
OBR|1||ORD789|CBC^Complete blood count
OBX|1|TX|NOTE^Clinical note||Patient {{{REDACTED-name}}} reports fatigue. Her husband {{{REDACTED-name}}} can be reached at {{{REDACTED-phone-number}}} or {{{REDACTED-email-address}}}.||||||F
OBX|2|NM|HGB^Hemoglobin||13.2|g/dL|12.0-16.0||||F
NTE|1||Discussed results with Dr. {{{REDACTED-name}}} on {{{REDACTED-date}}}. CBC \T\ CMP ordered for follow-up.
The numeric observation (OBX-2 is NM) is not sent to Philter, and the escaped & in the note is kept. The MRN becomes 131f18ea8c5e15b1 every time it appears with the same PSEUDONYM_KEY, so the patient’s messages can still be joined. Keep that key secret: anyone who holds it can test a guessed MRN against the pseudonyms.
Adapting it to your feed
- Add rules for the fields your feed carries. The rules above cover
PIDandNK1only. Feeds also carry PHI in other places, such as admission and discharge dates and the attending physician inPV1, guarantor details inGT1, insurance inIN1, and the message timestamp inMSH-7. Add a rule or a text-field entry for each one, and for your site’s Z-segments. - Decide what a cleared field should become. The script leaves a cleared field empty, which keeps the message valid. If a receiving system requires a value, write a fixed placeholder instead.
- Run it where the messages already flow. An interface engine such as Mirth Connect, Iguana, or Corepoint can call the same logic in a transformer step, or send each free-text field to Philter’s API itself.
- Plan for volume. The script makes one request per free-text field. For a high-volume feed, run several Philter instances behind a load balancer.
Safe Harbor is more than redaction
HIPAA’s Safe Harbor method requires removing all 18 identifier types and having no actual knowledge that what remains could identify someone. Rules and detection help with the first part. The second is a judgment about your data that your privacy officer makes, so review a sample of redacted messages before you treat a feed as de-identified.
Native HL7 support
Philter takes HL7 content through this kind of script today. Field rules for HL7 v2 messages, written in the redaction policy itself, are proposed in philterd/phisql#97. Comment there if your organization would use them.