The Penn State extension that turns a clever defense into a cryptographically hardened one—and why it matters for every LLM agent in production.


In the arms race between LLM agent builders and prompt injection attackers, the attackers have held a stubborn advantage: adaptivity. Defenses get published; attackers study them, probe their edges, and craft payloads that slip through. Polymorphic Prompt Assembling (PPA) was supposed to change that calculus by randomizing the boundary markers that separate trusted system instructions from untrusted user input. It worked—mostly. But a structural vulnerability lurked inside the design: once a separator leaked from a model response, it stayed valid forever.

A new paper from Penn State researchers Nima Dorzhiev and Peng Liu—"Strengthening Polymorphic Prompt Assembling: Dynamic Separator Generation Against Emerging Prompt Injection Attacks" (ArXiv 2605.30534)—closes that gap with an elegant cryptographic fix that adds just 2.7 microseconds of overhead per request and requires zero model fine-tuning.

This is the story of how a small architectural change eliminates an entire class of adaptive attacks, and why it matters for anyone deploying LLM agents in adversarial environments.


The Problem PPA Was Built to Solve

LLM agents don't just chat—they orchestrate tool calls, retrieve documents, and act with growing autonomy. That autonomy depends on a clean separation between trusted system instructions and untrusted user inputs. Prompt injection attacks exploit the absence of this separation: adversarial text embedded in user data or retrieved documents overrides the agent's intended behavior.

The scale of the problem is staggering. Lupinacci et al. evaluated 18 state-of-the-art LLMs across three attack surfaces and found that 94.4% were vulnerable to direct prompt injections. More critically, 100% of models that resisted direct injection were compromised when the payload arrived via a peer agent—a vector they termed "Inter-Agent Trust Exploitation."

Enter Zhilong Wang and collaborators, who introduced PPA at DSN 2025 (the 55th IEEE/IFIP International Conference on Dependable Systems and Networks). Their insight was deceptively simple: instead of using fixed delimiters like ### BEGIN ### and ### END ### to wrap user input—which attackers can learn and exploit—randomly select a different separator pair from a pool for each request. The original implementation used 84 genetic-algorithm-optimized separator pairs, achieving attack success rates below 2% on GPT-3.5 and GPT-4 and ranking second on the PINT benchmark with 97.68% accuracy.

The open-source implementation lives at github.com/zhilongwang/LLMAgentProtector (6 stars, MIT license), with a PyPI package (llm-agent-protector v0.1.0) for easy installation. The repository includes a Python SDK and a Go SDK, making it accessible across tech stacks.

Here's how the original static PPA assembles a prompt:

from llmagentprotector import PolymorphicPromptAssembler

SYSTEM_PROMPT = (
    "Please summarize the following article from user.\n{user_input}\n"
)
TOPICS = "!!!SUMMARIZE THE ARTICLE FROM USER"

protector = PolymorphicPromptAssembler(SYSTEM_PROMPT, TOPICS)

# double_prompt_assemble: separates system and user prompts
system_prompt, user_prompt, canary = protector.double_prompt_assemble(
    user_input=USER_INPUT
)

# canary = (left_sep, right_sep) — used for leak detection
response = await call_gpt(system_prompt, user_prompt)
prompt_leaked = protector.leak_detect(response, canary)

Under the hood, the static mode simply picks a random pair from the hardcoded pool:

# From polymorphic_prompt_assembler.py (static mode)
def double_prompt_assemble(self, user_input=None):
    left_sep, right_sep = random.choice(self.SEPARATORS)
    self.secure_user_prompt = (
        self.FORMAT_CONSTRAIN.format(left_sep=left_sep, right_sep=right_sep)
        + "\n\n" + left_sep + "\n" + user_input + "\n" + right_sep + "\n"
    )
    return self.secure_system_prompt, self.secure_user_prompt, (left_sep, right_sep)

