#!/usr/bin/env python3
"""
CipherVault Token Encryption System
====================================
This script shows how tokens are encrypted for the CipherVault platform.
AES-128-CBC with PKCS#7 padding is used.

Token format: IV (16 bytes) || Ciphertext (N blocks of 16 bytes)
Encoding: hexadecimal

The validation endpoint at /api/validate will tell you if a token has
valid padding or not. Use this information wisely.
"""

from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
import os
import json
import binascii

def encrypt_token(data: dict, key: bytes) -> str:
    """Encrypt a JSON token with AES-128-CBC"""
    plaintext = json.dumps(data).encode()
    iv = os.urandom(16)
    cipher = AES.new(key, AES.MODE_CBC, iv)
    padded = pad(plaintext, AES.block_size)
    ciphertext = cipher.encrypt(padded)
    return binascii.hexlify(iv + ciphertext).decode()

if __name__ == '__main__':
    # Example usage (the actual key is secret and random per instance)
    demo_key = os.urandom(16)

    user_token = encrypt_token({"role": "user", "name": "guest"}, demo_key)
    print(f"User token: {user_token}")

    admin_token = encrypt_token({"role": "admin", "flag": "FLAG{example}"}, demo_key)
    print(f"Admin token: {admin_token}")

    print(f"\nToken structure:")
    print(f"  IV:         {user_token[:32]} (16 bytes)")
    print(f"  Ciphertext: {user_token[32:]} ({(len(user_token)-32)//2} bytes)")
    print(f"  Block size: 16 bytes")
    print(f"  Mode:       CBC")
    print(f"  Padding:    PKCS#7")
