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

推荐订阅源

cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Hacker News - Newest:
Hacker News - Newest: "LLM"
S
Security Affairs
PCI Perspectives
PCI Perspectives
Google Online Security Blog
Google Online Security Blog
W
WeLiveSecurity
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Recent Commits to openclaw:main
Recent Commits to openclaw:main
P
Privacy & Cybersecurity Law Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
S
Security @ Cisco Blogs
Security Archives - TechRepublic
Security Archives - TechRepublic
Cyberwarzone
Cyberwarzone
L
Lohrmann on Cybersecurity
TaoSecurity Blog
TaoSecurity Blog
V
Visual Studio Blog
博客园 - 聂微东
Scott Helme
Scott Helme
博客园 - 【当耐特】
K
Kaspersky official blog
Security Latest
Security Latest
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
MyScale Blog
MyScale Blog
Schneier on Security
Schneier on Security
WordPress大学
WordPress大学
博客园 - 叶小钗
C
Check Point Blog
V2EX - 技术
V2EX - 技术
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - Franky
T
Tor Project blog
Apple Machine Learning Research
Apple Machine Learning Research
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
腾讯CDC
雷峰网
雷峰网
博客园_首页
美团技术团队
Y
Y Combinator Blog
C
CERT Recently Published Vulnerability Notes
AWS News Blog
AWS News Blog
月光博客
月光博客
N
Netflix TechBlog - Medium
Last Week in AI
Last Week in AI
Recent Announcements
Recent Announcements
Google DeepMind News
Google DeepMind News
Help Net Security
Help Net Security
P
Proofpoint News Feed
MongoDB | Blog
MongoDB | Blog
C
Cybersecurity and Infrastructure Security Agency CISA

Stonecharioteer on Tech