The SEPARATORS pool in config.py contains 84 hand-crafted delimiter pairs—strings like ===++===++===++===++, ~~~===~~~===~~~===~~~, and ###########[BEGIN]###########—each designed to be visually distinct and unlikely to appear in natural text.


The Blast-Radius Bug

Here's the critical vulnerability: the pool is fixed and finite. Under static PPA, if a separator leaks from one model response, that delimiter remains valid for all future requests. An attacker who observes a separator from one interaction can reuse it to craft targeted bypass payloads in subsequent interactions.

This isn't theoretical. Dorzhiev and Liu's evaluation found that in 100 static-mode requests, the system exhibited a maxobservedseparator_reuse of 8—meaning some separator pairs were reused up to 8 times. Out of 100 requests, 46 used a previously-seen pair. Each reuse is a window of opportunity.

The "blast radius" of a single leak is the entire future of that separator's validity. It's an architectural property of static selection that's independent of separator quality. No matter how clever your 84 separators are, once one is burned, it's burned for every future request that happens to draw it.

Consider a concrete attack scenario: an attacker submits a carefully crafted input that causes the model to echo back the =====BEGIN- portion of the separator in its response. The leak_detect() method catches this—but the attacker now knows that separator. On the next request, they can craft a payload that includes that exact separator, effectively telling the model "the user input ends here" and injecting their own instructions after it.


Dynamic Separators: Cryptographic Canaries

Dorzhiev and Liu's solution is beautifully simple: kill the pool entirely. Generate a unique separator pair for every single request.

Each request generates an independent (BEGIN, END) pair via domain-separated SHA-256 digests:

left  = ====BEGIN- || H_B[:24] || ====
right = ====END-   || H_E[:24] || ====

where:
  H_B = SHA-256("BEGIN:" || ts || sid || nonce)
  H_E = SHA-256("END:"   || ts || sid || nonce)

Here's what each component does:

  • ts: Nanosecond-resolution timestamp via time.time_ns()
  • sid: UUIDv4 session identifier
  • nonce: 16 random bytes from secrets.token_hex(16)
  • Domain prefix ("BEGIN:" / "END:"): Ensures the two digests cannot collide even with identical inputs
  • Truncation to 24 hex characters (96 bits): Gives a collision probability below 2⁻⁹⁶ across the separator space

The resulting markers satisfy all PPA separator constraints: non-empty, single-line, bounded length (≤80 characters), and free of user-controlled raw text. A validate_separator() call enforces these properties at generation time.

Here's the core dynamic separator generation in Python:

import hashlib
import secrets
import time
import uuid

class DynamicSeparatorProvider:
    """
    Generates a unique (BEGIN, END) separator pair per request
    using domain-separated SHA-256 digests.
    """

    def __call__(self, sid: str = None):
        ts = time.time_ns()
        sid = sid or str(uuid.uuid4())
        nonce = secrets.token_hex(16)

        h_b = hashlib.sha256(
            f"BEGIN:{ts}{sid}{nonce}".encode()
        ).hexdigest()
        h_e = hashlib.sha256(
            f"END:{ts}{sid}{nonce}".encode()
        ).hexdigest()

        left  = f"====BEGIN-{h_b[:24]}===="
        right = f"====END-{h_e[:24]}===="

        # Validate separator constraints
        validate_separator(left)
        validate_separator(right)

        return (left, right)

Each invocation produces a fresh pair—even with a fixed session identifier—because ts and nonce change on every call. A leaked separator from one request is useless in any other request because it's request-scoped by construction.


Integration: Backward Compatible by Design

The extended PPA SDK accepts a separator_mode parameter ('static' | 'dynamic') and an optional rng for seeded static selection. All existing callers default to static mode; no API change is required for the upgrade.

# Static mode (default, backward compatible)
protector = PolymorphicPromptAssembler(
    system_prompt, task_topic, separator_mode='static'
)

