← Learning AI
✨ Nuevo: v1.1.1 ✨ New: v1.1.1 Apache 2.0 Java 17+ Spring Boot 4.1+ Spring AI 2.0+

Prompt Shield Prompt Shield

Protege datos sensibles en prompts de IA. Ofusca DNI, emails, teléfonos, IBAN y ahora también claves de API de los 16 servicios más populares antes de enviarlos a LLMs. Protect sensitive data in AI prompts. Obfuscate DNI, emails, phone numbers, IBANs and now API keys from the 16 most popular services before sending to LLMs.

Maven Central

<groupId>com.ploybot</groupId> <artifactId>prompt-shield-core</artifactId> <version>1.1.1</version>
🔑

Novedad en v1.1.1: ofuscación de claves de API New in v1.1.1: API key obfuscation

Además de datos personales, Prompt Shield ahora detecta y ofusca automáticamente claves y tokens de 16 servicios populares —OpenAI, Anthropic, AWS, GitHub, Stripe y más— antes de que lleguen al prompt de la IA. Ideal para evitar fugas accidentales de secretos cuando un usuario pega logs, código o configuración en un chat con IA. Beyond personal data, Prompt Shield now detects and automatically obfuscates keys and tokens from 16 popular services —OpenAI, Anthropic, AWS, GitHub, Stripe and more— before they reach the AI prompt. Perfect for preventing accidental secret leaks when a user pastes logs, code or configuration into an AI chat.

Ver los 16 servicios See all 16 services

Características principales Key Features

🛡️

Ofuscación automática Automatic Obfuscation

Detecta y ofusca DNI, NIE, emails, teléfonos y tipos personalizados automáticamente. Detects and obfuscates DNI, NIE, emails, phone numbers and custom types automatically.

Nuevo New
🔑

Detección de claves de API API Key Detection

Ofusca claves de OpenAI, Anthropic, AWS, GitHub, Stripe y otros 11 servicios populares (16 en total). Obfuscates keys from OpenAI, Anthropic, AWS, GitHub, Stripe and 11 other popular services (16 total).

🔄

Restauración bidireccional Bidirectional Restoration

Los placeholders se restauran automáticamente en las respuestas de la IA. Placeholders are automatically restored in AI responses.

🤖

System prompt automático Automatic System Prompt

Inyecta un system prompt que le dice a la IA que preserve los placeholders. Injects a system prompt telling the AI to preserve placeholders.

📦

Soporte JSON y objetos JSON and Object Support

Ofusca strings en JSON y objetos Java manteniendo la estructura. Obfuscates strings in JSON and Java objects while preserving structure.

💾

Múltiples backends Multiple Backends

In-Memory, Redis, JPA/H2 para almacenar tags de ofuscación. In-Memory, Redis, JPA/H2 for storing obfuscation tags.

⚙️

Configurable Configurable

Prefijos, separadores y tipos de datos personalizables. Customizable prefixes, separators and data types.

Cómo funciona How it Works

1

Input del usuario User Input

"Mi DNI es 12345678Z"

2

Ofuscación Obfuscation

"Mi DNI es ~REDACTED:DNI#a1b2c3~"

3

Envío a IA Send to AI

La IA procesa sin ver datos reales AI processes without seeing real data

4

Restauración Restoration

Se restauran los valores originales Original values are restored

Ejemplo completo Complete Example

# Input del usuario
"Mi nombre es Juan, DNI 12345678Z, email juan@email.com"

# Se envía a la IA (ofuscado)
"Mi nombre es Juan, DNI ~REDACTED:DNI#a1b2c3~, email ~REDACTED:EMAIL#d4e5f6~"

# Respuesta de la IA
"El DNI ~REDACTED:DNI#a1b2c3~ es válido. El email ~REDACTED:EMAIL#d4e5f6~ está correcto."

# Respuesta final (restaurada)
"El DNI 12345678Z es válido. El email juan@email.com está correcto."# User input
"My name is Juan, DNI 12345678Z, email juan@email.com"

# Sent to AI (obfuscated)
"My name is Juan, DNI ~REDACTED:DNI#a1b2c3~, email ~REDACTED:EMAIL#d4e5f6~"

# AI response
"The DNI ~REDACTED:DNI#a1b2c3~ is valid. The email ~REDACTED:EMAIL#d4e5f6~ is correct."

# Final response (restored)
"The DNI 12345678Z is valid. The email juan@email.com is correct."

Ventaja adicional: Previene alucinaciones Additional Benefit: Prevents Hallucinations

⚠️

El problema: Alucinaciones de datos sensibles The Problem: Sensitive Data Hallucinations

Los modelos de IA pueden inventar, modificar o confundir datos críticos como: AI models can invent, modify or confuse critical data such as:

  • DNI/NIE: Inventar un DNI que no existe o modificar uno real DNI/NIE: Invent a DNI that doesn't exist or modify a real one
  • Cuentas bancarias: Generar números de cuenta falsos o alterar los reales Bank accounts: Generate fake account numbers or alter real ones
  • Teléfonos: Cambiar dígitos o crear números inexistentes Phone numbers: Change digits or create non-existent numbers
  • Emails: Modificar direcciones de correo electrónico Emails: Modify email addresses