I Traced My Traffic Through a Home Tailscale Exit Node What Was I Reading Last? In Three Not-So-Easy Pieces Dogfooding Is Hard Code blocks in your books, finally GoForGo v0.9.0 Merrilin - We built an app to read books I use a Macbook now Data Structures & Algorithms - Preparing for Interviews Using a local DNS namespace for local service discovery Direction KOllector - Publishing KOReader Highlights gbt: branches touched in the last 24 hours A Soiree into Symbols in Ruby Some Smalltalk about Ruby Loops Ruby Blocks Returning from Ruby Blocks, Procs and Lambdas My Linux Laptop Finally Works: How Claude Helped Me Fix Years of Annoyances TIL: Watchexec - Modern File Watching for Development Workflows A Less Busy Mind GoForGo - Learn Go through live examples Migrating My Old Blog to Hugo with Claude The Qtile Window Manager: A Python-Powered Tiling Experience Read the RFCs that Built the Internet Py-x-Protobuf - Or How I Learned to Stop Worrying and Love Protocol Buffers Python Reverse a List New Beginnings Leaving ChainSafe Systems Screen Lock for Cinnamon Desktop using Zenity and Terminal Commands Crews Not Teams A System for Getting Better at LeetCode So Far So Rust Retrying HTTP Requests with Rust A Primer on Control Charts Learning Rust Explicit is Better than Implicit: Rust for Pythonistas Using Custom Delimiters in Jinja Templates TIL: Creating Fixed Length Iterables in Python Documentation Without Assumption Vagrant Python - A Reflection in 2022 Learning Golang No, A Virtual Machine Is Not Enough: Why Developers Need Native Linux Empathy in Tech For Those Who Came in Late A Weekend With PostgreSQL TIL: Gooey and Python Fire for Quick GUIs and CLIs TIL: 2ality - Dr. Axel Rauschmayer's JavaScript Blog TIL: MassDNS - High-Performance Bulk DNS Lookups TIL: Matomo Analytics, Google Tech Writing, Memory Programming, and NES TV Signals TIL: MontyDB - MongoDB Implemented in Python Returning to the Craft of Programming TIL: CPUFetch, OneFetch, and Learn CSS TIL: DNS Performance Testing and Pi-hole with Unbound TIL: Eli Bendersky's Blog, Awesome By Example, NoCoDB, and Martin Kleppmann TIL: CRDTs, Extreme HTTP Performance, and BYTEPATH Game TIL: AutoInvent, ASGI, Python Packaging, RAPIDS GPU Computing, and FlaskCon TIL: MangaDesk - Terminal Client for MangaDex TIL: McFly - Smart Shell History Search TIL: Siege Load Testing and Awesome FastAPI Resources TIL: Ventoy Bootable USB and Justniffer Network Analysis TIL: CLI Code Review, Git Split Diffs, and Internal Combustion Engine TIL: Benford's Law, Web Security Headers, Event Sourcing, and Mozilla Security Guidelines How to Write Documentation - The README.md File The Importance of Documentation TIL: NNgroup UX Research, SponsorBlock, and Labella Python Library TIL: The Little Book of Rust Macros and Rust Performance Book TIL: Git-Bug Distributed Issue Tracker and Omni Kubernetes Monitoring TIL: Zellij - Modern Terminal Multiplexer TIL: How Discord Handles 2.5 Million Concurrent Voice Users TIL: Volumio - The Audiophile Music Player TIL: Areopagitica - Milton's Defense of Free Speech TIL: Fast Node Manager, Zoxide Smart CD, Technical Writing, PyO3, and Qubes OS TIL: Slurm Workload Manager for HPC Clusters TIL: Data Visualization Guide and Oso Authorization Academy TIL: CORS Deep Dive, Piku Tiny PaaS, Rust Strings, and Deno Standard Library TIL: Raspberry Pi OS Development, Vim Beginner Guide, Password Management, and QueryBook TIL: uBlock Origin Performance Optimization on Firefox TIL: Breaking PostgreSQL at Scale and LeetCode Problem Patterns TIL: Awesome Tmux Resources for Terminal Multiplexing TIL: Grit - A Multitree-Based Personal Task Manager TIL: Lens 4.2 Kubernetes IDE, Shell Scripting Guide, and Dark HTTP Server Do The Job You Hate So You Won't Hate The Job You Love TIL: Innernet VPN Solution and NoteCalc Calculator App TIL: Argo CD for GitOps and Lens Kubernetes IDE TIL: Modern Rust CLI Tools - System Monitoring, HTTP Requests, and DNS TIL: tz - A Time Zone Helper Tool TIL: Distributed Systems Education, Fallacies, and Self-Hosted Internet Archiving TIL: Real-Time Voice Cloning Technology TIL: ChartMuseum for Helm, AMD's Corporate Journey, and Kubernetes Pod Scaling TIL: Docker and Kubernetes Tools - Whaler, Descheduler, and Dive TIL: Post-Mortem Collection, Terminal Plotting, and Technical Twitter TIL: Dark Mode Toggle Web Component by Google Chrome Labs TIL: Python eval(), exec(), and compile() Functions TIL: Camelot PDF Tables, PostgreSQL Row Level Security, Zerodha Varsity, and Write Yourself a Git TIL: fuser Command for Process and File Investigation TIL: i Hate Regex - The Ultimate Regex Cheat Sheet TIL: Dolt - Git for Data and Database Version Control TIL: x86 Assembly Programming and SafeEyes Break Reminder TIL: Comprehensive Distributed Systems Reading List TIL: Cosmopolitan C Library, Distributed Systems Book, High Performance Browser Networking, and Rust Roguelike Tutorial
TIL: /dev/urandom and /dev/random for Cryptographically Secure Random Generation
2020-10-31 · via Stonecharioteer on Tech

Today I discovered the important distinctions between /dev/urandom and /dev/random, and their proper usage for secure random number generation.

Understanding Random Devices

Unix-like systems provide special devices for accessing random data from the kernel’s entropy pool:

/dev/random vs /dev/urandom:

/dev/random - “True” Random:

  • Blocks when entropy pool is empty
  • Provides cryptographically secure random data
  • Slower due to blocking behavior
  • Suitable for generating long-term keys

/dev/urandom - Pseudo-Random:

  • Never blocks (always returns data)
  • Uses cryptographically secure PRNG
  • Faster for most applications
  • Recommended for most use cases

Practical Usage Examples

Basic Random Data Generation:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# Generate 16 bytes of random data
dd if=/dev/urandom bs=16 count=1 2>/dev/null | hexdump -C

# Generate random password
tr -cd '[:alnum:]' < /dev/urandom | head -c 32
# Output: K9mP2qR8vN4LaB3xJ7tY5wZ1cE6fH0sU

# Generate random UUID-like string
dd if=/dev/urandom bs=16 count=1 2>/dev/null | base64 | tr -d '=' | head -c 22
# Output: K9mP2qR8vN4LaB3xJ7tY5w

Cryptographic Applications:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# Generate SSH key entropy
ssh-keygen -t rsa -b 4096 -f ~/.ssh/new_key -N ""
# (Uses /dev/urandom internally)

# Generate random salt for password hashing
openssl rand -base64 32
# Output: K9mP2qR8vN4LaB3xJ7tY5wZ1cE6fH0sUqV3mN8pR2tX=