# Dynamic mode (new)
protector = PolymorphicPromptAssembler(
    system_prompt, task_topic, separator_mode='dynamic'
)

# Both modes return the same interface
system_prompt, user_prompt, canary = protector.double_prompt_assemble(
    user_input=USER_INPUT
)

# Enhanced leak detection with per-side attribution
leak_detail = protector.leak_detect_detail(response, canary)
# Returns: {left: bool, right: bool, detected: bool}

The leakdetectdetail() method extends the original leak_detect() by reporting which boundary was echoed—left, right, or both—enabling more nuanced incident response.


The Numbers: A 2.3× Mitigation Against Adaptive Attacks

Dorzhiev and Liu evaluated the system against 16 injection payloads on Llama-3.3-70B-Instruct-Turbo (primary), with cross-model validation on DeepSeek-V4-Flash. The results are compelling.

M1 Injection (Leetspeak + Urgency Obfuscation)

This is the hardest test case—a post-publication payload from Lupinacci et al. that uses leetspeak obfuscation with urgency priming to bypass existing defenses.

Mode Attacked Defended ASR Leak Rate
Static 88 12 0.88 0
Dynamic 38 62 0.38 0

Dynamic mode reduces ASR from 0.88 to 0.38—a 2.3× mitigation. The 95% Wilson confidence intervals (static [0.802, 0.930] vs. dynamic [0.291, 0.478]) do not overlap, confirming statistical significance at N=100.

M2 Injection (Cognitive Override)

Mode Attacked Defended ASR Leak Rate
Static 9 91 0.09 0
Dynamic 0 100 0.00 0

Dynamic mode eliminates M2 entirely.

Format Breakout Salad (Separator Leakage)

This is where dynamic separators truly shine. The formatbreakoutsalad payload is specifically designed to cause the model to echo back separator boundaries.

Mode Leak Rate
Static 0.467
Dynamic 0.000

Static mode leaks separators nearly half the time. Dynamic mode eliminates separator leakage entirely—because even if a separator is echoed, it's useless for future requests.

Full Payload Sweep (N=30)

Across 14 additional payloads from Wang et al.'s attack registry, dynamic mode matched or improved static mode for every payload where static ASR was non-zero. The strongest result was payload_splitting, which dropped from static ASR 0.867 to dynamic ASR 0.133—a 6.5× reduction.

Separator Reuse Elimination

Metric Static Mode Dynamic Mode
Max separator reuse 8 1
Reused pairs out of 100 46 0
Unique separators ~54 100

Every dynamic-mode request gets a fresh, never-before-used separator pair. The blast radius of a single leak drops from "all future requests using this separator" to "this one specific request, which has already completed."


Cross-Model Validation: Where Dynamic Doesn't Help (Yet)

The cross-model validation on DeepSeek-V4-Flash tells an interesting story:

Mode ASR 95% Wilson CI
Static 0.45 [0.356, 0.548]
Dynamic 0.38 [0.291, 0.478]

The intervals overlap—the improvement isn't statistically significant on this backend. The authors interpret this correctly: dynamic separator benefit scales with baseline model susceptibility. When a model is already less susceptible to injection (lower baseline ASR), the marginal improvement from dynamic separators is smaller. The defense helps most where it's needed most.


The Overhead: Practically Free

Adding cryptographic separator generation to the prompt assembly pipeline costs 2.7 µs per request. For context, a single LLM API call typically takes 200–2000 ms. The overhead is five orders of magnitude below inference time. It requires:

  • No model fine-tuning
  • No additional API calls
  • No special hardware
  • No changes to the LLM serving infrastructure

The original PPA added 0.06 ms per request. The dynamic extension is 22× faster than even that minimal overhead. This is a defense you deploy not because you can afford it, but because you can't afford not to.


The Ecosystem: Where PPA Fits Among LLM Security Defenses

PPA and its dynamic extension occupy a specific niche in the LLM security landscape: prevention at the prompt assembly layer. This is distinct from—and complementary to—other defense categories:

