Skip to content

Encryption_gpg

Encryption is the cornerstone of Linux system security. This chapter covers symmetric and asymmetric encryption, GPG key management, disk encryption with LUKS, filesystem-level encryption, and practical production implementations. Mastery of these topics is essential for DevOps and SRE roles securing sensitive data.


┌─────────────────────────────────────────────────────────────────────────┐
│ ENCRYPTION TYPES │
├─────────────────────────────────────────────────────────────────────────┤
│ │
│ SYMMETRIC ASYMMETRIC │
│ ┌─────────┐ ┌─────────┐ ┌─────────┐ │
│ │ AES │ │ RSA │ │ ECC │ │
│ │ 256 │ │ 4096-bit│ │ 384-bit│ │
│ └────┬────┘ └────┬────┘ └────┬────┘ │
│ │ │ │ │
│ └───────────┬────────────┴───────────────┘ │
│ │ │
│ ┌───────▼───────┐ │
│ │ Same Key │ Fast, for bulk data │
│ │ Encrypt/ │ (files, disks) │
│ │ Decrypt │ │
│ └─────────────┘ │
│ │
│ HYBRID (Common Practice) │
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ 1. Generate random symmetric key (AES) │ │
│ │ 2. Encrypt data with symmetric key (fast) │ │
│ │ 3. Encrypt symmetric key with recipient's public key │ │
│ │ 4. Send both encrypted key + encrypted data │ │
│ └─────────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────────┘
AlgorithmKey SizeUse CaseSecurity Level
AES-128128-bitLegacy systemsAdequate
AES-256256-bitStandardVery Strong
RSA-20482048-bitSignatures, key exchangeStandard
RSA-40964096-bitHigh securityVery Strong
ECC-256256-bitMobile/embeddedEquivalent to RSA-3072
ChaCha20256-bitModern, TLSVery Strong

