broadfield-dev commited on
Commit
7a2942e
Β·
verified Β·
1 Parent(s): 75337d1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +146 -0
app.py CHANGED
@@ -1,3 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # ==============================================================================
2
  # GRADIO DASHBOARD INTERFACE
3
  # ==============================================================================
 
1
+ import gradio as gr
2
+ from PIL import Image, ImageDraw, ImageFont
3
+ import base64
4
+ import io
5
+ import json
6
+ import logging
7
+ import os
8
+ import requests
9
+ import struct
10
+ import numpy as np
11
+ from cryptography.hazmat.primitives import serialization
12
+ from cryptography.hazmat.primitives.asymmetric import rsa, padding
13
+ from cryptography.hazmat.primitives.ciphers.aead import AESGCM
14
+ from cryptography.hazmat.primitives import hashes
15
+
16
+ # --- Configure Logging ---
17
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
18
+ logger = logging.getLogger(__name__)
19
+
20
+ # ==============================================================================
21
+ # CONFIGURATION
22
+ # ==============================================================================
23
+ CREATOR_ENDPOINTS_JSON_URL = "https://huggingface.co/spaces/broadfield-dev/KeyLock-Auth-Creator/raw/main/endpoints.json"
24
+ BASE_HF_URL = "https://huggingface.co/spaces/"
25
+ # Define these here for cleaner linking in the UI
26
+ CREATOR_SPACE_ID = "broadfield-dev/KeyLock-Auth-Creator"
27
+ SERVER_SPACE_ID = "broadfield-dev/KeyLock-Auth-Server"
28
+ CREATOR_URL = f"{BASE_HF_URL}{CREATOR_SPACE_ID}"
29
+ SERVER_URL = f"{BASE_HF_URL}{SERVER_SPACE_ID}"
30
+
31
+ # ==============================================================================
32
+ # LOCAL LOGIC (Key and Image Generation)
33
+ # ==============================================================================
34
+ def generate_rsa_keys():
35
+ private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
36
+ private_pem = private_key.private_bytes(encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption()).decode('utf-8')
37
+ public_pem = private_key.public_key().public_bytes(encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo).decode('utf-8')
38
+ return private_pem, public_pem
39
+
40
+ def create_encrypted_image(secret_data_str: str, public_key_pem: str) -> Image.Image:
41
+ if not secret_data_str.strip(): raise ValueError("Secret data cannot be empty.")
42
+ if not public_key_pem.strip(): raise ValueError("Public Key cannot be empty.")
43
+ data_dict = {}
44
+ for line in secret_data_str.splitlines():
45
+ line = line.strip()
46
+ if not line or line.startswith('#'): continue
47
+ parts = line.split(':', 1) if ':' in line else line.split('=', 1)
48
+ if len(parts) == 2: data_dict[parts[0].strip()] = parts[1].strip().strip("'\"")
49
+ if not data_dict: raise ValueError("No valid key-value pairs found.")
50
+ json_bytes = json.dumps(data_dict).encode('utf-8')
51
+ public_key = serialization.load_pem_public_key(public_key_pem.encode('utf-8'))
52
+ aes_key, nonce = os.urandom(32), os.urandom(12)
53
+ ciphertext = AESGCM(aes_key).encrypt(nonce, json_bytes, None)
54
+ rsa_encrypted_key = public_key.encrypt(aes_key, padding.OAEP(mgf=padding.MGF1(hashes.SHA256()), algorithm=hashes.SHA256(), label=None))
55
+ encrypted_payload = struct.pack('>I', len(rsa_encrypted_key)) + rsa_encrypted_key + nonce + ciphertext
56
+ img = Image.new('RGB', (800, 600), color=(45, 52, 54))
57
+ draw = ImageDraw.Draw(img)
58
+ try: font = ImageFont.truetype("DejaVuSans.ttf", 40)
59
+ except IOError: font = ImageFont.load_default(size=30)
60
+ draw.text((400, 300), "KeyLock Secure Data", fill=(223, 230, 233), font=font, anchor="ms")
61
+ pixel_data = np.array(img.convert("RGB")).ravel()
62
+ binary_payload = ''.join(format(b, '08b') for b in struct.pack('>I', len(encrypted_payload)) + encrypted_payload)
63
+ if len(binary_payload) > pixel_data.size: raise ValueError("Data too large for image.")
64
+ pixel_data[:len(binary_payload)] = (pixel_data[:len(binary_payload)] & 0xFE) | np.array(list(binary_payload), dtype=np.uint8)
65
+ stego_pixels = pixel_data.reshape((600, 800, 3))
66
+ return Image.fromarray(stego_pixels, 'RGB')
67
+
68
+ # ==============================================================================
69
+ # UI HELPER & REMOTE API CALL LOGIC
70
+ # ==============================================================================
71
+
72
+ def get_server_list():
73
+ """Fetches and validates the list of servers from the public JSON file."""
74
+ status = f"Fetching server list from remote config..."
75
+ yield gr.Dropdown(choices=[], value=None, label="⏳ Fetching..."), status, []
76
+ try:
77
+ response = requests.get(ENDPOINTS_JSON_URL, timeout=10)
78
+ response.raise_for_status()
79
+
80
+ all_entries = response.json()
81
+ valid_endpoints = []
82
+ required_keys = ["name", "api_endpoint", "public_key"]
83
+
84
+ # --- ROBUST VALIDATION LOGIC ---
85
+ for entry in all_entries:
86
+ if all(key in entry for key in required_keys):
87
+ valid_endpoints.append(entry)
88
+ else:
89
+ logger.warning(f"Skipping invalid entry in configuration file: {entry}")
90
+
91
+ if not valid_endpoints:
92
+ raise ValueError("No valid server configurations found in the remote file.")
93
+
94
+ endpoint_names = [e['name'] for e in valid_endpoints]
95
+ status = f"βœ… Success! Found {len(endpoint_names)} valid servers."
96
+ yield gr.Dropdown(choices=endpoint_names, value=endpoint_names[0] if endpoint_names else None, label="Target Server"), status, valid_endpoints
97
+ except Exception as e:
98
+ status = f"❌ Error fetching or parsing configuration: {e}"
99
+ yield gr.Dropdown(choices=[], value=None, label="Error fetching servers"), status, []
100
+
101
+ def create_keylock_wrapper(service_name: str, secret_data: str, available_endpoints: list):
102
+ """UI wrapper for creating an image for a selected service."""
103
+ if not service_name: raise gr.Error("Please select a target server.")
104
+ public_key = next((e['public_key'] for e in available_endpoints if e['name'] == service_name), None)
105
+ if not public_key: raise gr.Error(f"Could not find public key for '{service_name}'.")
106
+ try:
107
+ created_image = create_encrypted_image(secret_data, public_key)
108
+ return created_image, f"βœ… Success! Image created for '{service_name}'."
109
+ except Exception as e:
110
+ return None, f"❌ Error: {e}"
111
+
112
+ def send_keylock_wrapper(service_name: str, image: Image.Image, available_endpoints: list):
113
+ """UI wrapper for sending an image to a selected server API."""
114
+ if not service_name: raise gr.Error("Please select a target server.")
115
+ if image is None: raise gr.Error("Please upload an image to send.")
116
+
117
+ api_endpoint = next((e.get('api_endpoint') for e in available_endpoints if e['name'] == service_name), None)
118
+ if not api_endpoint: raise gr.Error(f"Configuration Error: Could not find 'api_endpoint' for '{service_name}'.")
119
+
120
+ status = f"Connecting to endpoint: {api_endpoint}"
121
+ yield None, status
122
+
123
+ try:
124
+ with io.BytesIO() as buffer:
125
+ image.save(buffer, format="PNG")
126
+ b64_string = base64.b64encode(buffer.getvalue()).decode("utf-8")
127
+
128
+ payload = {"data": [b64_string]}
129
+ headers = {"Content-Type": "application/json"}
130
+ response = requests.post(api_endpoint, headers=headers, json=payload, timeout=45)
131
+ response_json = response.json()
132
+
133
+ if response.status_code == 200:
134
+ if "data" in response_json:
135
+ yield response_json["data"][0], "βœ… Success! Data decrypted by remote server."
136
+ else:
137
+ raise gr.Error(f"API returned an unexpected success format: {response_json}")
138
+ else:
139
+ raise gr.Error(f"API Error (Status {response.status_code}): {response_json.get('error', 'Unknown error')}")
140
+
141
+ except Exception as e:
142
+ yield None, f"❌ Error calling server API: {e}"
143
+
144
+ # ==============================================================================
145
+ # GRADIO DASHBOARD INTERFACE
146
+ # ==============================================================================
147
  # ==============================================================================
148
  # GRADIO DASHBOARD INTERFACE
149
  # ==============================================================================