Detection-Based Defenses (Input Filtering)

Tools like Lakera Guard, Azure AI Prompt Shield, Meta Prompt Guard, and ProtectAI's deberta-v3-base frame prompt injection as binary classification on input text. On the PINT benchmark, Lakera achieved 95.22% accuracy and Azure 89.12%. These operate at the input filtering layer—PPA enforces boundaries at the prompt assembly layer. A single request may benefit from both.

Prevention-Based Defenses (Prompt Structure)

Delimiter-based isolation uses fixed brackets; its static nature makes it vulnerable once the delimiter is known. SPIN introduced a self-supervised reversal mechanism with strong results but at a 5.8× inference latency penalty. Attack-inspired defenses invert injection strategies to reinforce instructions but are static. PPA remains the only randomized prevention mechanism with near-zero overhead.

Emerging Alternatives

The ecosystem is growing. prompt-guard by seojoonkim (152 stars) offers multi-language detection with severity scoring. AgentShield provides runtime security layers for LangChain, AutoGen, and CrewAI. ProtectAI's llm-guard (2,914 stars) is the established comprehensive toolkit. And a 2026 master's thesis from Halmstad University by Dennis Daniel Jesna Sunny—"A Hybrid Defense Against Prompt Injection in LLM Agents"—explicitly evaluates combining PPA with other approaches, finding that hybrid strategies offer the best security-efficacy/performance trade-offs.

The key insight: PPA is not a replacement for detection—it's a complement. Detection catches what looks malicious; PPA ensures that even if malicious input reaches the model, it can't cross the boundary between user input and system instructions.


Production Hardening: What's Next

The paper is refreshingly honest about the limitations of the current implementation. The authors explicitly note: "We do not claim cryptographic authentication strength in this study; HMAC-SHA256 with an application secret is the recommended production hardening step."

This is the right call. The current implementation uses bare SHA-256 with timestamp, session ID, and nonce as inputs. For production deployment, the recommended upgrade path is:

  1. HMAC-SHA256 with an application secret: Replace SHA-256("BEGIN:" || ts || sid || nonce) with HMAC-SHA256(secret, "BEGIN:" || ts || sid || nonce). This prevents an attacker who knows the generation algorithm from even verifying whether a guessed separator is valid.
  1. Key rotation: Rotate the HMAC secret periodically (daily or per-session) to limit the blast radius of a key compromise.
  1. Timing-safe comparison: When checking leaked separators in responses, use constant-time comparison to prevent timing side-channels.
  1. Monitoring and alerting: Use leakdetectdetail() to track which boundaries are being echoed, and alert on patterns that suggest active probing.

Why This Matters Now

The timing of this work is not coincidental. Three trends are converging:

  1. Agents are getting more autonomous. The gap between "read this document" and "execute this transaction" is shrinking. A prompt injection that hijacks an agent's tool-calling behavior can do real damage.
  1. Attacks are getting more adaptive. The Lupinacci payloads that motivated this work—leetspeak obfuscation, cognitive override, inter-agent trust exploitation—are specifically designed to defeat defenses published after the models were trained. They're adaptive.
  1. Compliance is getting stricter. As LLM agents move into regulated domains (finance, healthcare, legal), the bar for security evidence keeps rising. A defense with statistically significant Wilson intervals and a published evaluation harness is far more defensible than one that claims effectiveness based on vibes.

Dynamic separator generation turns PPA from a clever obfuscation trick into something approaching a proper security mechanism. The blast radius of a separator leak drops from "all future requests" to "one already-completed request." The overhead is negligible. The integration is backward compatible. There's no reason not to deploy this.


The Code You Need

If you're using the existing PPA SDK, upgrading to dynamic mode is a one-line change:

# Before (static mode, default)
protector = PolymorphicPromptAssembler(system_prompt, task_topic)

