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

推荐订阅源

T
Tenable Blog
MyScale Blog
MyScale Blog
罗磊的独立博客
Hugging Face - Blog
Hugging Face - Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
爱范儿
爱范儿
博客园 - 司徒正美
D
Darknet – Hacking Tools, Hacker News & Cyber Security
量子位
N
News | PayPal Newsroom
S
Secure Thoughts
酷 壳 – CoolShell
酷 壳 – CoolShell
L
LINUX DO - 热门话题
有赞技术团队
有赞技术团队
V
Visual Studio Blog
T
Tailwind CSS Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Project Zero
Project Zero
B
Blog RSS Feed
J
Java Code Geeks
Google Online Security Blog
Google Online Security Blog
Last Week in AI
Last Week in AI
Cyberwarzone
Cyberwarzone
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
小众软件
小众软件
博客园 - 【当耐特】
Latest news
Latest news
T
Threat Research - Cisco Blogs
aimingoo的专栏
aimingoo的专栏
博客园_首页
博客园 - 三生石上(FineUI控件)
Engineering at Meta
Engineering at Meta
D
Docker
Forbes - Security
Forbes - Security
Help Net Security
Help Net Security
Apple Machine Learning Research
Apple Machine Learning Research
P
Proofpoint News Feed
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Simon Willison's Weblog
Simon Willison's Weblog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
V2EX - 技术
V2EX - 技术
N
Netflix TechBlog - Medium
The Last Watchdog
The Last Watchdog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
T
Threatpost
Cloudbric
Cloudbric
T
The Exploit Database - CXSecurity.com
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 叶小钗
Webroot Blog
Webroot Blog

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
laravel-crypto: libsodium, no compromises, and per-user encryption
Dusan Maluse · 2026-05-19 · via DEV Community

Laravel's default cipher is AES-256-CBC. That is a 25-year-old design with no built-in authentication — the MAC is bolted on separately by the framework, and the correctness of that construction depends on nobody ever reordering the operations.

I am not saying it is broken. I am saying PHP has shipped with libsodium since 7.2, and libsodium gives you authenticated encryption by construction. There was no reason to keep using AES-256-CBC as the default the moment sodium_crypto_aead_xchacha20poly1305_ietf_encrypt became available in every standard PHP install. I built laravel-crypto because I wanted to stop thinking about that gap every time I started a new project.

why libsodium

NaCl — and libsodium as its portable successor — was designed around one principle: remove the ways you can shoot yourself in the foot. Every algorithm choice is made for you. There is no ECB mode. There is no "pick your own MAC." XChaCha20-Poly1305 is authenticated by definition. AEGIS was designed specifically for high-throughput AEAD on hardware with AES acceleration, which includes every modern x86 and ARM chip. The API surface is small enough to understand fully.

PHP's mcrypt was the old answer. It was unmaintained, it supported ECB, it let you combine incompatible primitives, and it was removed in PHP 7.2. libsodium replaced it — but Laravel did not update its default cipher. AES-256-CBC stayed in config/app.php, a leftover from before the ecosystem had anything better. laravel-crypto picks up where mcrypt's removal should have taken things.

the drop-in

Swapping the provider is two lines:

// bootstrap/providers.php (Laravel 11+)
// Illuminate\Encryption\EncryptionServiceProvider::class,   // remove
CodeLieutenant\LaravelCrypto\ServiceProvider::class,         // add

Enter fullscreen mode Exit fullscreen mode

After that, Crypt::encryptString() and Crypt::decryptString() still work exactly as before. All existing code calling the facade keeps working. The only change is what runs underneath.

Set the cipher in config/app.php:

'cipher' => 'Sodium_AEGIS256GCM',
// Options: Sodium_AES256GCM, Sodium_XChaCha20Poly1305, Sodium_AEGIS256GCM, Sodium_AEGIS128LGCM, Sodium_SecretBox

Enter fullscreen mode Exit fullscreen mode

Generate keys:

php artisan crypto:keys

Enter fullscreen mode Exit fullscreen mode

That is the full migration for most apps. If you already use AEAD via APP_PREVIOUS_KEYS, the library picks those up automatically for decryption during key rotation.

the numbers

Benchmarks from PHP 8.5.1 on a MacBook M4 Pro — Apple Silicon has hardware AES-NI and dedicated AEGIS acceleration:

