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

推荐订阅源

OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
人人都是产品经理
人人都是产品经理
IT之家
IT之家
T
The Blog of Author Tim Ferriss
V
V2EX
博客园 - 聂微东
The Cloudflare Blog
Blog — PlanetScale
Blog — PlanetScale
A
About on SuperTechFans
U
Unit 42
Vercel News
Vercel News
L
LangChain Blog
博客园 - 司徒正美
H
Help Net Security
Recent Announcements
Recent Announcements
Recorded Future
Recorded Future
V
Visual Studio Blog
Jina AI
Jina AI
Microsoft Azure Blog
Microsoft Azure Blog
GbyAI
GbyAI
Y
Y Combinator Blog
C
Check Point Blog
博客园 - 三生石上(FineUI控件)
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
J
Java Code Geeks
The Register - Security
The Register - Security
The GitHub Blog
The GitHub Blog
B
Blog RSS Feed
F
Fortinet All Blogs
B
Blog
G
Google Developers Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
云风的 BLOG
云风的 BLOG
爱范儿
爱范儿
MongoDB | Blog
MongoDB | Blog
F
Full Disclosure
有赞技术团队
有赞技术团队
罗磊的独立博客
博客园_首页
MyScale Blog
MyScale Blog
aimingoo的专栏
aimingoo的专栏
Google DeepMind News
Google DeepMind News
M
MIT News - Artificial intelligence
N
Netflix TechBlog - Medium
Engineering at Meta
Engineering at Meta
量子位
I
InfoQ
小众软件
小众软件
P
Proofpoint News Feed

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
Implement Encryption By Using AWS Services | 🏗️ Create A KMS Customer Managed Key
Ntombizakhona Mabaso · 2026-06-03 · via DEV Community

Exam Guide: Developer - Associate
🏗️ Domain 2: Security
📘 Task 2: Implement Encryption By Using AWS Services.

Encryption shows up everywhere, especially on this exam. S3, DynamoDB, SQS, Lambda environment variables, RDS, and more. You need to know the difference between client-side and server-side encryption, how KMS works, and when to use each approach.


📘Concepts

Encryption at Rest vs Encryption In Transit

Encryption At Rest

Data stored on disk: S3 Objects, DynamoDB tables, EBS volumes, RDS databases.

Encryption In Transit

Data moving between services or between client and server: HTTPS, TLS, VPN.

Where At Rest In Transit
S3 SSE-S3, SSE-KMS, SSE-C HTTPS (enforced via bucket policy)
DynamoDB Encrypted by default (AWS owned or KMS) HTTPS (always)
RDS KMS encryption SSL/TLS connections
SQS SSE-KMS HTTPS
Lambda env vars KMS (default + optional CMK) HTTPS

KMS Key Types

