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

推荐订阅源

U
Unit 42
S
Securelist
小众软件
小众软件
WordPress大学
WordPress大学
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
B
Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
The GitHub Blog
The GitHub Blog
Apple Machine Learning Research
Apple Machine Learning Research
博客园 - 司徒正美
博客园 - Franky
Hugging Face - Blog
Hugging Face - Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
酷 壳 – CoolShell
酷 壳 – CoolShell
O
OpenAI News
Cloudbric
Cloudbric
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
TaoSecurity Blog
TaoSecurity Blog
MongoDB | Blog
MongoDB | Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
V
V2EX
PCI Perspectives
PCI Perspectives
T
Troy Hunt's Blog
Schneier on Security
Schneier on Security
P
Palo Alto Networks Blog
M
MIT News - Artificial intelligence
V2EX - 技术
V2EX - 技术
阮一峰的网络日志
阮一峰的网络日志
Hacker News - Newest:
Hacker News - Newest: "LLM"
G
Google Developers Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
The Last Watchdog
The Last Watchdog
The Register - Security
The Register - Security
腾讯CDC
N
News and Events Feed by Topic
C
Check Point Blog
爱范儿
爱范儿
T
Tailwind CSS Blog
Webroot Blog
Webroot Blog
P
Proofpoint News Feed
S
Schneier on Security
MyScale Blog
MyScale Blog
N
News | PayPal Newsroom
Recorded Future
Recorded Future
T
Tenable Blog
I
InfoQ
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Microsoft Security Blog
Microsoft Security Blog
Simon Willison's Weblog
Simon Willison's Weblog
Engineering at Meta
Engineering at Meta

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
How to Detect Tampered PDFs (Forensics Tutorial)
Iurii Roguli · 2026-05-20 · via DEV Community

A client sends you a signed PDF contract. Looks legitimate. The signature block is there, the date is right, the numbers look fine. But something feels off. How do you know if it's the original or if someone changed a figure on page 3 and re-exported it?

I spent 5 days and 7 algorithm versions figuring this out. The result is HTPBE? — Has This PDF Been Edited? — a SaaS that analyzes a PDF in under 9 seconds and tells you exactly how many times it was modified, by what software, and which forensic markers triggered. Here's how it works.

How a PDF Is Actually Structured

Before talking about tamper detection, you need to understand what a PDF file actually contains at the binary level. It's not magic — it's a structured document format from 1993 that has some remarkably useful forensic properties.

A PDF has four sections:

  • Header — identifies the PDF version (%PDF-1.7, %PDF-2.0, etc.)
  • Body — the actual objects: pages, fonts, images, text streams
  • Cross-reference table (xref table) — an index that maps object numbers to their byte offsets in the file
  • Trailer — points to the xref table and contains document metadata

The xref table is the key. It's how a PDF reader finds objects quickly without scanning the entire file. And it's where tampering leaves an unmistakable trail.

The Core Insight: Count the xref Tables

When a PDF is created from scratch — by InDesign, Word, a PDF printer, anything — it contains exactly one xref table. That's the baseline.

Now someone opens the file in Adobe Acrobat and changes a number. Acrobat doesn't rewrite the entire file. That would be slow and could corrupt things. Instead, it appends the changes to the end of the file and adds a second xref table pointing to the new and modified objects. The original content is still there, underneath — just superseded.

This is called an incremental update. And it's the foundation of my detection approach:

One xref table = original document. Two or more xref tables = the document was modified after initial creation.

Every editor does this: Adobe Acrobat, Preview on macOS, LibreOffice, Foxit, PDF-XChange. They all append, never rewrite.

There is one legitimate exception, which took me several algorithm versions to handle correctly: LTV (Long-Term Validation) updates. When a digitally signed PDF needs to embed certificate revocation data for long-term validation, the signing software adds an incremental update with OCSP responses and CRL data. This is legitimate, expected, and should not be flagged as tampering. Missing this in v1 of my algorithm caused a flood of false positives on signed legal documents.

The 7 Forensic Markers

Counting xref tables is the primary signal. But a thorough analysis needs multiple corroborating markers. Here are the seven I check in every analysis:

1. xref Table Count

The count of xref or startxref keywords in the binary. More than one means incremental updates exist. I also check whether those updates are LTV-related before flagging them.

2. Incremental Update Signatures

Beyond just counting, I look at the structure of each incremental update: which object types were added or modified. A legitimate signing update touches only certain object types (signature dictionaries, DSS dictionaries). An update that modifies page content objects is a much stronger tampering signal.

3. Producer Metadata Field

Every PDF has a Producer field in its document info dictionary. This is set by whatever software created or last saved the file. A PDF generated by a hospital system might have Producer: Epic Systems. If the Producer field says Adobe Acrobat 23.0 but the document claims to be an original bank statement — that's a mismatch worth investigating.

I also look for multiple Producer strings across different revisions, which indicates the file passed through more than one software tool.

4. Creation Date vs. Modification Date Mismatch

The CreationDate and ModDate fields in PDF metadata. If they differ significantly — especially if ModDate is after CreationDate by years — that's a signal. If CreationDate is missing entirely but ModDate exists, that's unusual. If both are present but identical after an apparent edit, someone tried to cover their tracks.

5. Orphaned Objects

When PDF editors modify or delete content, the original objects often remain in the file — they're just no longer referenced from the active xref table. They become "orphaned" objects: still in the binary, not reachable from the current document tree. I scan for these. Their presence indicates prior revisions, and their content sometimes reveals what was changed.

6. Encryption and Permissions Changes

If a PDF's encryption dictionary changes between revisions, that's notable. It can indicate an attempt to remove password protection, change editing permissions, or re-encrypt content. I compare encryption settings across xref revisions where detectable.

7. Font Embedding Changes

Fonts embedded in a PDF are large objects. Changing text requires access to the right fonts. If a new font appears in a later xref revision that wasn't in the original, and it's not a system font added by a viewer for display purposes, that's a meaningful signal — particularly if the new font covers a character range used in key fields like amounts or dates.

The 7 Algorithm Versions (What Actually Failed)

I'll be honest about the iteration process: it wasn't linear.

v1 was exactly what it sounds like: count occurrences of xref and startxref in the binary, report the number. This produced catastrophic false positives. Signed PDF documents routinely have 2–3 incremental updates from the signing and LTV process. I was flagging every notarized document as tampered.

v2 added a heuristic: if the file contains a digital signature (/Sig object), ignore the first two incremental updates. Better, but wrong. The number of LTV updates is variable — some signing workflows produce one, some produce three.

v3 was the LTV breakthrough: instead of counting incremental updates after signatures, I actually parse the structure of each update to determine if it contains only DSS (Document Security Store) objects and OCSP/CRL data. If so, it's marked as LTV and excluded from the tampering score. This eliminated 90% of false positives on signed documents.

v4 added the Producer field analysis. This is where I discovered that some PDF generators write garbage into the Producer field — truncated strings, encoding artifacts, empty strings — which made simple string matching unreliable. I had to normalize and sanitize the field before comparison.

v5 introduced confidence scoring instead of binary yes/no. A single incremental update by itself is weak evidence. An incremental update plus a Producer field change plus orphaned content objects is strong evidence. Each marker contributes a weighted score to an overall confidence percentage.

v6 broke things. I tried to add binary-level entropy analysis to detect unusual compression patterns. It was interesting but the false positive rate on legitimately compressed PDFs made it useless in practice. I removed it.

v7 is what ships. Confidence scoring, LTV exclusion, seven markers, no entropy analysis.

slug="mvp-development"
text="Need to build document verification, fraud detection, or KYC tooling into your product? I can own this from the forensics layer to the billing and API surface."
/>

Technical Implementation

Parsing with pdf-lib

I use pdf-lib for structural parsing. It handles the xref table and object access well. For raw binary analysis — finding byte offsets, scanning for marker strings — I work directly on the ArrayBuffer.

Here is the core xref analysis:

interface XrefEntry {
  offset: number;
  isLTV: boolean;
  producerField: string | null;
  hasContentChanges: boolean;
}

