Skip to content

Key Rotation

What is Key Rotation

Key rotation is a security best practice of regularly updating API keys to meet security compliance requirements and reduce the risk of key leakage.

Rotation Steps

Zero-downtime key rotation follows three steps:

1. Create a New Key

First, create a new API key:

bash
curl -X POST https://ai-tokenhub.com/v1/keys \
  -H "Authorization: Bearer <YOUR_MANAGEMENT_API_KEY>" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "my-api-key-new"
  }'

2. Update Your Application

Update the API key in your application to the newly created key:

python
from openai import OpenAI

client = OpenAI(
  base_url="https://ai-tokenhub.com/v1",
  api_key="<NEW_API_KEY>",
)

3. Verify the New Key

Before deleting the old key, verify that the new key works correctly in the production environment to prevent accidental service interruption.

Automated Rotation

Python Example

python
import requests
from openai import OpenAI

def rotate_api_key(management_key, old_key_hash):
    # 1. Create new key
    response = requests.post(
        "https://ai-tokenhub.com/v1/keys",
        headers={"Authorization": f"Bearer {management_key}"},
        json={"name": "rotated-key"}
    )
    new_key = response.json()["key"]

    # 2. Verify the new key
    client = OpenAI(
        base_url="https://ai-tokenhub.com/v1",
        api_key=new_key
    )
    # Test call...

    # 3. Delete old key
    requests.delete(
        f"https://ai-tokenhub.com/v1/keys/{old_key_hash}",
        headers={"Authorization": f"Bearer {management_key}"}
    )

    return new_key

Security Recommendations

  • It is recommended to rotate keys every 90 days
  • Store keys in environment variables, do not hardcode
  • Monitor key usage to detect anomalies in a timely manner