┌─────────────────────────────────────────────────────────────────────────┐
│ GPG ECOSYSTEM │
├─────────────────────────────────────────────────────────────────────────┤
│ │
│ KEY GENERATION │
│ ┌────────────────────────────────────────────────────────────┐ │
│ │ ┌──────────────┐ ┌──────────────┐ │ │
│ │ │ Master Key │ │ Subkeys │ │ │
│ │ │ (Certification) │ (Signing/ │ │ │
│ │ │ - Sign other keys │ Encryption/ │ │ │
│ │ │ - Create subkeys │ Authentication│ │ │
│ │ └──────────────┘ └──────────────┘ │ │
│ └────────────────────────────────────────────────────────────┘ │
│ │
│ KEYRING STRUCTURE │
│ ~/.gnupg/ │
│ ├── pubring.kbx (Public keys + signatures) │
│ ├── pubring.gpg (Legacy public keyring) │
│ ├── secring.gpg (Secret keys - DEPRECATED) │
│ ├── private-keys-v1.d/ (Secret key stubs for gpg-agent) │
│ ├── gpg.conf (Options) │
│ ├── gpg-agent.conf (Agent options) │
│ └── trustdb.gpg (Ownertrust values) │
│ │
│ OPERATIONS │
│ ┌────────────────────────────────────────────────────────────┐ │
│ │ ENCRYPT DECRYPT │ │
│ │ ┌─────────┐ ┌─────────┐ │ │
│ │ │Message │ │ Encrypted│ │ │
│ │ │ File │──►Encrypt──► │ Data │──►Decrypt──►Message │ │
│ │ └─────────┘ with RSA └─────────┘ with RSA └─────────┘ │
│ │ │ (needs private key) │
│ │ │ │ │
│ │ ┌────▼────┐ ┌────▼────┐ │ │
│ │ │Public │ │Private │ │ │
│ │ │Key of │ │Key of │ │ │
│ │ │Receiver │ │Receiver │ │ │
│ │ └─────────┘ └─────────┘ │ │
│ └────────────────────────────────────────────────────────────┘ │
│ │
│ SIGNING VERIFICATION │
│ ┌────────────────────────────────────────────────────────────┐ │
│ │ SIGN VERIFY │ │
│ │ ┌─────────┐ ┌─────────┐ │ │
│ │ │Message/ │──►Sign──► │Signature│──►Verify──► Valid/Invalid│ │
│ │ │ File │ with RSA │ (.sig) │ with public key │ │
│ │ └─────────┘ Private └─────────┘ │ │
│ └────────────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────────┘
Terminal window
# ============================================================
# PRODUCTION KEY GENERATION - Step by Step
# ============================================================
# Step 1: Configure GPG for better security
mkdir -p ~/.gnupg
chmod 700 ~/.gnupg
cat > ~/.gnupg/gpg.conf << 'EOF'
# Use modern algorithms
default-preference-list SHA512 SHA384 SHA256 SHA224 AES256 AES192 AES168
BZIP2 ZLIB ZIP Uncompressed
# Modern keyserver
keyserver hkps://keyserver.ubuntu.com
# Security options
no-tty
no-emit-version
no-comments
# Fast options (if needed for automation)
# use-agent
EOF
cat > ~/.gnupg/gpg-agent.conf << 'EOF'
default-cache-ttl 600
max-cache-ttl 3600
allow-loopback-pinentry
EOF
# Step 2: Generate master key (Certification only)
gpg --full-generate-key
# Select:
# 1. RSA and RSA (default)
# 2. 4096 bits
# 3. Key does not expire (or set reasonable expiry)
# 4. Your name
# 5. Your email
# 6. Passphrase (use a strong, unique password)
# Step 3: Add subkeys for daily use
gpg --edit-key your@email.com
# In gpg> interactive mode:
# addkey
# 4. RSA (sign only) - 4096 bits
# Save
# addkey
# 5. RSA (encrypt only) - 4096 bits
# Save
# addkey
# 6. Authentication - 4096 bits
# Save
# quit
# Step 4: Backup your keys (CRITICAL!)
# Export master key (keep secure!)
gpg --armor --export-secret-keys your@email.com > master-key-backup.asc
gpg --armor --export-secret-subkeys your@email.com > subkeys-backup.asc
# Store these securely (encrypted USB, secure location)
# DELETE the secret keys from your machine after backup!
# Step 5: Export public key for distribution
gpg --armor --export your@email.com > public-key.asc
gpg --send-keys your@email.com # Upload to keyserver
Terminal window
# ============================================================
# KEY MANAGEMENT COMMANDS
# ============================================================
# List keys
gpg --list-keys # Public keys
gpg --list-secret-keys # Private keys
gpg --list-signatures # Signatures on keys
gpg --fingerprint your@email.com # Fingerprint (short form)
# Keyserver operations
gpg --keyserver keyserver.ubuntu.com --search-keys "search term"
gpg --keyserver keyserver.ubuntu.com --recv-key KEYID
gpg --keyserver keyserver.ubuntu.com --send-key KEYID
gpg --refresh-keys # Update all keys from keyserver
# Key editing
gpg --edit-key your@email.com
# Commands: list, uid, key, addkey, delkey, revuid, sign, check, quit
# Change passphrase
gpg --change-passphrase your@email.com
# Expire key
gpg --edit-key your@email.com
# gpg> expire
# gpg> save
# Sign a key (establishing trust)
gpg --sign-key other@email.com # Sign with your key
gpg --lsign-key other@email.com # Local signature (not exported)
# Export/Import
gpg --armor --export your@email.com > public.asc
gpg --armor --export-secret-keys your@email.com > private.asc
gpg --import keyfile.asc
gpg --import --import-filter import-clean-sigs keyfile.asc
# Delete keys
gpg --delete-secret-keys your@email.com # First delete secret
gpg --delete-keys your@email.com # Then public
Terminal window
# ============================================================
# FILE ENCRYPTION - Multiple Methods
# ============================================================
# Method 1: Encrypt for specific recipient
gpg -e -r recipient@email.com file.txt
# Output: file.txt.gpg
# Method 2: Encrypt with compression
gpg -z 9 -e -r recipient@email.com largefile.tar
# -z 9 = maximum compression
# Method 3: Encrypt with symmetric cipher (password-based)
gpg -c sensitive.doc
# Prompts for passphrase
# Output: sensitive.doc.gpg
# Method 4: Encrypt + sign (both encryption and authenticity)
gpg -e -s -u sender@email.com -r recipient@email.com message.txt
# Method 5: ASCII armor output (for email/text)
gpg -a -e -r recipient@email.com file.txt
# Output: file.txt.asc (ASCII format)
# Decryption
gpg -d file.txt.gpg # Decrypt to stdout
gpg -d -o output.txt file.txt.gpg # Decrypt to file
gpg file.txt.gpg # Interactive decryption
# Symmetric decryption
gpg -d symmetric.gpg
# Batch decryption (for scripts)
echo "passphrase" | gpg --batch --yes --passphrase-fd 0 -d file.gpg
Terminal window
# ============================================================
# SIGNING AND VERIFICATION
# ============================================================
# Binary signature (creates .sig file)
gpg --sign document.pdf
# Output: document.pdf.sig
# Clear text signature (for email - visible signature)
gpg --clearsign message.txt
# Output: message.txt.asc
# Contains the message + signature in ASCII
# Detached signature (separate signature file)
gpg --armor --detach-sign document.pdf
# Output: document.pdf.asc
# Use when you don't want to modify original file
# Sign with specific key
gpg -u sender@email.com --sign document.txt
# Multiple signatures
gpg --sign --local-user key1@email.com \
--sign --local-user key2@email.com document.txt
# Verification
gpg --verify file.txt.sig # Verify binary signature
gpg --verify file.txt.asc # Verify ASCII/armored signature
gpg --verify document.pdf.asc document.pdf # Verify detached signature
# Verbose verification (shows key details)
gpg --verify --verbose file.txt.asc
┌─────────────────────────────────────────────────────────────────────────┐
│ WEB OF TRUST │
├─────────────────────────────────────────────────────────────────────────┤
│ │
│ Trust Levels: │
│ ┌─────────────────────────────────────────────────────────────┐ │
│ │ ultimate (u) - You trust this key completely │ │
│ │ (usually your own keys) │ │
│ │ full (f) - You trust this key fully │ │
│ │ marginal (m) - You trust this key somewhat │ │
│ │ never (n) - You do not trust this key │ │
│ │ unknown (o) - No trust decision made │ │
│ └─────────────────────────────────────────────────────────────┘ │
│ │
│ Trust Path Example: │
│ │
│ [YOU] │
│ │ │
│ │ signs │
│ ▼ │
│ ┌─────────────┐ signs ┌─────────────┐ │
│ │ Friend A │ ───────────────► │ Friend B │ │
│ │ (full) │ │ (marginal) │ │
│ └─────────────┘ └─────────────┘ │
│ │ │
│ signs │ │
│ ▼ │
│ ┌─────────────┐ │
│ │ Target │ │
│ │ Key │ │
│ └─────────────┘ │
│ │
│ You trust Target if: │
│ - At least one path with "full" trust, OR │
│ - At least 3 paths with "marginal" trust │
│ │
└─────────────────────────────────────────────────────────────────────────┘
# Trust management commands
gpg --edit-key your@email.com
# gpg> trust
# Select trust level (1-5)
# gpg> quit
Terminal window
# ============================================================
# GPG-AGENT CONFIGURATION
# ============================================================
# Configuration file: ~/.gnupg/gpg-agent.conf
cat > ~/.gnupg/gpg-agent.conf << 'EOF'
# Cache TTL settings
default-cache-ttl 3600 # Default: 600 seconds
max-cache-ttl 86400 # Maximum: 1 day
# PIN entry
pinentry-program /usr/bin/pinentry-gnome3
allow-loopback-pinentry
# Agent lifecycle
# gpg-agent --daemon # Start agent
# gpgconf --kill gpg-agent # Stop agent
# Check agent status
gpg-connect-agent /bye
gpg-agent --homedir ~/.gnupg --daemon
# Reload agent
gpg-connect-agent RELOADAGENT /bye

┌─────────────────────────────────────────────────────────────────────────┐
│ LUKS DISK ENCRYPTION │
├─────────────────────────────────────────────────────────────────────────┤
│ │
│ Physical Disk Layout: │
│ ┌──────────────────────────────────────────────────────────────┐ │
│ │ LUKS Header (1-2MB) │ Encrypted Data │ │
│ │ ┌──────────────────┐ │ ┌─────────────────────────────┐ │ │
│ │ │ Magic String │ │ │ │ │ │
│ │ │ (LUKS version) │ │ │ dm-crypt / dm-luks │ │ │
│ │ │ Key Slots (8) │ │ │ (AES-XTS, plain/luks2) │ │ │
│ │ │ - PBKDF2 params │ │ │ │ │ │
│ │ │ - Salt │ │ │ (Encrypted User Data) │ │ │
│ │ │ - Key Material │ │ │ │ │ │
│ │ └──────────────────┘ │ └─────────────────────────────┘ │ │
│ └──────────────────────────────────────────────────────────────┘ │
│ │
│ Key Slots (8 maximum): │
│ ┌─────────────────────────────────────────────────────────────┐ │
│ │ Slot 0 │ Slot 1 │ Slot 2 │ Slot 3 │ Slot 4 │ Slot 5 │ Slot 6 │Slot 7│
│ │Active │Active │ Empty │ Empty │ Empty │ Empty │ Empty │Empty │
│ └─────────────────────────────────────────────────────────────┘ │
│ Each slot can hold a different passphrase │
│ Allows: key rotation, multiple users, backup passphrases │
│ │
│ Encryption Workflow: │
│ ┌─────────────────────────────────────────────────────────────┐ │
│ │ 1. PBKDF2 derives key from passphrase + salt │ │
│ │ 2. Master Key (stored in header) decrypted temporarily │ │
│ │ 3. Master Key used to encrypt/decrypt disk data │ │
│ │ 4. Master Key held in kernel keyring (not in header) │ │
│ └─────────────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────────┘
Terminal window
# ============================================================
# LUKS DISK ENCRYPTION - Complete Guide
# ============================================================
# Prerequisites
sudo apt install cryptsetup # Debian/Ubuntu
sudo yum install cryptsetup # RHEL/CentOS
# Step 1: Prepare the device
lsblk # List block devices
sudo parted /dev/sdb # Partition if needed
sudo mkfs.ext4 /dev/sdb1 # Create filesystem first
# OR create partition: sudo parted /dev/sdb mklabel gpt mkpart primary 0% 100%
# Step 2: Initialize LUKS container
sudo cryptsetup luksFormat /dev/sdb1
# WARNING: This ERASES all data!
# Enter YES (uppercase)
# Enter and confirm passphrase (use strong passphrase!)
# With custom options:
sudo cryptsetup luksFormat --type luks2 \
--cipher aes-xts-plain64 \
--key-size 512 \
--hash sha512 \
--iter-time 5000 \
--pbkdf argon2id \
/dev/sdb1
# LUKS2 is the default since cryptsetup 2.1.0
# Argon2id is recommended (memory-hard, GPU resistant)
# Step 3: Open the container
sudo cryptsetup luksOpen /dev/sdb1 secure_volume
# Creates device mapper: /dev/mapper/secure_volume
# Step 4: Create filesystem
sudo mkfs.ext4 /dev/mapper/secure_volume
# Step 5: Mount and use
sudo mkdir /mnt/encrypted
sudo mount /dev/mapper/secure_volume /mnt/encrypted
# Write some test data
echo "Sensitive data" | sudo tee /mnt/encrypted/secret.txt
# Step 6: Unmount and close
sudo umount /dev/mapper/secure_volume
sudo cryptsetup luksClose secure_volume
# ============================================================
# LUKS MANAGEMENT
# ============================================================
# View LUKS header info
sudo cryptsetup luksDump /dev/sdb1
# Shows: version, cipher, key size, UUID, key slots, etc.
# Add a new passphrase
sudo cryptsetup luksAddKey /dev/sdb1
# Prompts for existing passphrase, then new passphrase
# Remove a passphrase
sudo cryptsetup luksRemoveKey /dev/sdb1
# Must have at least one remaining passphrase!
# Change passphrase
sudo cryptsetup luksChangeKey /dev/sdb1
# Can also change specific slot: luksChangeKey -S 0 /dev/sdb1
# Add key to specific slot
sudo cryptsetup luksAddKey -S 1 /dev/sdb1
# Remove key from specific slot
sudo cryptsetup luksRemoveKey -S 1 /dev/sdb1
# Check which slots are used
sudo cryptsetup luksDump /dev/sdb1 | grep -A 10 "Key Slots"
# Backup LUKS header (CRITICAL for recovery!)
sudo cryptsetup luksHeaderBackup /dev/sdb1 --header-backup-file luks_header.img
# Store securely - with this, attacker can try to crack your passphrase
# Restore LUKS header
sudo cryptsetup luksHeaderRestore /dev/sdb1 --header-backup-file luks_header.img
# Resume suspended container (after system sleep)
sudo cryptsetup luksResume /dev/mapper/secure_volume
Terminal window
# ============================================================
# AUTOMOUNT WITH KEYFILE (For servers/automation)
# ============================================================
# Method 1: Create random keyfile
sudo dd if=/dev/urandom of=/root/luks.key bs=4096 count=1
sudo chmod 600 /root/luks.key
# Add keyfile to LUKS slot
sudo cryptsetup luksAddKey /dev/sdb1 /root/luks.key
# Method 2: Add keyfile to specific slot
sudo cryptsetup luksAddKey -S 2 /dev/sdb1 /root/luks.key
# Method 3: Configure /etc/crypttab (auto-unlock at boot)
# /etc/crypttab:
# secure_volume /dev/sdb1 /root/luks.key luks,discard
# Method 4: Using systemd (modern approach)
# /etc/systemd/system/mnt-secure.mount
[Unit]
Description=Encrypted Secure Volume
[Mount]
What=/dev/mapper/secure_volume
Where=/mnt/secure
Type=ext4
Options=defaults
# /etc/fstab:
# /dev/mapper/secure_volume /mnt/secure ext4 defaults 0 2
# Create systemd service to unlock at boot
# /etc/systemd/system/luks-unlock.service
[Unit]
Description=Unlock LUKS volume
Requires=systemd-remount-fs.service
After=systemd-remount-fs.service
[Service]
Type=oneshot
ExecStart=/usr/bin/cryptsetup luksOpen /dev/sdb1 secure_volume
ExecStart=/usr/bin/mount /dev/mapper/secure_volume /mnt/secure
RemainAfterExit=yes
[Install]
WantedBy=multi-user.target
# Enable: sudo systemctl enable luks-unlock.service
Terminal window
# ============================================================
# LUKS PERFORMANCE OPTIMIZATION
# ============================================================
# Benchmark encryption options
sudo cryptsetup benchmark
# Example output:
# KDF, 5 iterations, 64 memory, threads: 4
# PBKDF2-sha256 362k
# PBKDF2-sha512 337k
# argon2id 170k (memory-hard, slower but more secure)
# Recommended options for new containers:
sudo cryptsetup luksFormat --type luks2 \
--cipher aes-xts-plain64 \ # XTS mode for disk encryption
--key-size 512 \ # 512-bit = 256-bit effective
--hash sha512 \ # For key derivation
--iter-time 5000 \ # ms for PBKDF2 (adjust for security)
--pbkdf argon2id \ # Better than PBKDF2
/dev/sdb1
# For older systems (LUKS1):
sudo cryptsetup luksFormat --type luks1 \
--cipher aes-xts-plain64 \
--key-size 512 \
--hash sha512 \
--iter-time 3000 \
--pbkdf pbkdf2 \
/dev/sdb1
# Check if hardware encryption is available
cat /proc/crypto | grep -i aes
ls /dev/crypto # Should exist if available
# Check CPU for AES-NI support
grep -o aes /proc/cpuinfo | head -1
# Or: lscpu | grep -i aes
Terminal window
# ============================================================
# EMERGENCY RECOVERY PROCEDURES
# ============================================================
# Scenario 1: System won't boot - LUKS password not accepted
# Boot from rescue media, then:
# Check if LUKS container is accessible
sudo cryptsetup luksDump /dev/sdX1
# If header corrupted, restore from backup
sudo cryptsetup luksHeaderRestore /dev/sdX1 --header-backup-file /path/to/backup.img
# Scenario 2: Forgotten passphrase - but you have backup
# If you have another working slot:
sudo cryptsetup luksOpen /dev/sdX1 recovery
# Scenario 3: Header completely corrupted
# Without backup, data is LOST - this is why backups are critical!
# Only cryptographically secure erasure can recover
# Scenario 4: Suspended container won't resume
# After system crash/suspend
sudo dmsetup remove /dev/mapper/secure_volume
sudo cryptsetup luksOpen /dev/sdX1 secure_volume
# Scenario 5: Check LUKS integrity
sudo cryptsetup luksDump /dev/sdX1
# Check "Failed authentication counter" - too many failures = lockout
# Emergency: Wipe LUKS container completely
sudo cryptsetup luksErase /dev/sdX1
# Or: sudo wipefs -a /dev/sdX1

Terminal window
# ============================================================
# ECryptfs - Stacked Filesystem Encryption
# ============================================================
# Install
sudo apt install ecryptfs-utils
# Create encrypted directory
mkdir -p ~/Private
sudo mount -t ecryptfs ~/Private ~/Private
# Select: passphrase, aes, plain, no signature, no encryption of filenames
# Using the automated tool
ecryptfs-setup-private
# Creates ~/.Private and ~/Private
# ~/.Private contains encrypted data
# ~/Private is the decrypted view when mounted
# Mount manually with options
sudo mount -t ecryptfs \
-o key=passphrase,ecryptfs_cipher=aes,ecryptfs_key_bytes=32,\
ecryptfs_passthrough=n,ecryptfs_enable_filename_crypt=y \
/home/user/.Private /home/user/Private
# Unmount (hides data)
ecryptfs-umount-private
# Add signature to keyring for auto-mount
ecryptfs-add-passphrase --fnek
# Add to /etc/ecryptfs/rc.local or pam_ecryptfs
Terminal window
# ============================================================
# fscrypt - Native Linux Encryption (Kernel 4.2+)
# ============================================================
# Install
sudo apt install fscrypt libpam-fscrypt
# Enable on filesystem
sudo tune2fs -O encrypt /dev/sdX1
# Or at mount: mount -o encrypt /dev/sdX1 /mnt
# Setup
fscrypt setup
fscrypt setup root # For root user
fscrypt setup other_user # For other users
# Create encrypted directory
mkdir -p ~/encrypted
fscrypt encrypt ~/encrypted
# Check status
fscrypt status
fscrypt status ~/encrypted
# Lock/Unlock
fscrypt lock ~/encrypted
fscrypt unlock ~/encrypted

Terminal window
# ============================================================
# ENCRYPTED SWAP
# ============================================================
# Method 1: Using systemd (recommended)
# /etc/fstab:
# /dev/mapper/cryptswap none swap sw 0 0
# /etc/systemd/system/cryptswap.service:
[Unit]
Description=Encrypted Swap
After=swap.target
[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/sbin/cryptsetup open --type plain /dev/sda2 cryptswap --key-file /root/swap.key
ExecStart=/sbin/mkswap /dev/mapper/cryptswap
ExecStop=/sbin/cryptsetup close cryptswap
[Install]
WantedBy=multi-user.target
# Create keyfile
dd if=/dev/urandom of=/root/swap.key bs=4096 count=1
chmod 600 /root/swap.key
# Enable
sudo systemctl enable cryptswap.service
sudo systemctl start cryptswap.service
# Method 2: Using /etc/crypttab (legacy)
# /etc/crypttab:
# cryptswap /dev/sda2 /dev/urandom swap,cipher=aes-xts-plain64,size=512

Terminal window
# ============================================================
# OPENSSL - TLS CERTIFICATES
# ============================================================
# Generate private key
openssl genrsa -out server.key 2048
openssl genrsa -out server.key 2048 # With encryption
openssl genrsa -aes256 -out server.key 2048
# Generate CSR
openssl req -new -key server.key -out server.csr
openssl req -new -key server.key -out server.csr \
-subj "/C=US/ST=State/L=City/O=Organization/CN=example.com"
# Self-signed certificate (for testing)
openssl req -x509 -days 365 -key server.key -in server.csr -out server.crt
openssl req -x509 -days 365 -newkey rsa:2048 -keyout server.key -out server.crt
# Verify certificate
openssl x509 -in server.crt -text -noout
openssl verify -CAfile ca.crt server.crt
# Extract info
openssl x509 -in server.crt -noout -subject
openssl x509 -in server.crt -noout -issuer
openssl x509 -in server.crt -noout -dates
openssl x509 -in server.crt -noout -fingerprint
# Convert formats
openssl x509 -in cert.pem -outform DER -out cert.der
openssl x509 -in cert.der -inform DER -outform PEM -out cert.pem
# Generate DH parameters
openssl dhparam -out dhparam.pem 2048
# Test SSL connection
openssl s_client -connect example.com:443
openssl s_client -connect example.com:443 -showcerts
openssl s_client -connect example.com:443 -verify_return_error
# Check cipher suites
openssl ciphers -v 'HIGH:!aNULL:!MD5'

Terminal window
# ============================================================
# PRODUCTION ENCRYPTION CHECKLIST
# ============================================================
# 1. Disk Encryption
# [ ] All sensitive data disks encrypted with LUKS
# [ ] LUKS header backed up and stored securely
# [ ] Keyfiles protected (permissions 600)
# [ ] Multiple LUKS passphrases for recovery
# 2. Filesystem Encryption
# [ ] Home directories encrypted (fscrypt/ecryptfs)
# [ ] Database files encrypted
# [ ] Log files containing sensitive data encrypted
# 3. Network Encryption
# [ ] All production traffic uses TLS 1.2+
# [ ] Strong cipher suites only
# [ ] Certificates from trusted CA
# [ ] Certificate expiration monitoring
# 4. Key Management
# [ ] GPG keys backed up securely
# [ ] Expiration dates set on all keys
# [ ] Revocation certificates generated
# [ ] Key rotation policy in place
# 5. Swap and Temp
# [ ] Swap encrypted
# [ ] /tmp on encrypted volume if sensitive data
# [ ] /dev/shm permissions restricted
# 6. Monitoring
# [ ] Failed decryption attempts logged
# [ ] LUKS authentication failures monitored
# [ ] Certificate expiration alerts
# 7. Recovery
# [ ] Documented recovery procedures
# [ ] Test recovery process
# [ ] Multiple authorized individuals for recovery

┌─────────────────────────────────────────────────────────────────────────┐
│ ENCRYPTION INTERVIEW QUESTIONS │
├─────────────────────────────────────────────────────────────────────────┤
Q1: Explain the difference between symmetric and asymmetric encryption. │
A1: │
- Symmetric: Same key for encryption/decryption (AES, ChaCha20) │
- Pros: Fast, efficient for bulk data │
- Cons: Key distribution problem │
- Asymmetric: Public key encrypts, private key decrypts (RSA, ECC) │
- Pros: Solves key distribution, enables signatures │
- Cons: Slow, computationally intensive │
- Hybrid: Encrypt data with symmetric key, encrypt key with │
asymmetric key (standard practice for file encryption) │
─────────────────────────────────────────────────────────────────────────┤
Q2: How does GPG implement the Web of Trust? │
A2: │
- Each user can sign other users' public keys │
- Trust levels: ultimate > full > marginal > never > unknown │
- A key is considered trusted if: │
- One path with full trust, OR │
- Three paths with marginal trust │
- Reduces dependency on centralized CAs │
- More complex but decentralized │
─────────────────────────────────────────────────────────────────────────┤
Q3: Describe the LUKS encryption structure and key slots. │
A3: │
- LUKS header contains: │
- Magic string, version, cipher info │
- 8 key slots (each can hold encrypted master key) │
- PBKDF2 parameters for key derivation │
- Master key encrypts actual data (via dm-crypt) │
- Different passphrases can unlock different slots │
- Allows: key rotation, backup passphrases, multiple users │
- Header backup critical for recovery │
─────────────────────────────────────────────────────────────────────────┤
Q4: What are the differences between LUKS1 and LUKS2? │
A4: │
| Feature | LUKS1 | LUKS2 | │
|----------------|-----------------|--------------------------| │
| Max slots | 8 | 8 (unlimited internally) | │
| Header size | 512KB fixed | 16MB default | │
| KDF | PBKDF2 | Argon2id, PBKDF2 | │
| Integrity | None | dm-integrity | │
| Reencryption | Offline only | Online reencryption | │
| Performance | Good | Better (more iterations) | │
─────────────────────────────────────────────────────────────────────────┤
Q5: How would you recover data from a corrupted LUKS container? │
A5: │
1. First, backup the entire device (dd if=/dev/sdX of=backup.img) │
2. Try to read header: cryptsetup luksDump /dev/sdX │
3. If header corrupted, restore from backup: │
cryptsetup luksHeaderRestore /dev/sdX --header-backup-file backup │
4. Try each key slot: cryptsetup luksOpen --test-crypto /dev/sdX │
5. If header completely lost and no backup - data is UNRECOVERABLE │
6. Use grep -a /dev/sdX for "LUKS" magic string to find header │
─────────────────────────────────────────────────────────────────────────┤
Q6: Explain the difference between dm-crypt and dm-luks. │
A6: │
- dm-crypt: Plain device encryption, no LUKS header │
- No key slots, single passphrase │
- Can be faster (no header I/O) │
- Harder to verify correct passphrase │
- No key rotation │
- dm-luks: LUKS wrapper around dm-crypt │
- Has LUKS header with key slots │
- Multiple passphrases │
- Key management features │
- Default choice for most use cases │
─────────────────────────────────────────────────────────────────────────┤
Q7: What is Argon2id and why is it preferred over PBKDF2? │
A7: │
- Argon2id is winner of Password Hashing Competition (2015) │
- Memory-hard: Uses significant RAM to compute hash │
- GPU-resistant: Hard to parallelize on GPU clusters │
- Better security margin than PBKDF2 │
- Recommended for new LUKS2 containers │
─────────────────────────────────────────────────────────────────────────┤
Q8: How do you secure a Linux server's sensitive data at rest? │
A8: │
1. Encrypt system disk (LUKS) - prevents physical theft │
2. Encrypt data drives with separate LUKS containers │
3. Use filesystem-level encryption for user directories │
4. Encrypt swap and /tmp │
5. Store encryption keys in hardware security modules (HSM) │
6. Implement proper key management: rotation, backup, access control │
7. Enable full-disk encryption on laptops/mobile devices │
─────────────────────────────────────────────────────────────────────────┤
Q9: What are the security considerations when using keyfiles? │
A9: │
- Keyfile is just as secure as the passphrase it replaces │
- If keyfile is compromised, entire encryption is compromised │
- Best practices: │
- Use strong randomness: dd if=/dev/urandom (not /dev/random) │
- Restrict permissions: chmod 600 keyfile │
- Store separately from encrypted data │
- Use TPM for automatic unlock without exposed keyfile │
- Encrypt keyfile itself with another layer of protection │
─────────────────────────────────────────────────────────────────────────┤
Q10: Explain the difference between file encryption and disk encryption.│
A10: │
- Disk/Full-disk encryption: │
- Encrypts entire block device │
- All data at rest protected │
- Transparent to applications │
- LUKS, dm-crypt, VeraCrypt │
- File-level encryption: │
- Encrypts individual files/directories │
- Can have different keys for different files │
- eCryptfs, fscrypt, GPG-encrypted files │
- Portable - encrypted file can be moved │
- Hybrid approach often used in production │
└─────────────────────────────────────────────────────────────────────────┘

Terminal window
# GPG Commands
gpg --full-generate-key # Generate key pair
gpg --list-keys # List public keys
gpg --list-secret-keys # List private keys
gpg -e -r recipient file.txt # Encrypt
gpg -d file.txt.gpg # Decrypt
gpg --sign file.txt # Sign
gpg --verify file.sig # Verify signature
gpg --armor --export email > key.asc # Export public key
gpg --import key.asc # Import key
# LUKS Commands
cryptsetup luksFormat /dev/sdX1 # Create LUKS
cryptsetup luksOpen /dev/sdX1 name # Open container
cryptsetup luksClose name # Close container
cryptsetup luksDump /dev/sdX1 # Show header info
cryptsetup luksAddKey /dev/sdX1 # Add passphrase
cryptsetup luksRemoveKey /dev/sdX1 # Remove passphrase
cryptsetup luksHeaderBackup /dev/sdX1 -f backup.img # Backup header
# OpenSSL Commands
openssl genrsa -out key.pem 2048 # Generate key
openssl req -new -key key.pem -out csr.pem # Generate CSR
openssl x509 -req -days 365 -in csr.pem -signkey key.pem -out cert.pem # Self-signed
openssl x509 -in cert.pem -text -noout # View certificate
openssl s_client -connect host:443 # Test connection
# fscrypt Commands
fscrypt setup # Initialize
fscrypt encrypt directory # Encrypt directory
fscrypt lock directory # Lock directory
fscrypt unlock directory # Unlock directory

  • GPG: Asymmetric encryption for secure communication, signing, and key management
  • Web of Trust: Decentralized trust model through key signatures
  • LUKS: Standard for Linux disk encryption with key slots and secure key derivation
  • LUKS2 vs LUKS1: LUKS2 offers Argon2id, integrity protection, and online reencryption
  • Filesystem Encryption: eCryptfs and fscrypt for directory-level encryption
  • Production: Combine disk encryption, key management, and monitoring

Chapter 36: System Logging - rsyslog, syslog-ng


Last Updated: February 2026