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

推荐订阅源

爱范儿
爱范儿
博客园_首页
U
Unit 42
Apple Machine Learning Research
Apple Machine Learning Research
云风的 BLOG
云风的 BLOG
MongoDB | Blog
MongoDB | Blog
美团技术团队
H
Help Net Security
G
Google Developers Blog
B
Blog RSS Feed
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
aimingoo的专栏
aimingoo的专栏
Google DeepMind News
Google DeepMind News
J
Java Code Geeks
M
MIT News - Artificial intelligence
腾讯CDC
IT之家
IT之家
Vercel News
Vercel News
C
Check Point Blog
博客园 - 三生石上(FineUI控件)
Last Week in AI
Last Week in AI
I
InfoQ
博客园 - 司徒正美
A
About on SuperTechFans

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
AES-256-GCM Encryption in Rust — Securing Local App Data
hiyoyo · 2026-06-16 · via DEV Community
Cover image for AES-256-GCM Encryption in Rust — Securing Local App Data

hiyoyo

All tests run on an 8-year-old MacBook Air. All results from shipping 7 Mac apps as a solo developer. No sponsored opinion.

Hiyoko PDF Vault encrypts PDFs with AES-256-GCM. Here's the implementation — the parts that aren't obvious from the docs.


Why AES-256-GCM

AES-256-GCM is authenticated encryption. It provides both confidentiality (the data is encrypted) and integrity (you know if the data was tampered with). Without authentication, encrypted data can be modified without detection.

For document encryption, use authenticated encryption. AES-256-GCM is the standard choice.


The implementation with aes-gcm

[dependencies]
aes-gcm = "0.10"
rand = "0.8"

use aes_gcm::{
    aead::{Aead, AeadCore, KeyInit, OsRng},
    Aes256Gcm, Key, Nonce,
};

pub fn encrypt(data: &[u8], key: &[u8; 32]) -> Result<Vec<u8>, AppError> {
    let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(key));

    // Generate random nonce — never reuse a nonce with the same key
    let nonce = Aes256Gcm::generate_nonce(&mut OsRng);

    let ciphertext = cipher
        .encrypt(&nonce, data)
        .map_err(|_| AppError::Encryption("Encryption failed".into()))?;

    // Prepend nonce to ciphertext — you need it for decryption
    let mut result = nonce.to_vec();
    result.extend_from_slice(&ciphertext);

    Ok(result)
}

pub fn decrypt(data: &[u8], key: &[u8; 32]) -> Result<Vec<u8>, AppError> {
    if data.len() < 12 {
        return Err(AppError::Encryption("Data too short".into()));
    }

    let (nonce_bytes, ciphertext) = data.split_at(12);
    let nonce = Nonce::from_slice(nonce_bytes);
    let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(key));

    cipher
        .decrypt(nonce, ciphertext)
        .map_err(|_| AppError::Encryption("Decryption failed — wrong key or corrupted data".into()))
}


Key derivation from password

Never use a password directly as an AES key. Use Argon2id to derive a key:

argon2 = "0.5"

use argon2::{Argon2, PasswordHasher, password_hash::SaltString};

pub fn derive_key(password: &str, salt: &[u8; 32]) -> Result<[u8; 32], AppError> {
    let argon2 = Argon2::default();
    let mut key = [0u8; 32];

    argon2
        .hash_password_into(password.as_bytes(), salt, &mut key)
        .map_err(|_| AppError::Encryption("Key derivation failed".into()))?;

    Ok(key)
}

Store the salt with the encrypted data. The salt is not secret — it just prevents rainbow table attacks.


The nonce rule

Never reuse a nonce with the same key. With a 96-bit random nonce and OsRng, collision probability is negligible for any realistic number of encryptions. Always generate fresh nonces with a cryptographically secure RNG.


Storing encrypted PDFs

Format: [salt (32 bytes)][nonce (12 bytes)][ciphertext]

Everything needed for decryption is in the file. The password is the only secret.


TL;DR: Use aes-gcm crate for AES-256-GCM encryption — authenticated encryption that catches tampering. Derive keys from passwords with Argon2id (never use passwords directly as keys). Store format: [salt][nonce][ciphertext]. Generate a fresh nonce per encryption with OsRng.


If this was useful, a ❤️ helps more than you'd think — thanks!

Hiyoko PDF Vault | X → @hiyoyok