implementing-api-key-security-controls
它能做什么
这个工具可以帮助你为系统创建和管理安全的访问密钥。它确保密钥难以被猜到、不会以不安全的方式存储,并且可以方便地停用或更换。
适用场景
- ✓当你构建一个需要安全的服务器之间访问的新系统时。
- ✓当你需要在不中断服务的情况下,用新密钥替换旧密钥时。
- ✓当你怀疑某个访问密钥可能已经泄露时。
技能链接
https://github.com/mukul975/Anthropic-Cybersecurity-Skills/blob/main/skills/implementing-api-key-security-controls/SKILL.md复制后粘贴给你的 AI(Claude、ChatGPT 或 Cursor),让它按照说明操作。
使用方法
最简单的方法:复制下面的消息,粘贴给你的 AI。它会读取这个技能并按说明操作。
可直接粘贴的消息
适用于 Claude Code、Codex 或 Cursor:在项目文件夹中运行,即可安装该技能。
下载 SKILL.md,放进智能体的技能文件夹。
可以这样问 AI
“为我的后端应用生成一个安全的 API 密钥,权限设为只读,有效期 90 天。”
每周 5 个新技能,1 分钟读完。
工作原理
这个工具会生成随机性很高的密钥,并以加密方式存储。它还可以设置使用限制,并监控密钥是否出现在不安全的位置。
技术内容(原始 SKILL.md)
作者在 GitHub 上的英文原文。
Implementing API Key Security Controls
When to Use
- Designing secure API key generation with sufficient entropy and identifiable prefixes for leak detection
- Implementing server-side API key hashing (never storing keys in plaintext) with SHA-256 or bcrypt
- Building key rotation workflows that allow zero-downtime key replacement for API consumers
- Configuring per-key scoping to limit each API key to specific endpoints, IP ranges, and rate limits
- Setting up automated monitoring for API key leakage in GitHub repos, logs, and client-side code
Do not use API keys as the sole authentication mechanism for user-facing applications. API keys are best suited for server-to-server communication and developer access.
Prerequisites
- Secure random number generator (os.urandom, secrets module) for key generation
- Database with proper encryption at rest for storing hashed API keys
- Redis or similar store for key-to-metadata caching and rate limiting
- Secret scanning tools (GitHub secret scanning, truffleHog, gitleaks)
- Monitoring and alerting infrastructure for key usage anomalies
Workflow
Step 1: Secure API Key Generation
import secrets
import hashlib
import hmac
import time
import json
from datetime import datetime, timedelta
class APIKeyManager:
"""Manages secure API key lifecycle: generation, storage, validation, rotation."""
# Key format: prefix_base64random (e.g., sk_live_a1b2c3d4e5f6...)
# Prefix identifies the key type and environment for leak detection
KEY_PREFIXES = {
"live_secret": "sk_live_",
"test_secret": "sk_test_",
"live_public": "pk_live_",
"test_public": "pk_test_",
}
def __init__(self, db_connection, redis_connection):
self.db = db_connection
self.redis = redis_connection
def generate_key(self, key_type="live_secret", owner_id=None, scopes=None,
rate_limit=None, ip_allowlist=None, expires_days=365):
"""Generate a new API key with metadata."""
prefix = self.KEY_PREFIXES.get(key_type, "sk_live_")
# Generate 32 bytes (256 bits) of randomness
random_bytes = secrets.token_bytes(32)
key_body = secrets.token_urlsafe(32) # Base64url-encoded
# Full API key that the client receives (shown only once)
full_key = f"{prefix}{key_body}"
# Hash the key for storage (never store the raw key)
key_hash = hashlib.sha256(full_key.encode()).hexdigest()
# Create a short key ID for reference (first 8 chars)
key_id = f"{prefix}{key_body[:8]}..."
# Store the hashed key with metadata
key_metadata = {
"key_hash": key_hash,
"key_id": key_id,
"key_type": key_type,
"owner_id": owner_id,
"scopes": scopes or ["read"],
"rate_limit": rate_limit or {"requests": 1000, "window": 3600},
"ip_allowlist": ip_allowlist or [],
"created_at": datetime.utcnow().isoformat(),
"expires_at": (datetime.utcnow() + timedelta(days=expires_days)).isoformat(),
"last_used": None,
"is_active": True,
"usage_count": 0,
}
# Store in database
self.db.execute(
"INSERT INTO api_keys (key_hash, key_id, metadata) VALUES (?, ?, ?)",
(key_hash, key_id, json.dumps(key_metadata))
)
# Cache in Redis for fast validation
self.redis.setex(
f"apikey:{key_hash}",
86400, # 24-hour cache TTL
json.dumps(key_metadata)
)
return {
"api_key": full_key, # Show to user ONCE
"key_id": key_id, # For reference/management
"scopes": key_metadata["scopes"],
"expires_at": key_metadata["expires_at"],
}
def validate_key(self, api_key):
"""Validate an API key and return its metadata."""
key_hash = hashlib.sha256(api_key.encode()).hexdigest()
# Check Redis cache first
cached = self.redis.get(f"apikey:{key_hash}")
if cached:
metadata = json.loads(cached)
else:
# Fall back to database
row = self.db.execute(
"SELECT metadata FROM api_keys WHERE key_hash = ?",
(key_hash,)
).fetchone()
if not row:
return None, "invalid_key"
metadata = json.loads(row[0])
…
常见问题
什么是“熵”(entropy)?
它衡量密钥的随机性或不可预测性。熵越高,别人就越难猜中这个密钥。
为什么不能以明文存储密钥?
明文存储风险很大。如果有人获得了你数据库的访问权限,就能看到所有密钥并加以滥用。
什么是“密钥轮换”(key rotation)?
它指用新的访问密钥替换旧密钥的过程。这样做是为了保持安全,尤其是在旧密钥可能已经泄露或即将过期的时候。
详情
作者的原始描述
Implements secure API key generation with sufficient entropy, server-side hashing (SHA-256/bcrypt) instead of plaintext storage, per-key scoping to endpoints/IPs/rate limits, zero-downtime rotation, and automated leak monitoring across GitHub repos, logs, and client-side code. Use when designing API key formats, building key rotation or revocation workflows, or protecting server-to-server API cred
热度
- GitHub 星标
- 35k
- 排名
- #7987
- 许可证
- Apache-2.0
- 更新时间
- 2026/8/31
评论
- …
同一仓库的更多技能
abusing-dpapi-for-credential-access
35k为你的 AI 智能体提供针对特定任务的现成指令,让它完成得更好、更快。
abusing-shadow-credentials-for-privesc
35k教你的 AI 智能体写出清晰、结构良好的文本。
achieving-cmmc-level-2-compliance
35k帮助你的智能体搭建符合 CMMC Level 2 合规要求的环境。它会落实安全要求,并管理必要的文档。
acquiring-disk-image-with-dd-and-dcfldd
35k帮助你的智能体创建硬盘的精确副本。这能确保调查过程中信息不丢失、不被篡改。