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

推荐订阅源

Security Archives - TechRepublic
Security Archives - TechRepublic
Project Zero
Project Zero
K
Kaspersky official blog
G
Google Developers Blog
T
Threat Research - Cisco Blogs
T
The Blog of Author Tim Ferriss
Cyberwarzone
Cyberwarzone
Y
Y Combinator Blog
Recorded Future
Recorded Future
Blog — PlanetScale
Blog — PlanetScale
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Cisco Talos Blog
Cisco Talos Blog
Latest news
Latest news
Microsoft Security Blog
Microsoft Security Blog
H
Help Net Security
S
Schneier on Security
P
Palo Alto Networks Blog
H
Hacker News: Front Page
N
News and Events Feed by Topic
N
Netflix TechBlog - Medium
博客园 - Franky
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
SecWiki News
SecWiki News
Cloudbric
Cloudbric
TaoSecurity Blog
TaoSecurity Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
The Hacker News
The Hacker News
C
Check Point Blog
L
LangChain Blog
腾讯CDC
小众软件
小众软件
T
Tenable Blog
Google DeepMind News
Google DeepMind News
GbyAI
GbyAI
L
LINUX DO - 最新话题
A
About on SuperTechFans
Google Online Security Blog
Google Online Security Blog
C
Cisco Blogs
Recent Announcements
Recent Announcements
Hacker News: Ask HN
Hacker News: Ask HN
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Vercel News
Vercel News
雷峰网
雷峰网
美团技术团队
D
DataBreaches.Net
Martin Fowler
Martin Fowler
Help Net Security
Help Net Security
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
F
Full Disclosure
博客园_首页

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
Designing an E2E-Encrypted Terminal Chat in C++17: SRP-6a, HKDF, and a Relay-Blind Server
secret_KK · 2026-05-06 · via DEV Community

There is a class of security properties that most hobby chat implementations simply skip: the server should not be able to read your messages, and authentication should not require trusting the server with a password hash. cmd_chat is a deliberately minimal C++17 implementation that takes both of these seriously — using SRP-6a, HKDF-SHA256, and a Fernet-compatible AEAD scheme — without hiding the mechanics behind a TLS library.

This post is about the design decisions, the trade-offs, and the places where I deliberately kept the implementation simple in ways that a production system would not.


Design Goals and Non-Goals

Goals:

  • The server relays ciphertext it cannot decrypt. No key material touches the server after authentication.
  • Authentication is mutual and zero-knowledge. Neither side learns the other's secret; both sides prove they share it.
  • The crypto stack is auditable in a single afternoon. No opaque abstractions.
  • Cross-platform: Windows (Winsock2), Linux, macOS — same source tree, CI on all three.

Non-goals (explicitly deferred):

  • Perfect forward secrecy. All session confidentiality is tied to the room password. An ephemeral ECDH layer per connection would fix this; it is on the roadmap.
  • TLS transport. The current framing is JSON lines over raw TCP — entirely appropriate for a trusted network or a demo, not appropriate for public deployment without wrapping in TLS.
  • Persistent storage. The message store is in-memory. Replacing it with SQLite is a small mechanical change that would add no insight here.

System Architecture

cmd_chat_cpp/
├── CMakeLists.txt
├── client/          ← TCP connect, SRP handshake, send/recv threads, UI
├── server/          ← accept loop, per-client threads, in-memory stores, broadcast
└── common/          ← crypto.hpp, base64.hpp, json_io.hpp, uuid.hpp  (header-only)

Enter fullscreen mode Exit fullscreen mode

Transport: Newline-delimited JSON (NDJSON) over raw TCP. One nlohmann::json object per line. The framing is intentionally simple — any JSON parser and nc can participate, which matters for debugging and future language interoperability.

Server threading model: One std::thread per accepted connection, detached. Shared state (MessageStore, UserSessionStore, ConnectionManager, SRPAuthManager) is guarded by per-object mutexes. This is the classic thread-per-connection model: straightforward to reason about, does not scale to thousands of concurrent clients, and is entirely appropriate for the stated scope.

Client threading model: Main thread owns stdin and the send path. A dedicated receive thread runs recv_loop() and updates the display. The two threads share no mutable state beyond the socket handle, which is safe after connection establishment.


Security Design