💡 Ejemplo: Si envías "Mi DNI es 12345678Z" sin ofuscar, la IA podría responder con "El DNI 12345678A es válido" - cambiando la letra sin que te des cuenta. 💡 Example: If you send "My DNI is 12345678Z" without obfuscation, the AI might respond with "The DNI 12345678A is valid" - changing the letter without you noticing.

La solución: Prompt Shield The Solution: Prompt Shield

Al ofuscar los datos, la IA no puede alucinar porque: By obfuscating data, the AI cannot hallucinate because:

  • Placeholders opacos: La IA ve ~REDACTED:DNI#a1b2c3~, no el DNI real Opaque placeholders: AI sees ~REDACTED:DNI#a1b2c3~, not the real DNI
  • Imposible modificar: La IA no puede cambiar letras ni dígitos en un placeholder Impossible to modify: AI cannot change letters or digits in a placeholder
  • System prompt: Instrucciones explícitas para preservar los marcadores System prompt: Explicit instructions to preserve markers
  • Restauración segura: Los valores reales solo se restauran después de la IA Safe restoration: Real values are only restored after AI processing

💡 Con Prompt Shield: La IA recibe ~REDACTED:DNI#a1b2c3~ y responde con el mismo placeholder. Nunca toca el DNI real. 💡 With Prompt Shield: AI receives ~REDACTED:DNI#a1b2c3~ and responds with the same placeholder. It never touches the real DNI.

Casos de uso críticos Critical Use Cases

🏦

Banca y finanzas Banking & Finance

Procesar transferencias sin exponer IBANs Process transfers without exposing IBANs

🏥

Salud Healthcare

Analizar historiales sin exponer datos médicos Analyze records without exposing medical data

⚖️

Legal Legal

Revisar contratos sin exponer datos personales Review contracts without exposing personal data

Comenzar rápido Quick Start

Maven

<!-- Core Library -->
<dependency>
    <groupId>com.ploybot</groupId>
    <artifactId>prompt-shield-core</artifactId>
    <version>1.1.1</version>
</dependency>

<!-- Spring Boot Starter (optional) -->
<dependency>
    <groupId>com.ploybot</groupId>
    <artifactId>prompt-shield-spring-boot-starter</artifactId>
    <version>1.1.1</version>
</dependency>

<!-- Spring AI Advisor (optional) -->
<dependency>
    <groupId>com.ploybot</groupId>
    <artifactId>prompt-shield-spring-ai-advisor</artifactId>
    <version>1.1.1</version>
</dependency>

Gradle

implementation 'com.ploybot:prompt-shield-core:1.1.1'
implementation 'com.ploybot:prompt-shield-spring-boot-starter:1.1.1'
implementation 'com.ploybot:prompt-shield-spring-ai-advisor:1.1.1'

Ejemplos de código Code Examples

Uso básico Basic Usage

import com.ploybot.promptshield.engine.ObfuscationEngine;

ObfuscationEngine engine = new ObfuscationEngine();

// Ofuscar texto
String obfuscated = engine.ofuscar("Mi DNI es 12345678Z y mi email es user@email.com");
// Resultado: "Mi DNI es ~REDACTED:DNI#1c9f96~ y mi email es ~REDACTED:EMAIL#e5a3b2~"

// Restaurar valores originales
String restored = engine.restaurar(obfuscated);
// Resultado: "Mi DNI es 12345678Z y mi email es user@email.com"

Ofuscación JSON JSON Obfuscation

// Ofuscar string JSON
String json = "{\"dni\":\"12345678Z\",\"email\":\"user@email.com\"}";
String obfuscated = engine.ofuscarObjetoJson(json);
// Resultado: "{\"dni\":\"~REDACTED:DNI#1c9f96~\",\"email\":\"~REDACTED:EMAIL#e5a3b2~\"}"

// Restaurar JSON
String restored = engine.restaurarObjetoJson(obfuscated);

Integración Spring AI Spring AI Integration

@RestController
@RequestMapping("/api/ai")
public class AiController {

    private final ChatClient chatClient;

    public AiController(ChatClient.Builder builder, PromptShieldAdvisor advisor) {
        this.chatClient = builder
                .defaultAdvisors(advisor)
                .build();
    }

    @PostMapping("/chat")
    public AiResponse chat(@RequestBody AiRequest request) {
        // Los datos se ofuscan automáticamente antes de enviar a la IA
        // y se restauran en la respuesta
        String response = chatClient.prompt()
                .user(request.message())
                .call()
                .content();
        return new AiResponse(response);
    }
}

Configuración Configuration

application.yml

spring:
  ai:
    openai:
      api-key: ${OPENAI_API_KEY}
      chat:
        options:
          model: gpt-4o-mini

