RUNLOCALAIv38
->Will it run?Best GPUCompareTroubleshootStartLearnPulseModelsHardwareToolsBench
Run check
RUNLOCALAI

Independently operated catalog for local-AI hardware and software. Hand-written verdicts. Source-cited claims. Reproducible commands when we have them.

OP·Fredoline Eruo
DIR
  • Models
  • Hardware
  • Tools
  • Benchmarks
TOOLS
  • Will it run?
  • Compare hardware
  • Cost vs cloud
  • Choose my GPU
  • Prompting kits
  • Quick answers
REF
  • All buyer guides
  • Learn local AI
  • Methodology
  • Glossary
  • Errors KB
  • Trust
EDITOR
  • About
  • Author
  • How we make money
  • Editorial policy
  • Contact
LEGAL
  • Privacy
  • Terms
  • Sitemap
MAIL · MONTHLY DIGEST
Get monthly local AI changes
Monthly recap. No spam.
DISCLOSURE

Some links on this site are affiliate links (Amazon Associates and other first-class retailers). When you buy through them, we earn a small commission at no extra cost to you. Affiliate links do not influence our verdicts — there are cards we rate highly that we don't have affiliate relationships with, and cards that sell well that we refuse to recommend. Read more →

© 2026 runlocalai.coIndependently operated
RUNLOCALAI · v38
  1. >
  2. Home
  3. /Learn
  4. /Courses
  5. /Security and Privacy for Local AI
  6. /Ch. 5
Security and Privacy for Local AI

05. API Key Management

Chapter 5 of 16 · 15 min
KEY INSIGHT

API keys are credentials. Treat them like passwords: generate randomly, rotate frequently, store securely, and revoke immediately when compromised. A key that lives for years is a key that will eventually be stolen.

API keys protect your services but become attack surfaces if mishandled. Proper key management follows the principle of least privilege: keys should have minimal scope, expire quickly, and never appear in code or logs.

Generating secure keys:

# Generate a 256-bit random key formatted for readability
openssl rand -hex 32

# Generate multiple keys with prefixes for identification
for env in dev staging prod; do
    echo "${env}:$(openssl rand -hex 32)"
done > ~/.ai/secrets/keys
chmod 600 ~/.ai/secrets/keys

Key rotation strategies:

Rotate keys on a schedule (monthly for sensitive services) and immediately upon suspected compromise. Implement key versioning so old keys remain valid during transition:

# Key rotation implementation
import time

class KeyStore:
    def __init__(self):
        self.keys = {}  # {key_id: {secret_hash, created, expires, scopes}}
    
    def add_key(self, key_id: str, secret: str, ttl_days: int = 30, 
                scopes: list[str] = None):
        self.keys[key_id] = {
            "secret_hash": hashlib.sha256(secret.encode()).hexdigest(),
            "created": time.time(),
            "expires": time.time() + (ttl_days * 86400),
            "scopes": scopes or ["read"]
        }
    
    def verify(self, key_id: str, secret: str, required_scope: str = None) -> bool:
        key = self.keys.get(key_id)
        if not key:
            return False
        if time.time() > key["expires"]:
            return False
        if hashlib.sha256(secret.encode()).hexdigest() != key["secret_hash"]:
            return False
        if required_scope and required_scope not in key["scopes"]:
            return False
        return True

Storage anti-patterns to avoid:

  • Never store keys in source code (even private repos)
  • Never log keys (sanitize logs to redact them)
  • Never embed keys in Docker images or container configs
  • Never share keys via Slack, email, or Slack

Secure storage options:

  • Environment variables loaded from secrets manager at startup
  • HashiCorp Vault, AWS Secrets Manager, or similar dedicated secrets storage
  • Local file with restrictive permissions (600) on POSIX systems
  • Encrypted file using gpg or age
EXERCISE

Audit your current API keys. For each key, write down: creation date, last rotation, storage location, and rotation plan. Create a script that alerts you 7 days before keys expire.

← Chapter 4
API Authentication
Chapter 6 →
Data Isolation