Algorithm 1 KiB enc 1 KiB dec 1 MiB enc 1 MiB dec
Laravel AES-256-CBC 8.09 μs 9.98 μs 5.02 ms 7.57 ms
Laravel AES-256-GCM 3.37 μs 5.33 μs 1.31 ms 3.94 ms
Sodium AES-256-GCM 2.39 μs 2.58 μs 1.11 ms 1.88 ms
Sodium XChaCha20-Poly1305 3.41 μs 3.58 μs 2.21 ms 2.90 ms
Sodium AEGIS-256 2.06 μs 2.27 μs 0.82 ms 1.65 ms
Sodium AEGIS-128L 2.03 μs 2.14 μs 0.90 ms 1.60 ms

AEGIS-128L decrypts a 1 MiB payload in 1.60 ms versus Laravel's AES-256-CBC at 7.57 ms. That is 4.7× faster, authenticated, on the same hardware. Sodium AES-256-GCM halves the decryption time compared to Laravel's own GCM implementation — same algorithm, better path through the Sodium extension than through OpenSSL via PHP's stream wrapper.

XChaCha20-Poly1305 is the conservative choice: well-analyzed, hardware-agnostic, fast on everything. Use it if you need consistent performance on older or constrained hardware without AES acceleration. On ARM or x86 with AES-NI, AEGIS is the right pick.

The point is not that the difference matters for a single request. It matters when you are decrypting a hundred fields per page load, or processing a batch job over encrypted rows, or streaming large files. AES-256-CBC at 7.57 ms per MiB is not a performance problem in isolation. As a default that never gets questioned, it adds up.

per-user encryption

The standard model — one APP_KEY encrypts everything — has a structural problem. Anyone with access to that key can decrypt every row in the database. That is the DBA, the sysadmin, the developer with a .env copy, and any process with access to the environment. If client data confidentiality is a real requirement, "we encrypted the database" is not a complete answer when a single key unlocks all of it.

Per-user encryption means each user's sensitive fields are encrypted with a key unique to that user. A 32-byte random key is generated at enrollment and wrapped in a self-contained blob stored in the encryption_key column. Two wrapping modes exist depending on what is available at enrollment time:

  • Mode 1 — password-wrapped (0x01, 89 bytes): wrapping key derived via Argon2id from the user's plaintext password. APP_KEY is not involved. Unwrapping requires the password — no server-side secret alone can decrypt these fields.
  • Mode 2 — server-wrapped (0x02, 73 bytes): wrapping key derived via BLAKE2b(appKey, userId). Used for auto-enrollment when the plaintext password is unavailable (e.g. OAuth users, Filament). The blob is promoted to Mode 1 transparently the next time the user provides their password.

The unwrapped key is never stored anywhere. It is base64url-encoded, sent to the client as X-Encryption-Token (header for SPA/API clients) or as an HTTP-only enc_token cookie (web clients), and re-sent on every subsequent request. The middleware reads it, loads it into the request-scoped context, then zeros it at the end of the response.

Setting it up:

// User model
use CodeLieutenant\LaravelCrypto\Traits\HasUserEncryption;

class User extends Authenticatable
{
    use HasUserEncryption;
}

Enter fullscreen mode Exit fullscreen mode

At registration, return the token to the client:

$rawKey = $user->initUserEncryption($request->password);
$user->save();
return response()->json([...])->header('X-Encryption-Token', $user->encodeEncryptionToken($rawKey));

Enter fullscreen mode Exit fullscreen mode

At login, re-derive the token from the password and hand it back:

if (Auth::attempt($credentials)) {
    $token = Auth::user()->issueEncryptionToken($credentials['password']);
    return response()->json([...])->header('X-Encryption-Token', $token);
}

Enter fullscreen mode Exit fullscreen mode

After that, model casts handle the rest transparently:

class UserSecret extends Model
{
    protected function casts(): array
    {
        return [
            'ssn' => UserEncryptedWithIndex::class . ':ssn_index',
        ];
    }
}

Enter fullscreen mode Exit fullscreen mode

Reading $secret->ssn decrypts using the key currently in the request context. Saving writes ciphertext. Nothing else in the application changes.

the key in memory

The key lives in a scoped container — one instance per HTTP request. The BootPerUserEncryption middleware loads it from the incoming header or cookie, sets it on the context, then clears it in a finally block:

// src/Encryption/UserKey/UserEncryptionContext.php
public function clear(): void
{
    if ($this->key !== null) {
        sodium_memzero($this->key);
        $this->key = null;
    }
}

public function __destruct()
{
    $this->clear();
}

Enter fullscreen mode Exit fullscreen mode

Setting a variable to null in PHP does not zero the memory — the garbage collector might hold the reference, and even when it collects, it does not overwrite the bytes. sodium_memzero does. The key is gone, not just unreferenced.

For Mode 1 blobs the wrapped blob in the database is useless without the user's password. Compromising APP_KEY does not help. For Mode 2 blobs, APP_KEY + userId is enough to re-derive the wrapping key — that is the acknowledged trade-off for the auto-enrollment path. The moment the user sets a password, issueEncryptionToken() promotes the blob to Mode 1 automatically.

blind indexes for searchable fields

Encrypting a column means you can no longer query it. WHERE ssn = ? stops working when ssn is ciphertext. The standard solution is a blind index: a deterministic MAC of the plaintext stored alongside the ciphertext, used only for equality lookups.

The derivation:

// src/Encryption/UserKey/BlindIndex.php — compute
public function compute(
    #[SensitiveParameter] string $value,
    string $column,
    bool $normalise = true,
): string {
    $userKey = $this->context->get();
    $subKey  = $this->deriveColumnSubKey($userKey, $column);

    $input = $normalise ? mb_strtolower(trim($value)) : $value;

    return sodium_crypto_generichash($input, $subKey, self::INDEX_BYTES);
}

// src/Encryption/UserKey/BlindIndex.php — column sub-key
private function deriveColumnSubKey(string $userKey, string $column): string
{
    $hash = sodium_crypto_generichash($column, '', SODIUM_CRYPTO_GENERICHASH_BYTES_MIN);
    $ctx  = substr($hash, 0, 8);

    return sodium_crypto_kdf_derive_from_key(
        self::INDEX_BYTES,
        self::KDF_SUBKEY_ID,
        $ctx,
        $userKey,
    );
}

Enter fullscreen mode Exit fullscreen mode

Each column gets a distinct sub-key derived from the user's key via libsodium's official KDF. The index for ssn is cryptographically separated from the index for email, even though both come from the same user key. Two users with identical SSNs produce different indexes. Querying:

UserSecret::where('ssn_index', UserCrypt::blindIndex('123-45-6789', 'ssn'))->first();

Enter fullscreen mode Exit fullscreen mode

The leakage is explicit: blind indexes leak equality. An attacker with database read access can tell that two rows share a value — they learn nothing about what that value is. Do not put a blind index on a low-cardinality field. gender, country, boolean flags — no. SSN, passport number, phone, email — yes.

what it isn't

  • It is not a replacement for proper key management. Mode 1 blobs are only as safe as the user's password — weak passwords mean weak wrapping. Mode 2 blobs are only as safe as APP_KEY. Treat APP_KEY accordingly: secrets manager, rotation policy, backup.
  • It does not protect against runtime compromise. If an attacker can execute arbitrary PHP in your process, they can read the key from the request context during a live request. Encryption protects data at rest, not running code.
  • Per-user encryption is not transparent key rotation. Changing a user's password requires rewrapUserEncryption($old, $new). Rotating APP_KEY requires re-wrapping every user's key. Neither is automatic.
  • Blind indexes leak equality. Two rows with the same value in the same column for the same user produce the same index. On fields with a small set of possible values, that is dangerous enough to skip the index entirely.
  • It is not end-to-end encryption. The raw key is derived server-side and then handed to the client as a token. The server sees it. True E2E requires the key to never reach the server — that is a different architecture and a different threat model entirely.

where to start

composer require codelieutenant/laravel-crypto
php artisan vendor:publish --provider="CodeLieutenant\LaravelCrypto\ServiceProvider"
php artisan crypto:keys

Enter fullscreen mode Exit fullscreen mode

Set 'cipher' => 'Sodium_AEGIS256GCM' in config/app.php, swap the service provider, run your test suite. For most apps the migration takes twenty minutes.

Per-user encryption takes longer — you need to decide which columns are sensitive enough to warrant it, wire up the middleware, and handle the password-change re-wrap flow. The docs in docs/UserEncryption.md cover the full setup. I use it in every project where the question "can your team read this user's data?" has an answer I would be uncomfortable defending.