惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Recent Announcements
Recent Announcements
阮一峰的网络日志
阮一峰的网络日志
爱范儿
爱范儿
博客园_首页
Last Week in AI
Last Week in AI
月光博客
月光博客
有赞技术团队
有赞技术团队
IT之家
IT之家
博客园 - Franky
P
Proofpoint News Feed
Hugging Face - Blog
Hugging Face - Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Microsoft Azure Blog
Microsoft Azure Blog
博客园 - 三生石上(FineUI控件)
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
V
V2EX
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
云风的 BLOG
云风的 BLOG
WordPress大学
WordPress大学
The GitHub Blog
The GitHub Blog
人人都是产品经理
人人都是产品经理
A
About on SuperTechFans
N
Netflix TechBlog - Medium
雷峰网
雷峰网
Recorded Future
Recorded Future
S
Securelist
C
CERT Recently Published Vulnerability Notes
Vercel News
Vercel News
F
Full Disclosure
C
Cybersecurity and Infrastructure Security Agency CISA
A
Arctic Wolf
Simon Willison's Weblog
Simon Willison's Weblog
L
LINUX DO - 热门话题
T
Tenable Blog
MongoDB | Blog
MongoDB | Blog
V
Visual Studio Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Jina AI
Jina AI
TaoSecurity Blog
TaoSecurity Blog
H
Hacker News: Front Page
D
DataBreaches.Net
Google DeepMind News
Google DeepMind News
T
The Exploit Database - CXSecurity.com
S
Security @ Cisco Blogs
W
WeLiveSecurity
酷 壳 – CoolShell
酷 壳 – CoolShell
D
Darknet – Hacking Tools, Hacker News & Cyber Security
SecWiki News
SecWiki News

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
PII Masking vs Data Encryption: What's the Difference for AI APIs?
gunxueqiu6 · 2026-06-21 · via DEV Community

When developers realize their AI prompts contain sensitive data, the first instinct is usually: "I'll just encrypt it."

It makes sense. Encryption is the universal answer to data protection. Encrypt at rest, encrypt in transit, encrypt end-to-end. Follow that playbook and you're safe.

Except with AI APIs, encryption at the wrong layer doesn't just fail to protect your data — it makes the AI completely useless.

Here's the technical breakdown of why encryption breaks AI, why hashing doesn't work either, and why masking is the right approach.

Layer 1: Encryption — Why It Fails for AI

Let's trace the problem. You want to ask an AI about a customer support ticket:

{
  "ticket_id": "TKT-4921",
  "customer_email": "jane.doe@bigcorp.com",
  "issue": "Cannot access account since changing phone number"
}

If you encrypt this payload end-to-end, here's what happens:

Your request → Encrypted → [Network] → Encrypted → AI API endpoint
                                                    ↓
                                            [Cannot decrypt]
                                            [Cannot process]
                                            [Cannot reply]
                                                    ↓
                                              Error or nonsense

The AI model needs plaintext to generate a response. There is no homomorphic encryption scheme mature enough to run a 400-billion-parameter transformer model on encrypted data. Even if you encrypt the HTTPS transport (which always happens with TLS/SSL), the AI server decrypts the payload to process it.

Encryption protects data:

  • ✅ In transit (TLS/SSL) — already handled by HTTPS
  • ✅ At rest (server-side encryption) — done by cloud providers
  • ❌ During inference — the model reads plaintext

The gap is inference-time privacy. Once the data reaches the AI server's memory to be processed, it exists in plaintext inside that server. If the server logs prompts (and most do, for monitoring), the plaintext is logged too.

What About End-to-End Encryption for AI?

Some services advertise E2E encryption. Here's what that typically means in practice:

// Client side: encrypt before sending
const encrypted = await crypto.subtle.encrypt(
  { name: "AES-GCM", iv: iv },
  serverPublicKey,
  encoder.encode(JSON.stringify(prompt))
);

// Server decrypts → processes → encrypts response → sends back

The AI server still decrypts your prompt to run inference on it. The "E2E encryption" in this context means the transport, not the processing. The plaintext exists in the server's memory during inference — and that memory is what gets logged, cached, and potentially used for training.

Layer 2: Hashing — Why It Destroys Semantics

If encryption is a no-go, what about hashing? Hash the sensitive values before sending them:

function hashEmail(email) {
  return crypto.createHash('sha256').update(email).digest('hex');
}

const prompt = `Customer ${hashEmail("jane@example.com")} is reporting login issues.`;

Sent to the AI:

Customer a7ffc6f8bf1ed76651c14756a061d662f580ff4de43b49fa82d80a4b80f8434a is reporting login issues.

This is useless. The AI can't:

  • Recognize the hash as an email address (it looks like random hex)
  • Understand the structure of the data (is it a name? token? ID?)
  • Reason about the relationship (e.g., "does this customer have a .edu address for discounts?")

Hashing is deterministic and non-reversible by design — and that's exactly why it breaks AI. The model needs to understand the category and structure of data, not just verify its integrity.

When Hashing Actually Works

There's one narrow case where hashing makes sense: lookup-based detection without revealing the original value. For example:

// Before sending to AI, check a local hash set to warn about secrets
const sensitiveHashSet = new Set([hash(myApiKey), hash(myDbPassword)]);