async function analyzeXrefTables(fileBuffer: ArrayBuffer): Promise<XrefEntry[]> {
  const bytes = new Uint8Array(fileBuffer);
  const text = new TextDecoder("latin1").decode(bytes);
  const entries: XrefEntry[] = [];

  // Find all startxref markers — each one marks an xref table or xref stream
  const startxrefPattern = /startxref\s+(\d+)/g;
  let match: RegExpExecArray | null;

  while ((match = startxrefPattern.exec(text)) !== null) {
    const offset = parseInt(match[1], 10);

    // Skip the terminal startxref before %%EOF — offset 0 is the document terminator
    if (offset === 0) continue;

    const entry = await parseXrefRevision(bytes, text, offset);
    entries.push(entry);
  }

  return entries;
}

async function parseXrefRevision(
  bytes: Uint8Array,
  text: string,
  offset: number
): Promise<XrefEntry> {
  const trailerStart = text.indexOf("trailer", offset);
  const trailerEnd = text.indexOf(">>", trailerStart);
  const trailerContent = trailerStart !== -1 ? text.slice(trailerStart, trailerEnd + 2) : "";

  // DSS (Document Security Store) presence indicates an LTV update
  const hasDSSObject = trailerContent.includes("/DSS");
  const hasOnlySigObjects = checkForSignatureOnlyUpdate(text, offset);

  const producerMatch = /\/Producer\s*\(([^)]+)\)/.exec(text.slice(offset, offset + 4096));
  const producerField = producerMatch ? producerMatch[1].trim() : null;

  const hasContentChanges = checkForContentModifications(text, offset);

  return {
    offset,
    isLTV: hasDSSObject || hasOnlySigObjects,
    producerField,
    hasContentChanges,
  };
}

function checkForContentModifications(text: string, offset: number): boolean {
  // /Contents, /Page, and BT/ET (Begin Text/End Text) operators signal content edits
  const revisionSlice = text.slice(offset, offset + 16384);
  const contentIndicators = ["/Contents", "/Page\n", "/Pages\n", "BT\n", "ET\n"];
  return contentIndicators.some((indicator) => revisionSlice.includes(indicator));
}

function computeTamperingScore(entries: XrefEntry[]): number {
  const nonLTVEntries = entries.filter((e) => !e.isLTV);

  // Base document always has one xref — anything beyond is an edit
  const editCount = Math.max(0, nonLTVEntries.length - 1);
  if (editCount === 0) return 0;

  let score = 0;
  score += Math.min(editCount * 25, 60);

  // Content modifications are a stronger signal than metadata-only changes
  const contentEdits = nonLTVEntries.filter((e) => e.hasContentChanges);
  score += contentEdits.length * 15;

  // Multiple distinct Producer strings across revisions indicate tool switching
  const producers = new Set(nonLTVEntries.map((e) => e.producerField).filter(Boolean));
  if (producers.size > 1) score += 20;

  return Math.min(score, 100);
}

Enter fullscreen mode Exit fullscreen mode

Bypassing Vercel's 4.5MB Serverless Limit

PDF files up to 10MB need to be analyzed. Vercel's serverless functions have a 4.5MB request body limit. Sending a 10MB PDF directly to an API route fails with a 413 — or worse, silently truncates the body.

The solution is Vercel Blob with client-side upload. The browser uploads directly to Vercel Blob storage (bypassing the serverless function entirely via a token endpoint), then passes the blob URL to a Server Action for analysis. The file never flows through the serverless function body at all.

// components/Hero/index.tsx — Step 1: browser → Vercel Blob
import { upload } from "@vercel/blob/client";

const blob = await upload(filename, file, {
  access: "public",
  handleUploadUrl: "/api/blob-token",
  clientPayload: JSON.stringify({ size: file.size }),
});

// Step 2: pass blob URL to Server Action for analysis
await analyzePdf(blob.url, file.name);

// app/api/blob-token/route.ts — origin-based security for token generation
import { handleUpload } from "@vercel/blob/client";

const ALLOWED_ORIGINS = [process.env.NEXT_PUBLIC_APP_URL!];

