Canonicalization is the process of converting input data into a single, standard, unambiguous representation before it is processed by a security filter or machine learning model. This defensive technique prevents attackers from bypassing prompt injection defenses by using alternate encodings—such as URL encoding, Unicode homoglyphs, or zero-width characters—that appear different to a parser but resolve to the same malicious string.
Glossary
Canonicalization

What is Canonicalization?
Canonicalization is a critical security process that converts data into a single, standard, unambiguous representation to prevent attackers from bypassing security filters using encoding tricks.
In the context of LLM security, canonicalization is applied to user prompts before they are combined with system instructions. By resolving all characters to a base form and stripping invisible control sequences, the system ensures that a guard model or input sanitization filter evaluates the true semantic content of the input, closing a common evasion vector in the prompt injection kill chain.
Key Properties of Effective Canonicalization
Effective canonicalization is the bedrock of input validation. It eliminates the ambiguity that attackers exploit through encoding tricks, ensuring that security filters evaluate the true, intended meaning of data rather than a manipulated representation.
Idempotency
The canonicalization function must produce the same output regardless of how many times it is applied. Applying the function once must yield the same result as applying it ten times.
- Property:
f(x) = f(f(x)) - Why it matters: Prevents attackers from using recursive encoding (e.g., double URL-encoding) to bypass a single-pass filter.
- Example: If
%2527decodes to%27, a second pass decodes it to'. An idempotent function resolves it to'in a single, atomic operation.
Lossless Normalization
The process must preserve the semantic meaning of the input while reducing it to its simplest form. No critical data should be destroyed during normalization.
- Key distinction: Converting
../to its canonical path is lossless for path resolution, but stripping it entirely is lossy and dangerous. - Example: Unicode normalization forms like NFC vs. NFD. Choosing the wrong form can break string comparisons, but the chosen form must consistently represent the same abstract characters.
Single Coherent Representation
The system must define and enforce one true representation for every data type. There can be no ambiguity about which form is the standard.
- File paths: A single canonical form (e.g., absolute path with no trailing slashes or dot segments).
- Unicode: A single normalization form (NFC or NFKC) enforced at the boundary.
- JSON keys: A strict ordering and whitespace policy.
- Why it matters: If
adminandADMINare treated as distinct, an attacker can registerADMINto impersonate theadminuser.
Boundary Enforcement
Canonicalization must occur at the trust boundary—the exact point where data crosses from an untrusted zone to a trusted one. It is not a step to be deferred.
- Rule: Convert to canonical form before validation, never after.
- Anti-pattern: Validating a filename for path traversal characters, then later decoding it for storage.
- Example: A web application firewall must canonicalize a request's URL and body before applying its rule set, otherwise an encoded attack like
%2e%2e%2fpasses through undetected.
Recursive Resolution
The algorithm must fully resolve all layers of encoding and nested representations until a raw, atomic form is reached. Partial resolution is a security vulnerability.
- Process: Decode URL-encoding -> Decode HTML entities -> Normalize Unicode -> Resolve path traversal.
- Attack vector: An attacker sends
%253Cscript%253E. A single decode pass yields%3Cscript%3E, which is still benign to a naive filter. A second pass yields<script>. Recursive resolution catches this on the first pass.
Deterministic Output
Given the same input byte stream, the canonicalization function must always produce the exact same output, on every platform, in every environment.
- No system call variance: Relying on the local file system's
realpath()can yield different results on different OS kernels. - No locale dependence: String case-folding must use a locale-independent method (e.g.,
toUpperCase(Locale.ROOT)in Java) to avoid the 'Turkish I' problem. - Why it matters: A distributed system where different nodes canonicalize the same input differently creates a security gap that an attacker can exploit by targeting a specific node.
Frequently Asked Questions
Explore the critical defensive technique of canonicalization, which converts input into a single, unambiguous representation to neutralize encoding-based attacks that bypass security filters.
Canonicalization is the process of converting input data into a single, standard, unambiguous representation—its 'canonical' form—before any security validation or processing occurs. It works by applying a series of normalization rules to resolve syntactic variations. For example, a file path like C:\Windows\..\Windows\System32 is canonicalized to C:\Windows\System32 by resolving the parent directory traversal. In the context of prompt injection defense, canonicalization decodes multi-layered encoding tricks (like URL encoding, Unicode normalization, or HTML entities) to reveal the attacker's true payload. This ensures that a security filter sees the actual malicious string, not a cleverly obfuscated version designed to slip past pattern-matching rules.
Canonicalization vs. Related Input Processing Techniques
A comparison of canonicalization with other input processing techniques used in prompt injection defense, highlighting their distinct roles in the security pipeline.
| Feature | Canonicalization | Input Sanitization | Prompt Normalization |
|---|---|---|---|
Primary Objective | Convert input to a single, unambiguous representation | Remove or neutralize malicious control sequences | Rewrite prompts into a safe, canonical form before instruction combination |
Defense Stage | Pre-processing (normalization layer) | Pre-processing (cleaning layer) | Pre-processing (restructuring layer) |
Handles Encoding Tricks | |||
Handles Homoglyph Attacks | |||
Handles Zero-Width Characters | |||
Preserves Semantic Intent | |||
Output Format | Standardized byte/character sequence | Cleaned text with removed sequences | Restructured prompt text |
Risk of Over-Normalization | High — may collapse distinct inputs | Medium — may strip benign content | Low — preserves meaning while restructuring |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Related Terms
Canonicalization is a foundational defense that converts input into a single, unambiguous representation. Explore the related techniques and attack vectors that form the broader prompt injection defense landscape.
Input Sanitization
The process of cleaning and normalizing user-provided text to remove or neutralize potentially malicious control sequences before model processing. This is the direct implementation layer where canonicalization logic is applied.
- Strips or encodes dangerous characters
- Normalizes Unicode to a single form (e.g., NFC)
- Validates against an allowed schema
- Prevents homoglyph attacks and zero-width character injection
Prompt Normalization
The process of rewriting or restructuring user prompts into a safe, canonical form before they are combined with system instructions. This goes beyond character-level canonicalization to address semantic structure.
- Reorders clauses to a standard template
- Removes redundant or obfuscating language
- Resolves multi-turn injection attempts
- Ensures delimiter-based defense boundaries remain intact
Homoglyph Attack
A technique that uses visually similar characters from different alphabets to bypass text-based filters while appearing normal to a human reviewer. Canonicalization is the primary defense.
- Replaces Latin 'a' with Cyrillic 'а' (U+0430)
- Evades keyword blocklists and pattern matching
- Mitigated by Unicode normalization (NFKC)
- Often combined with prompt injection payloads
Zero-Width Character Injection
An attack that inserts invisible Unicode characters into text to break tokenization or keyword filtering without being visible to the user. Canonicalization strips these characters before processing.
- Uses characters like U+200B (Zero-Width Space)
- Disrupts tokenizer boundaries
- Hides malicious strings from human review
- Defeated by stripping control characters during input sanitization
Delimiter-Based Defense
A mitigation technique that uses special character sequences to clearly separate untrusted user input from trusted system instructions. Canonicalization ensures these delimiters cannot be spoofed or escaped.
- Uses markers like
--- USER INPUT --- - Prevents prompt injection via boundary confusion
- Requires canonicalization to normalize delimiter-like user text
- Works in tandem with instructional hierarchy frameworks
Instructional Hierarchy
A safety framework that prioritizes system-level instructions over user-level or tool-level instructions to prevent lower-privilege inputs from overriding core directives. Canonicalization ensures privilege boundaries are unambiguous.
- System > User > Tool priority ordering
- Prevents privilege escalation via injection
- Relies on canonical input representation
- Core component of system prompt hardening strategies

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us