prompt-shield:
  enabled: true
  hash-algorithm: SHA-256
  hash-length: 6
  storage-type: memory
  redacted-prefix: "REDACTED"
  tag-separator: "#"
  service-keys-enabled: true   # false para desactivar la detección de claves de API
  custom-types:
    CODIGO_POSTAL:
      pattern: "\d{5}"
    N_CUENTA:
      pattern: "ES\d{22}"
  advisor:
    enabled: true
    order: 0
    restore-on-response: true
    inject-system-prompt: true

@Obfuscate Annotation

@Service
public class MyService {

    @Obfuscate
    public String processPrompt(String prompt) {
        // prompt se ofusca automáticamente
        return aiClient.call(prompt);
    }
    
    @Obfuscate(types = {"DNI", "EMAIL"})
    public String processSpecific(String prompt) {
        // Solo DNI y EMAIL se ofuscan
        return aiClient.call(prompt);
    }
}

Opciones de almacenamiento Storage Options

🧠

In-Memory

Por defecto. Ideal para desarrollo y testing. Default. Ideal for development and testing.

prompt-shield:
  storage:
    type: memory
🔴

Redis

Para producción con TTL configurable. For production with configurable TTL.

prompt-shield:
  storage:
    type: redis
  redis:
    ttl-hours: 24
🗄️

JPA/H2

Persistencia con base de datos. Database persistence.

prompt-shield:
  storage:
    type: jpa
  jpa:
    ttl-hours: 24

Tipos de datos soportados Supported Data Types

Tipo Type Patrón Pattern Ejemplo
DNI \d{8}[A-Za-z] 12345678Z
NIE [XYZxyz]\d{7}[A-Za-z] X1234567A
EMAIL [\w.+-]+@[\w.-]+\.\w{2,} user@email.com
TELEFONO \d{9} 612345678
CODIGO_POSTAL \d{5} 28001
N_CUENTA ES\d{22} ES1234567890123456789012

Claves de API soportadas (Service Keys) Supported API Keys (Service Keys)

Nuevo en v1.1.1 New in v1.1.1

Prompt Shield detecta y ofusca automáticamente claves y tokens de los 16 servicios más populares antes de enviarlos a la IA, evitando fugas de secretos cuando un usuario pega código, logs o configuración en un chat. Prompt Shield automatically detects and obfuscates keys and tokens from the 16 most popular services before sending them to the AI, preventing secret leaks when a user pastes code, logs or configuration into a chat.

Servicio Service Tipo Type Patrón Pattern Ejemplo
🤖 OpenAI OPENAI_API_KEY sk-proj-[A-Za-z0-9_-]{20,} sk-proj-abc123...
🧠 Anthropic ANTHROPIC_API_KEY sk-ant-[A-Za-z0-9_-]{20,} sk-ant-api03-...
✨ Google AI GOOGLE_AI_KEY AIza[A-Za-z0-9_-]{35} AIzaSyA1b2C3d4...
🤗 HuggingFace HUGGINGFACE_TOKEN hf_[A-Za-z0-9]{34} hf_abc123...
☁️ AWS AWS_ACCESS_KEY AKIA[0-9A-Z]{16} AKIAIOSFODNN7...
🔷 Azure AZURE_STORAGE_KEY [A-Za-z0-9+/]{88}== AbCdEf...==
🌊 DigitalOcean DIGITALOCEAN_TOKEN dop_v1_[a-f0-9]{64} dop_v1_abc...
🐙 GitHub GITHUB_TOKEN gh[psoa]_[A-Za-z0-9]{36} ghp_abc123...
🦊 GitLab GITLAB_TOKEN glpat-[A-Za-z0-9_-]{20,} glpat-abc123...
📦 NPM NPM_TOKEN npm_[A-Za-z0-9]{36} npm_abc123...
🐍 PyPI PYPI_TOKEN pypi-[A-Za-z0-9_-]{60,} pypi-AgEIcHl...
💬 Slack SLACK_TOKEN xox[bpsa]-[0-9]{10,13}-[a-zA-Z0-9-]{20,} xoxb-123456789012-...
📞 Twilio TWILIO_API_KEY SK[0-9a-fA-F]{32} SKabcdef0123...
📧 SendGrid SENDGRID_KEY SG\.[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43} SG.abc123...XYZ
✉️ Mailgun MAILGUN_API_KEY key-[0-9a-zA-Z]{32} key-abcdef0123...
💳 Stripe STRIPE_KEY (?:sk|pk|rk)_(?:live|test)_[0-9a-zA-Z]{24,} sk_live_abc123...

💡 Los service keys se pueden desactivar con service-keys-enabled: false en la configuración. 💡 Service keys can be disabled with service-keys-enabled: false in the configuration.

¿Listo para proteger tus prompts? Ready to protect your prompts?

Empieza a usar Prompt Shield hoy y protege los datos sensibles de tus usuarios. Start using Prompt Shield today and protect your users' sensitive data.