Store Encryption Keys Safely in AWS Secrets Manager
Storing raw keys in AWS Secrets Manager can go wrong when escaping or encoding changes the contents. This bit me with a JSON payload holding a private key: line breaks and backslashes were being altered.
Base64 avoids that class of problem. Store the base64-encoded key; decode it at runtime; treat any decode failure as a hard stop.
Example decode in a Django settings module:
import base64
import os
SECRET_KEY_B64 = os.environ["PRIVATE_KEY_B64"]
try:
PRIVATE_KEY = base64.b64decode(SECRET_KEY_B64).decode("utf-8")
except Exception as exc:
raise RuntimeError("Private key could not be decoded") from exc
Key points:
- Store the base64 version in Secrets Manager (or your parameter store of choice).
- Decode once, at startup, so broken secrets fail fast and loudly.
- Do not catch-and-ignore decode errors—let the process crash so you never run with a mangled key.
If you want more background on why base64 helps here, read Adrin Mukherjee’s article.