#!/usr/bin/env python3 """ Generates data.enc from data.json using AES-256-GCM + PBKDF2. Re-run whenever you change data.json or rotate the password. Usage on the server: nix-shell -p python3Packages.cryptography --run "python3 encrypt.py" """ import json, os, base64, getpass from pathlib import Path from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.ciphers.aead import AESGCM here = Path(__file__).parent plaintext = here.joinpath('data.json').read_bytes() password = getpass.getpass('Password: ').encode() salt = os.urandom(16) kdf = PBKDF2HMAC(algorithm=hashes.SHA256(), length=32, salt=salt, iterations=100000) key = kdf.derive(password) iv = os.urandom(12) ciphertext = AESGCM(key).encrypt(iv, plaintext, None) here.joinpath('data.enc').write_text(json.dumps({ 'salt': base64.b64encode(salt).decode(), 'iv': base64.b64encode(iv).decode(), 'ct': base64.b64encode(ciphertext).decode(), })) print('data.enc written.')