Type Managed By Cost Use Case
AWS owned keys AWS Free Default encryption (DynamoDB, S3 SSE-S3)
AWS managed keys AWS (in your account) Free (per-use charges) aws/s3, aws/dynamodb (you can't manage them)
Customer managed keys (CMK) You Monthly + per-use Full control: rotation, policies, cross-account

Envelope Encryption

KMS can only directly encrypt up to 4 KB. For larger data, it uses envelope encryption:

1. KMS generates a data key (plaintext + encrypted copy)
2. You encrypt your data with the plaintext data key
3. You store the encrypted data key alongside the encrypted data
4. You discard the plaintext data key from memory
5. To decrypt: KMS decrypts the data key → you decrypt the data

The AWS Encryption SDK handles this automatically.

Server-Side Encryption Options for S3

Option Key Management Use Case
SSE-S3 AWS manages everything Simplest, no KMS costs
SSE-KMS You control the KMS key Audit trail via CloudTrail, key policies
SSE-C You provide the key with every request Full key control, AWS doesn't store the key

Client-Side vs Server-Side Encryption

Aspect Server-Side Client-Side
Who encrypts AWS (after receiving data) You (before sending to AWS)
Data in transit Encrypted by HTTPS Encrypted by you + HTTPS
Key management AWS or KMS You (via KMS or your own keys)
Complexity Simple More complex
Use case Most workloads When you can't trust the storage layer

Key Rotation

  • AWS managed keys: Rotated every year automatically (can't change this)
  • Customer managed keys: Enable automatic rotation (every year)
  • Old key material is kept, existing encrypted data still works
  • The key ID doesn't change with automatic rotation
  • Manual rotation: Create a new key, update alias to point to it

Certificate Management

Service What It Does Cost
ACM Free public SSL/TLS certificates for AWS services Free
AWS Private CA Issue private certificates for internal services Paid

💡ACM certificates can't be exported. They're bound to AWS services (CloudFront, ALB, API Gateway). They auto-renew.


🏗️ Create A KMS Customer Managed Key

Now let's put these concepts into practice:

  • Create a KMS customer managed key
  • Encrypt and decrypt data using KMS
  • Upload objects to S3 with different encryption options (SSE-S3, SSE-KMS)
  • Enable automatic key rotation
  • Encrypt Lambda environment variables with a custom KMS key

Prerequisites


Part I

Create a KMS Customer Managed Key

Step 01: Open the KMS console
Click Create key

Step 02: Configure key

  • Key type: Symmetric
  • Key usage: Encrypt and decrypt

Click Next

Step 03: Add labels

  • Alias: app-encryption-key
  • Description: Customer managed key for application data

Click Next

Step 04: Define key administrative permissions - optional

  • Key administrators: Select your IAM user

Click Next

Step 05: Define key usage permissions - optional

  • Key administrators: Select your IAM user

Click Next

Step 06: Edit key policy - optional
Click Next

Step 07: Review
Click Finish

✅Green banner: Success
Your AWS KMS key was created with alias app-encryption-key and key ID 17fx7cex-17ae-419x-x816-de16fx50x928.

💡 You now have a customer managed KMS key. Note the Key ID and ARN.

Enable Automatic Key Rotation

Step 08: Click on your key (app-encryption-key)

Step 09: Go to the Key material rotations tab
Click Edit

Step 10: Edit automatic key rotation

  • Key rotation: Enable
  • Rotation period in days: 365

Click Save

✅Green banner: Successfully enabled automatic key rotation

💡 With automatic rotation, KMS keeps old key material so existing ciphertext can still be decrypted. The key ID and ARN don't change. With manual rotation (creating a new key), you get a new key ID. Use aliases to abstract this.


Part II

Encrypt and Decrypt Data with KMS

Using the Console

💡 In the KMS console, you can't directly encrypt/decrypt from the UI

Step 01: Create a Lambda function to demonstrate
LambdaCreate function:

  • Name: KMSEncryptionDemo
  • Runtime: Python 3.12
  • Deploy: Code:
import json
import boto3
import base64

kms = boto3.client('kms')
KEY_ID = 'alias/app-encryption-key'

def lambda_handler(event, context):
    """
    Demonstrates KMS encrypt/decrypt operations.

    Key concepts:
    - KMS can directly encrypt up to 4 KB
    - For larger data, use GenerateDataKey (envelope encryption)
    - The AWS Encryption SDK handles envelope encryption automatically
    """
    action = event.get('action', 'encrypt')
    plaintext = event.get('data', 'Hello, this is sensitive data!')

    if action == 'encrypt':
        # Encrypt data (up to 4 KB)
        response = kms.encrypt(
            KeyId=KEY_ID,
            Plaintext=plaintext.encode('utf-8')
        )
        ciphertext_b64 = base64.b64encode(response['CiphertextBlob']).decode('utf-8')

        return {
            'statusCode': 200,
            'body': json.dumps({
                'message': 'Data encrypted successfully',
                'ciphertext': ciphertext_b64,
                'keyId': response['KeyId']
            })
        }

    elif action == 'decrypt':
        # Decrypt data
        ciphertext = base64.b64decode(event['ciphertext'])
        response = kms.decrypt(CiphertextBlob=ciphertext)

        return {
            'statusCode': 200,
            'body': json.dumps({
                'message': 'Data decrypted successfully',
                'plaintext': response['Plaintext'].decode('utf-8')
            })
        }

    elif action == 'generate_data_key':
        # Generate a data key for envelope encryption
        response = kms.generate_data_key(
            KeyId=KEY_ID,
            KeySpec='AES_256'
        )

        return {
            'statusCode': 200,
            'body': json.dumps({
                'message': 'Data key generated (envelope encryption)',
                'plaintextKey': '*** exists in memory only — use it to encrypt, then discard ***',
                'encryptedKey': base64.b64encode(response['CiphertextBlob']).decode('utf-8'),
                'note': 'Store the encrypted key alongside your encrypted data'
            })
        }

Step 02: Add KMS permissions to the Lambda role:
ConfigurationPermissions → click role name
Add permissionsAttach policiesAWSKeyManagementServicePowerUser

Step 03: Test events
Encrypt:

{"action": "encrypt", "data": "My secret credit card number"}

Generate data key:

{"action": "generate_data_key"}


Part III

S3 Encryption Options

Create an S3 Bucket

Step 01: Open the S3 console → Create bucket

Step 02: General configuration

  • Bucket type: General purpose
  • Bucket namespace: Account Regional namespace (recommended)
  • Bucket name prefix: dva-encryption-demo
  • Encryption type: Server-side encryption with Amazon S3 managed keys (SSE-S3)

Step 03: Upload with SSE-S3 (Default)

  • Click Upload
  • Click Add files
  • Add a file (any text file)
  • Click Upload

💡SSE-S3 is applied automatically

Step 04: Upload with SSE-KMS

  • Click Upload
  • Click Add files
  • Expand ▶ Properties
  • Server side encryption: Specify an encryption key
  • Encryption settings: Override bucket settings for default encryption
  • Encryption type: Server-side encryption with AWS Key Management Service keys (SSE-KMS)
  • AWS KMS Key: Choose from your AWS KMS keys
  • Available AWS KMS Key: app-encryption-key
  • Click Upload

Step 05: Verify Encryption
Click on each uploaded file

Step 06: Go to the Properties tab → Server-side encryption settings
You'll see which encryption method was used

💡SSE-KMS gives you an audit trail in CloudTrail (every encrypt/decrypt call is logged). SSE-S3 does not. If a question mentions "audit" or "compliance," SSE-KMS is usually the answer.


Part IV

Encrypt Lambda Environment Variables

Using a Custom KMS Key

Step 01: Open your KMSEncryptionDemo function

Step 02: ConfigurationEnvironment variablesEdit

Step 03: Edit environment variables
Click Add environment variable

  • Key: DB_PASSWORD
  • Value: super-secret-password

Step 04: Expand ▶ Encryption configuration

  • Encryption in transit: ✔ Check Enable helpers for encryption in transit
  • AWS KMS key to encrypt at rest: Use a customer managed key
  • Select app-encryption-key
  • Click the Encrypt button next to DB_PASSWORD

Click Save

The value is now encrypted.
In your code, you'd decrypt it:

import boto3
import base64
import os

kms = boto3.client('kms')

# Decrypt at cold start, cache the result
ENCRYPTED = os.environ['DB_PASSWORD']
DECRYPTED = kms.decrypt(
    CiphertextBlob=base64.b64decode(ENCRYPTED)
)['Plaintext'].decode('utf-8')

def lambda_handler(event, context):
    # Use DECRYPTED: already decrypted at cold start
    print(f"Password length: {len(DECRYPTED)}")  # Don't log the actual password!


🏗️ What You Built | 📘 Exam Concepts Recap

What You Built Exam Concept
Created a Customer Managed KMS key Key types: AWS owned vs AWS managed vs customer managed
Assigned key administrators and key users KMS key policies: separate admin and usage permissions
Enabled automatic key rotation Old key material preserved, key ID unchanged, seamless decryption
Encrypted data directly with kms.encrypt() KMS direct encryption: limited to 4 KB
Called generate_data_key for AES-256 Envelope encryption: encrypt large data locally, protect the key with KMS
Discarded the plaintext data key after use Security best practice: plaintext key lives only in memory
Uploaded S3 objects with SSE-S3 Default encryption: AWS manages everything, no audit trail
Uploaded S3 objects with SSE-KMS Audit trail in CloudTrail, key policy control, cross-account possible
Encrypted Lambda environment variables with a CMK Protecting secrets at rest in Lambda configuration
Decrypted env vars at cold start and cached the result Performance pattern: avoid decrypting on every invocation

⚠️ Clean Up Protocol

  1. S3 → Empty and delete the bucket
  2. Lambda → Delete KMSEncryptionDemo
  3. KMS → Schedule key deletion (7-day minimum waiting period)
  4. IAM → Delete Lambda execution roles
  5. CloudWatch → Delete log groups

Key Takeaways

  1. KMS encrypts up to 4 KB directly: use envelope encryption (GenerateDataKey) for larger data
  2. SSE-S3: simplest. SSE-KMS: audit trail + key control. SSE-C: you provide the key.
  3. Client-side encryption: you encrypt before sending to AWS
  4. Automatic key rotation keeps old key material and existing data ia still decryptable
  5. Use aliases for seamless manual key rotation
  6. Cross-account KMS requires both a key policy AND an IAM policy
  7. ACM = free public certs (can't export). Private CA = private certs (costs money).
  8. Envelope encryption: the AWS Encryption SDK handles this for you

Additional Resources


🏗️