export async function POST(req: Request): Promise<Response> {
  const origin = req.headers.get("origin") ?? "";
  const isAllowed = ALLOWED_ORIGINS.some((o) => origin === o);
  if (!isAllowed) return new Response("Forbidden", { status: 403 });

  const body = await req.json();
  const jsonResponse = await handleUpload({
    body,
    request: req,
    onBeforeGenerateToken: async () => ({
      allowedContentTypes: ["application/pdf"],
      maximumSizeInBytes: 10 * 1024 * 1024,
    }),
  });
  return Response.json(jsonResponse);
}

Enter fullscreen mode Exit fullscreen mode

Async Processing with Polling

Analysis takes up to 9 seconds. That's too long for a synchronous Vercel function. I use an async pattern: the job is queued, a job ID is returned immediately, the client polls for results.

// app/api/analyze/route.ts — accepts the Vercel Blob URL, returns a job ID immediately
export async function POST(request: Request) {
  const { blobUrl } = await request.json();
  const jobId = crypto.randomUUID();

  await redis.setex(`job:${jobId}`, 600, JSON.stringify({ status: "queued" }));
  await analysisQueue.add("analyze-pdf", { blobUrl, jobId });

  return Response.json({ jobId });
}

// app/api/analyze/[jobId]/route.ts — client polls this until status === "completed"
export async function GET(request: Request, { params }: { params: Promise<{ jobId: string }> }) {
  const { jobId } = await params;
  const raw = await redis.get(`job:${jobId}`);
  if (!raw) {
    return Response.json({ error: "Job not found" }, { status: 404 });
  }
  return Response.json(JSON.parse(raw));
}

Enter fullscreen mode Exit fullscreen mode

The client polls every 1.5 seconds. Most files finish in 3–5 seconds. The 9-second ceiling is for maximum-size PDFs with complex xref structures.

Gotchas Worth Knowing

LTV updates will fool a naive implementation. If you just count xref tables, every notarized PDF, every DocuSign document, every government e-signature will appear tampered. You must parse the update structure and identify LTV-specific object types before flagging anything.

base64-encoded PDFs need special handling. Some APIs transmit PDFs as base64 strings. If you run binary analysis on the raw base64 string without decoding first, your byte-offset calculations will be completely wrong. Decode to Uint8Array before any binary analysis.

File size from binary vs. encoded differs by ~33%. The File API's .size property returns the correct binary byte count. The .length of a base64 string is approximately 33% larger. Keep this straight or your 10MB validation will reject valid files.

The terminal startxref before %%EOF has offset 0. This is the document terminator marker, not a real xref table. Naive regex counting includes it and inflates the xref count by one. Filter out any entry where offset === 0.

Some enterprise PDF generators produce split xref tables in the original document. Certain systems write multiple xref sections at creation time (not incremental updates). I handle this by checking whether all xref sections share the same Producer metadata — if they do and there are no trailer Prev pointers, it's a single logical revision.

Results

  • Analysis time: under 9 seconds for files up to 10MB
  • False positive rate on legitimately signed documents: near zero after v3 LTV handling
  • Detection coverage: 100% for the 7 deterministic markers
  • File size limit: 10MB, handled via presigned S3 uploads to bypass serverless body limits

The confidence scoring approach handles ambiguous cases better than a binary flag would. A document with one extra xref table from a PDF optimizer (score: 25, low confidence) is treated very differently from a document with three non-LTV incremental updates, two different Producer strings, and orphaned content objects (score: 85+, high confidence). Users get actionable context, not just an alarm.

Try it at HTPBE?. Upload any PDF — a bank statement, a contract, a signed invoice — and see the full forensic breakdown.


If you're building fintech or legaltech tooling where document authenticity matters — loan origination, contract management, insurance claims, KYC workflows — this kind of verification layer is worth integrating directly into your pipeline. The seven markers described here are implementable in any language with binary file access.

If you need a senior developer who can build document verification systems, automation pipelines, or SaaS infrastructure from scratch — get in touch. I'm available for freelance projects and long-term engagements.

Related reading: Technical SEO I Build Into Every Project — because the same "build it right the first time" discipline applies to indexing infrastructure too. | One Package, Five Registries — another example of shipping multiple layers of a system end-to-end.