57 lines
1.5 KiB
Python
57 lines
1.5 KiB
Python
"""Create the local project-specific VIN HMAC key without printing it."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import hashlib
|
|
import os
|
|
import secrets
|
|
import stat
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
|
|
PROJECT_ROOT = Path(__file__).resolve().parents[1]
|
|
DEFAULT_PATH = PROJECT_ROOT / ".secrets/vin_hmac.key"
|
|
|
|
|
|
def parse_args() -> argparse.Namespace:
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--path", type=Path, default=DEFAULT_PATH)
|
|
return parser.parse_args()
|
|
|
|
|
|
def key_fingerprint(key: bytes) -> str:
|
|
return hashlib.sha256(
|
|
b"utah-vehicle-health/key-fingerprint/v1\0" + key
|
|
).hexdigest()[:16]
|
|
|
|
|
|
def main() -> int:
|
|
path = parse_args().path.resolve()
|
|
os.umask(0o077)
|
|
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
|
|
if path.exists():
|
|
mode = stat.S_IMODE(path.stat().st_mode)
|
|
if mode & 0o077:
|
|
print(f"Existing key has unsafe permissions: {path}", file=sys.stderr)
|
|
return 1
|
|
print(f"Key already exists; leaving it unchanged: {path}")
|
|
return 0
|
|
|
|
key = secrets.token_bytes(32)
|
|
descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
|
with os.fdopen(descriptor, "w", encoding="ascii") as handle:
|
|
handle.write(key.hex() + "\n")
|
|
handle.flush()
|
|
os.fsync(handle.fileno())
|
|
|
|
print(f"Created private VIN HMAC key: {path}")
|
|
print(f"Non-secret key fingerprint: {key_fingerprint(key)}")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|