# After (dynamic mode)
protector = PolymorphicPromptAssembler(
    system_prompt, task_topic, separator_mode='dynamic'
)

If you're building from scratch or want the cryptographic implementation directly:

import hashlib
import secrets
import time
import uuid

def generate_dynamic_separators(sid: str = None):
    """
    Generate a unique per-request (BEGIN, END) separator pair
    using domain-separated SHA-256 digests.

    Production: replace with HMAC-SHA256 using an application secret.
    """
    ts = time.time_ns()
    sid = sid or str(uuid.uuid4())
    nonce = secrets.token_hex(16)

    h_b = hashlib.sha256(f"BEGIN:{ts}{sid}{nonce}".encode()).hexdigest()
    h_e = hashlib.sha256(f"END:{ts}{sid}{nonce}".encode()).hexdigest()

    left  = f"====BEGIN-{h_b[:24]}===="
    right = f"====END-{h_e[:24]}===="

    return (left, right)

# Usage
left, right = generate_dynamic_separators()
# Example output:
# left  = '====BEGIN-a3f8c2e1b9d04f7e2c6b8a3d===='
# right = '====END-7e2d4f6b8a1c3e9f0d5b7a2e===='

# Wrap user input
wrapped = f"{left}\n{user_input}\n{right}\n"

# Check for leaks in model response
def detect_leak(response, left, right):
    left_leaked = left in response
    right_leaked = right in response
    return {
        'left': left_leaked,
        'right': right_leaked,
        'detected': left_leaked or right_leaked
    }

For the full implementation with HMAC-SHA256 hardening:

import hmac

def generate_hmac_separators(secret_key: bytes, sid: str = None):
    """Production-hardened separator generation with HMAC-SHA256."""
    ts = time.time_ns()
    sid = sid or str(uuid.uuid4())
    nonce = secrets.token_hex(16)

    msg_b = f"BEGIN:{ts}{sid}{nonce}".encode()
    msg_e = f"END:{ts}{sid}{nonce}".encode()

    h_b = hmac.new(secret_key, msg_b, hashlib.sha256).hexdigest()
    h_e = hmac.new(secret_key, msg_e, hashlib.sha256).hexdigest()

    left  = f"====BEGIN-{h_b[:24]}===="
    right = f"====END-{h_e[:24]}===="

    return (left, right)

Key References

  • Original PPA Paper: Wang, Z., Nagaraja, N., Zhang, L., Bahsi, H., Patil, P., & Liu, P. (2025). "To Protect the LLM Agent Against the Prompt Injection Attack with Polymorphic Prompt." DSN 2025. NSF PAR | ArXiv 2506.05739
  • Dynamic Extension: Dorzhiev, N. & Liu, P. (2025). "Strengthening Polymorphic Prompt Assembling: Dynamic Separator Generation Against Emerging Prompt Injection Attacks." ArXiv 2605.30534
  • Code Repository: github.com/zhilongwang/LLMAgentProtector (MIT License)
  • PyPI Package: pip install llm-agent-protector
  • Attack Payloads: Lupinacci et al. evaluation of 18 LLMs across three attack surfaces, finding 94.4% vulnerability to direct injection.
  • Hybrid Defense Thesis: Sunny, D.D.J. (2026). "A Hybrid Defense Against Prompt Injection in LLM Agents." Halmstad University.

The lesson here goes beyond prompt injection defense. In security, the blast radius of any single failure is as important as the probability of that failure. PPA's static pool reduced the probability of a successful injection to near-zero—but left the blast radius of a leak at 100%. Dynamic separators compress that blast radius to a single request. It's the difference between a fire door and a fire extinguisher: one limits spread, the other limits damage. You want both.

For teams deploying LLM agents in production, the message is clear: if you're using PPA, switch to dynamic mode today. If you're not using PPA, start—and use dynamic mode from day one. The 2.7 microseconds you'll spend are the cheapest security improvement you'll ever make.