मुख्य सामग्री पर जाएँ
Skillpedia
सिक्योरिटी35k · #7987

implementing-api-key-security-controls

यह क्या करती है

यह टूल आपके सिस्टम के लिए सुरक्षित access keys बनाने और मैनेज करने में मदद करता है। यह सुनिश्चित करता है कि keys का आसानी से अनुमान न लगाया जा सके, वे असुरक्षित जगह स्टोर न हों, और आसानी से बंद या बदली जा सकें।

कब इस्तेमाल करें

  • ✓जब कोई नया सिस्टम बन रहा हो जिसे server-to-server सुरक्षित एक्सेस चाहिए।
  • ✓पुरानी access keys को बिना सेवा रुकावट के नई keys से बदलना हो।
  • ✓अगर शक हो कि कोई access key लीक हो गई है।

Skill का लिंक

https://github.com/mukul975/Anthropic-Cybersecurity-Skills/blob/main/skills/implementing-api-key-security-controls/SKILL.md

इसे कॉपी करके अपने AI (Claude, ChatGPT या Cursor) में पेस्ट करें और निर्देशों का पालन करने को कहें।

कैसे इस्तेमाल करें

सबसे आसान तरीका: मैसेज कॉपी करके अपने AI में पेस्ट करें। वह skill पढ़कर निर्देशों का पालन करेगा।

पेस्ट करने के लिए तैयार मैसेज

इस skill से मेरी मदद करो: https://github.com/mukul975/Anthropic-Cybersecurity-Skills/blob/main/skills/implementing-api-key-security-controls/SKILL.md इस लिंक की SKILL.md फ़ाइल पढ़ो और मेरे काम में उसके निर्देशों का पालन करो।
क्या आप चाहते हैं कि आपका AI ऐसी skills खुद ढूँढे?मुफ़्त Skillpedia MCP इंस्टॉल करें: बस एक लाइन, और हर काम से पहले यह 15,000+ skills में खोजता है।1 मिनट में इंस्टॉल करें →

AI से क्या माँगें: उदाहरण

“मेरे backend application के लिए सुरक्षित API key बनाओ, जिसमें सिर्फ़ read-only अनुमति हो और 90 दिन में expire हो।”

हर हफ़्ते 5 नई skills, 1 मिनट में पढ़ें।

यह कैसे काम करती है

यह टूल बहुत ज़्यादा randomness वाली keys बनाता है और उन्हें encrypted रूप में स्टोर करता है। यह उपयोग की सीमाएँ तय करने देता है और यह भी देखता है कि keys किसी असुरक्षित जगह पर तो नहीं दिख रहीं।

तकनीकी सामग्री (मूल 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 की randomness या अप्रत्याशितता का माप है। entropy जितनी ज़्यादा होगी, किसी के लिए key का अनुमान लगाना उतना ही कठिन होगा।

keys plaintext में क्यों स्टोर नहीं करनी चाहिए?

Plaintext में keys स्टोर करना बहुत जोखिम भरा है। अगर किसी को आपके database तक पहुँच मिल जाए, तो वह सारी keys देख सकता है और उनका गलत इस्तेमाल कर सकता है।

'key rotation' क्या है?

पुरानी access key को नई key से बदलने की प्रक्रिया है। यह सुरक्षा बनाए रखने के लिए की जाती है, खासकर जब पुरानी key से समझौता हो गया हो या उसकी expiry पास हो।

जानकारी

लेखक का मूल विवरण

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

repo: mukul975/Anthropic-Cybersecurity-Skills

लोकप्रियता

GitHub स्टार
35k
रैंकिंग में स्थान
#7987
लाइसेंस
Apache-2.0
अपडेट की गई
31/8/2026

क्या यह skill काम की है?

0

लॉग इन करें वोट करने के लिए।

कमेंट

  • …

इस repository की और skills

मिलती-जुलती skills