Client                               Server
  |                                    |
  |--- SRP step 1: username + A ------>|
  |<-- SRP step 2: salt + B -----------|
  |--- SRP step 3: client proof M ---->|
  |<-- SRP step 4: server proof H_AMK -|
  |                                    |
  |  (both sides now hold session_key) |
  |                                    |
  |  room_key = HKDF(session_key,      |
  |                  room_salt,        |
  |                  "room_key")       |
  |                                    |
  |--- Fernet(room_key, plaintext) --->|  ← server sees only opaque base64
  |<-- Fernet(room_key, plaintext) ----|

Enter fullscreen mode Exit fullscreen mode

Layer 1: SRP-6a — Password-Authenticated Key Exchange

SRP is a PAKE: it gives you mutual authentication and a shared session key, and the wire messages are computationally indistinguishable from random to a passive observer who does not know the password. The server stores a verifier v = g^x mod N (where x = H(salt | password)), never the password itself.

The handshake produces session_key = H(A | B | S) independently on both sides, where S is the shared premaster secret. Neither x nor S is ever transmitted.

I used csrp with SRP_NG_2048 and SRP_SHA256. The server creates the verifier once at startup:

srp_create_salted_verification_key(
    SRP_SHA256, SRP_NG_2048, "chat",
    reinterpret_cast<const unsigned char*>(password.data()), password.size(),
    &bytes_s, &len_s, &bytes_v, &len_v, nullptr, nullptr);

Enter fullscreen mode Exit fullscreen mode

One deliberate simplification: all clients authenticate as the identity "chat". The username is a display name only, not a separate credential. This means the SRP verifier is shared across all clients — the password is the room credential, not a per-user one. That is a group chat model, not a user account model.

Layer 2: HKDF-SHA256 — Room Key Derivation

After SRP, every client that authenticated with the same password holds the same session_key. HKDF turns that into a deterministic, domain-separated encryption key:

room_key = HKDF-SHA256(ikm=session_key, salt=room_salt, info="room_key", len=32)

Enter fullscreen mode Exit fullscreen mode

room_salt is 16 bytes of RAND_bytes generated at server startup and transmitted during the auth handshake. The info parameter provides domain separation — if you later derive a MAC key or a different-purpose key from the same IKM, use a different info string and you get an independent key with no relation to room_key.

The implementation in common/crypto.hpp covers both the OpenSSL 3 EVP_KDF API and the legacy EVP_PKEY_derive path, since both are in active use in the wild:

std::vector<uint8_t> hkdf_sha256(
    const std::vector<uint8_t>& ikm,
    const std::vector<uint8_t>& salt,
    const std::string& info,
    size_t out_len);

Enter fullscreen mode Exit fullscreen mode

Layer 3: Fernet-Compatible AEAD — Message Encryption

Each message is encrypted into a Fernet token. The layout is:

token = version(1B 0x80) | timestamp(8B big-endian) | IV(16B) | ciphertext | HMAC-SHA256(32B)

Enter fullscreen mode Exit fullscreen mode

The HMAC covers everything from version through the end of ciphertext. This is encrypt-then-MAC — the MAC is over the ciphertext, not the plaintext, which is what you want for a padding-oracle-resistant scheme. AES-128-CBC with a fresh RAND_bytes IV per message.

The server stores and rebroadcasts the base64-encoded token unchanged. It has no key. It cannot decrypt, forge, or modify a message without the HMAC check failing on the receiving client.

std::string fernet_encrypt(const std::vector<uint8_t>& key, const std::string& plaintext);
std::string fernet_decrypt(const std::vector<uint8_t>& key, const std::string& token);

Enter fullscreen mode Exit fullscreen mode

One honest note: AES-128-CBC is not the current best practice for new designs — AES-256-GCM gives you authenticated encryption natively, without a separate HMAC, and eliminates the IV-reuse-is-catastrophic property of CBC. I used CBC + HMAC to match the Fernet specification precisely and to keep the construction transparent. For a production system, reach for GCM or ChaCha20-Poly1305.


The Wire Protocol

Authentication phase (four round trips):

{"cmd": "srp_init", "username": "alice", "A": "<base64>"}
{"user_id": "<uuid>", "B": "<base64>", "salt": "<hex>", "room_salt": "<base64>"}
{"cmd": "srp_verify", "user_id": "<uuid>", "M": "<base64>"}
{"H_AMK": "<base64>", "session_key": "<base64>"}