function detectLeak(text) {
  for (const word of text.split(/\s+/)) {
    const h = crypto.createHash('sha256').update(word).digest('hex');
    if (sensitiveHashSet.has(h)) return { leaked: true, type: 'credential' };
  }
  return { leaked: false };
}

This lets you detect leaks locally without ever sending the raw values to a detection service. But it doesn't help during inference — you can't hash-replace values in a prompt and expect the AI to understand them.

Layer 3: Masking — The Sweet Spot

Masking replaces sensitive values with placeholders that preserve the structural semantics:

Original Masked Semantics Preserved?
john.smith@gmail.com [EMAIL] Yes — tells the AI "this is an email"
192.168.1.100 [IP_ADDRESS] Yes — tells the AI "this is an IP"
sk-proj-xxxxxxxx [API_KEY] Yes — tells the AI "this is a credential"
John Smith [PERSON_NAME] Yes — tells the AI "this is a person's name"

The AI still understands the structure and context of your question:

Original prompt:

Is there a security issue with this database URL?
DATABASE_URL=postgresql://admin:RealP@ssword1@staging-3.internal.corp:5432/users

Masked prompt:

Is there a security issue with this database URL?
DATABASE_URL=postgresql://[USERNAME]:[PASSWORD]@[HOSTNAME]:5432/users

The AI can still analyze the question perfectly. It knows the URL format, the port, the database name. It can tell you: "Yes, using a hardcoded password in a connection string is a security issue — you should use environment variables or a secrets manager." All without ever seeing the actual password or hostname.

Detection-and-Masking: How It Works

Modern masking tools use a combination of techniques:

1. Regex Pattern Matching

const patterns = {
  EMAIL: /\b[\w.-]+@[\w.-]+\.\w{2,}\b/g,
  IP_ADDRESS: /\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g,
  API_KEY_OPENAI: /\b(sk-proj-|sk-)[A-Za-z0-9]{20,}\b/g,
  CREDIT_CARD: /\b\d{4}[- ]?\d{4}[- ]?\d{4}[- ]?\d{4}\b/g,
  PHONE: /\b\+?\d{1,3}[-.()]?\d{3}[-.]?\d{3}[-.]?\d{4}\b/g,
};

function maskPrompt(text) {
  let masked = text;
  for (const [type, pattern] of Object.entries(patterns)) {
    masked = masked.replace(pattern, `[${type}]`);
  }
  return masked;
}

2. Named Entity Recognition (NER)

NER models detect entities regex can't catch:

import spacy

nlp = spacy.load("en_core_web_trf")

def mask_entities(text):
    doc = nlp(text)
    masked = text
    for ent in reversed(doc.ents):  # Reverse to maintain positions
        if ent.label_ in ("PERSON", "ORG", "GPE", "EMAIL", "PHONE"):
            masked = masked[:ent.start_char] + f"[{ent.label_}]" + masked[ent.end_char:]
    return masked

3. Entropy Detection

For secrets in non-standard formats (custom API keys, tokens):

import math

def shannon_entropy(s):
    """Higher entropy = more random = more likely a secret"""
    prob = [float(s.count(c)) / len(s) for c in set(s)]
    return -sum(p * math.log2(p) for p in prob)

def is_likely_secret(value):
    return len(value) > 12 and shannon_entropy(value) > 4.5

Putting It Together: A Real Masking Pipeline

The AI Privacy Gateway combines all three approaches in a single pipeline that runs as a local proxy:

Request body
    ↓
[1] Regex detector → known patterns (email, IP, API key, SSN)
    ↓
[2] NER detector → names, organizations, locations
    ↓
[3] Entropy detector → high-entropy unknown tokens
    ↓
[4] Context-aware labeler → apply consistent masking per category
    ↓
Masked request → AI API

The pipeline runs in under 5ms on average — imperceptible latency for chat applications.

Why This Matters for Compliance

If you're working in a regulated industry, masking changes your compliance posture significantly:

Raw prompts sent to AI Masked prompts sent to AI
GDPR exposure Full PII transmitted abroad No PII transmitted
HIPAA compliance PHI shared with third party No PHI shared
SOC 2 scope Data shared with subprocessor Anonymized data
Audit trail Full data exposure Metadata only
Data retention concerns Need deletion agreement No PII to delete

Most compliance frameworks care about whether PHI/PII crosses organizational boundaries during processing. Masking before sending means the AI provider never receives protected data in the first place — which significantly simplifies your compliance obligations.

The Bottom Line

Choose the right tool for the job:

Technique Works for AI prompts? Why
Transport encryption (TLS) ✅ Required baseline Already happening, doesn't protect against server-side processing
End-to-end encryption AI must decrypt to process, so data exists in plaintext on server
Hashing Destroys semantics; AI can't understand hashed values
Format-preserving encryption ⚠️ Partial Preserves format but not meaning; limited value
Masking ✅ Best approach Preserves semantics while removing actual sensitive values
Redaction (remove entirely) ⚠️ Partial Safe but removes context the AI might need

For AI API privacy, masking is the practical sweet spot. It's computationally cheap, preserves the semantic structure the AI needs, and keeps sensitive data off third-party servers.

AI Privacy Gateway implements all three detection methods (regex, NER, entropy) with a pluggable detector system. But the principle applies regardless of implementation: detect before you send, mask what you can, structure what you can't.


Encryption protects bytes. Masking protects meaning. For AI, you need both.