# Create random initialization vector
dd if=/dev/urandom bs=16 count=1 2>/dev/null | base64
# Output: K9mP2qR8vN4LaB3xJ7tY5w==

System Administration:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
# Generate random MAC address
printf '%02x:%02x:%02x:%02x:%02x:%02x\n' \
  $(od -An -N6 -tu1 /dev/urandom | tr ' ' '\n' | grep -v '^$')
# Output: 4a:3f:2e:1d:5c:8b

# Create random temporary filenames
temp_file="/tmp/$(tr -cd '[:alnum:]' < /dev/urandom | head -c 16)"
echo "Random temp file: $temp_file"

# Generate random port numbers
random_port=$((RANDOM % 64512 + 1024))
echo "Random port: $random_port"

Programming Language Integration

Shell Scripting:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
#!/bin/bash

# Function to generate secure random string
generate_secure_random() {
    local length=${1:-32}
    local charset=${2:-'[:alnum:]'}

    tr -cd "$charset" < /dev/urandom | head -c "$length"
}

# Generate API key
api_key=$(generate_secure_random 64 '[:alnum:]')
echo "API Key: $api_key"

# Generate session token
session_token=$(generate_secure_random 32 '[:alnum:]')
echo "Session Token: $session_token"

# Generate random hex string
hex_string=$(dd if=/dev/urandom bs=16 count=1 2>/dev/null | xxd -p -c 32)
echo "Hex String: $hex_string"

Python Integration:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
import os
import secrets
import base64

# Using os.urandom (preferred for cryptographic use)
random_bytes = os.urandom(32)
print(f"Random bytes: {random_bytes.hex()}")

# Using secrets module (Python 3.6+)
secure_token = secrets.token_urlsafe(32)
print(f"Secure token: {secure_token}")

# Generate cryptographically secure password
import string
alphabet = string.ascii_letters + string.digits + "!@#$%^&*"
password = ''.join(secrets.choice(alphabet) for _ in range(16))
print(f"Secure password: {password}")

# Random UUID
import uuid
random_uuid = uuid.uuid4()
print(f"Random UUID: {random_uuid}")

System Monitoring:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# Check available entropy
cat /proc/sys/kernel/random/entropy_avail
# Output: 3847 (bits of entropy available)

# Monitor entropy pool
watch -n 1 'cat /proc/sys/kernel/random/entropy_avail'

# Check random device statistics
cat /proc/sys/kernel/random/poolsize
cat /proc/sys/kernel/random/read_wakeup_threshold
cat /proc/sys/kernel/random/write_wakeup_threshold

Security Considerations

When to Use Each Device:

Use /dev/urandom for:

  • Session tokens and API keys
  • Password generation
  • Initialization vectors
  • Salts for password hashing
  • General cryptographic purposes

Use /dev/random for:

  • Long-term cryptographic keys
  • Certificate generation (rarely needed directly)
  • One-time pads
  • When you need maximum entropy guarantees

Best Practices:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
# Good: Fast and secure for most uses
password=$(tr -cd '[:alnum:]' < /dev/urandom | head -c 20)

# Avoid: Slow and usually unnecessary
# password=$(tr -cd '[:alnum:]' < /dev/random | head -c 20)

# Good: Check if enough entropy is available
if [ $(cat /proc/sys/kernel/random/entropy_avail) -lt 100 ]; then
    echo "Warning: Low entropy available"
fi

# Good: Use appropriate tools
openssl rand -base64 32  # Uses /dev/urandom internally

Common Pitfalls:

1
2
3
4
5
6
7
8
# Bad: Predictable random data
password=$(date +%s | sha256sum | head -c 20)

# Bad: Using RANDOM for cryptographic purposes
session_id=$RANDOM$RANDOM$RANDOM

# Good: Cryptographically secure
session_id=$(tr -cd '[:alnum:]' < /dev/urandom | head -c 32)

Performance Comparison:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# Benchmark random data generation
time dd if=/dev/urandom bs=1M count=10 of=/dev/null 2>/dev/null
# Typically: ~0.1-0.5 seconds

time dd if=/dev/random bs=1M count=10 of=/dev/null 2>/dev/null
# May block indefinitely on low-entropy systems

# Test entropy depletion
dd if=/dev/random bs=1 count=1000 of=/dev/null
# Will likely block after some bytes

Understanding these random devices is crucial for implementing secure systems, as using the wrong source of randomness can compromise the security of cryptographic operations.