Enter fullscreen mode Exit fullscreen mode

Chat phase:

{"type": "init",    "messages": [...], "users": ["alice", "bob"]}
{"type": "message", "text": "<fernet-token>"}
{"type": "message", "username": "alice", "text": "<fernet-token>", "timestamp": "..."}
{"type": "user_joined", "username": "bob"}
{"type": "user_left",   "username": "bob"}

Enter fullscreen mode Exit fullscreen mode

The json_io.hpp helpers handle framing — send appends \n, recv reads until \n:

bool send_json(SOCKET sock, const nlohmann::json& j);
std::optional<nlohmann::json> recv_json(SOCKET sock);

Enter fullscreen mode Exit fullscreen mode

std::optional on recv_json is deliberate — nullopt signals EOF or a parse error, which the caller uses to terminate the connection cleanly rather than entering an invalid state.


Known Limitations Worth Naming

No forward secrecy. If the room password is ever compromised, all past session keys (which are derived from the password via SRP) can be recomputed and all past messages can be decrypted — assuming an adversary recorded the traffic. An ephemeral ECDH exchange per connection would bound the blast radius to that session.

Replay is possible at the SRP layer. The current implementation does not validate that the SRP ephemeral values A and B are fresh across reconnections. A full implementation would include a session nonce in the proof. This is a known omission.

session_key is transmitted but not used for chat crypto. After SRP, the server sends session_key to the client for potential per-session keying. In the current implementation, encrypt_text and decrypt_text use room_key (derived from the password directly), not from session_key. This is documented as a known gap between the README security diagram and the actual implementation — aligning them is a clean next step.

Thread-per-connection does not scale. For the stated use case (small team, trusted network) this is fine. For anything beyond ~100 concurrent connections, io_uring or epoll/kqueue with an event loop would be the right move.


Build and Dependency Management

All C++ dependencies except OpenSSL are fetched at configure time via CMake FetchContent:

FetchContent_Declare(nlohmann_json
    URL https://github.com/nlohmann/json/releases/download/v3.11.3/json.tar.xz)
FetchContent_Declare(csrp
    GIT_REPOSITORY https://github.com/cocagne/csrp.git
    GIT_TAG        15d6bd7)

Enter fullscreen mode Exit fullscreen mode

csrp has no CMakeLists.txt of its own, so it is built manually as a static library after FetchContent_Populate:

add_library(csrp STATIC ${csrp_SOURCE_DIR}/srp.c)
target_link_libraries(csrp PUBLIC OpenSSL::Crypto)

Enter fullscreen mode Exit fullscreen mode

OpenSSL is the only system dependency. CI builds on GitHub Actions cover Windows (Chocolatey), Ubuntu (libssl-dev), and macOS (Homebrew openssl@3).

cmake -S . -B build -DCMAKE_BUILD_TYPE=Release
cmake --build build -j$(nproc)

./build/cmd_chat_server serve 0.0.0.0 9000 --password roomsecret
./build/cmd_chat_client connect 127.0.0.1 9000 alice roomsecret

Enter fullscreen mode Exit fullscreen mode


What I Would Change in a Production Version

  1. AES-256-GCM instead of AES-128-CBC + HMAC. Simpler construction, no padding oracle surface, authenticated natively by the AEAD mode.
  2. Ephemeral ECDH per session (X25519) layered on top of SRP to achieve forward secrecy.
  3. TLS for the transport layer. The current raw TCP is fine for a controlled environment; wrapping with OpenSSL::SSL (or just boringssl) would take the transport threat model off the table.
  4. Per-user credentials. The current single-verifier model makes sense for a shared room but not for a multi-room or multi-tenant system.
  5. io_uring-based event loop on Linux to replace thread-per-connection for anything that needs to scale.

Source

GitHub: double-k-3033/cmd-chat-cpp

The implementation is intentionally small — around 600 lines across all source files — so the full crypto flow is traceable from a single reading session. If you are evaluating PAKE schemes, building a custom secure channel in C++, or just want a working reference for HKDF + Fernet without an opaque wrapper library, it should be useful.


Tags: cpp cryptography security networking systems