# Practical 6 – Cloud Security: Encrypt and Upload
# Install: pip install boto3 cryptography
# First run init_db, keys, and s3_setup. Configure AWS credentials, place
# sample.txt in this folder, and use your chosen bucket name below.
# Then run from this folder: python p6_cloudSec_upload.py
import sqlite3
import secrets
from cryptography.hazmat.primitives.ciphers.aead import AESGCM

# Authenticate administrator
token = input("Enter admin token: ")

conn = sqlite3.connect("cloud.db")
cur = conn.cursor()

cur.execute("SELECT role FROM users WHERE token = ?", (token,))
user = cur.fetchone()
conn.close()

if not user or user[0] != "admin":
    print("Access denied. Admin access required.")
    exit()

# Read AES key
with open("secret.key", "rb") as f:
    key = f.read()

# Read original file
with open("sample.txt", "rb") as f:
    data = f.read()

# Encrypt file
nonce = secrets.token_bytes(12)
encrypted = nonce + AESGCM(key).encrypt(nonce, data, None)

# Upload to simulated cloud storage
with open("cloud_storage/sample.txt", "wb") as f:
    f.write(encrypted)

print("File encrypted and uploaded successfully.")

# What this code does: verifies the admin token, encrypts sample.txt with
# AES-GCM, and writes the encrypted file to the simulated cloud folder.