Update app.py
Browse files
app.py
CHANGED
|
@@ -12,12 +12,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 |
-
# --- Basic Configuration ---
|
| 17 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
| 18 |
logger = logging.getLogger(__name__)
|
| 19 |
|
| 20 |
-
# --- Constants ---
|
| 21 |
CREATOR_ENDPOINTS_JSON_URL = "https://huggingface.co/spaces/broadfield-dev/KeyLock-Auth-Creator/raw/main/endpoints.json"
|
| 22 |
BASE_HF_URL = "https://huggingface.co/spaces/"
|
| 23 |
CREATOR_SPACE_ID = "broadfield-dev/KeyLock-Auth-Creator"
|
|
@@ -29,7 +28,6 @@ SERVER_APP_PY_URL = f"{SERVER_URL}/raw/main/app.py"
|
|
| 29 |
|
| 30 |
|
| 31 |
def generate_rsa_keys():
|
| 32 |
-
"""Generates a new 2048-bit RSA private and public key pair."""
|
| 33 |
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
| 34 |
private_pem = private_key.private_bytes(
|
| 35 |
encoding=serialization.Encoding.PEM,
|
|
@@ -43,7 +41,6 @@ def generate_rsa_keys():
|
|
| 43 |
return private_pem, public_pem
|
| 44 |
|
| 45 |
def create_encrypted_image(secret_data_str: str, public_key_pem: str) -> Image.Image:
|
| 46 |
-
"""Encrypts data and embeds it into a new image using steganography."""
|
| 47 |
if not secret_data_str.strip():
|
| 48 |
raise ValueError("Secret data cannot be empty.")
|
| 49 |
if not public_key_pem.strip():
|
|
@@ -64,20 +61,16 @@ def create_encrypted_image(secret_data_str: str, public_key_pem: str) -> Image.I
|
|
| 64 |
json_bytes = json.dumps(data_dict).encode('utf-8')
|
| 65 |
public_key = serialization.load_pem_public_key(public_key_pem.encode('utf-8'))
|
| 66 |
|
| 67 |
-
# AES-GCM encryption
|
| 68 |
aes_key, nonce = os.urandom(32), os.urandom(12)
|
| 69 |
ciphertext = AESGCM(aes_key).encrypt(nonce, json_bytes, None)
|
| 70 |
|
| 71 |
-
# RSA-OAEP encryption for the AES key
|
| 72 |
rsa_encrypted_key = public_key.encrypt(
|
| 73 |
aes_key,
|
| 74 |
padding.OAEP(mgf=padding.MGF1(hashes.SHA256()), algorithm=hashes.SHA256(), label=None)
|
| 75 |
)
|
| 76 |
|
| 77 |
-
# Pack the payload: [len(rsa_key)][rsa_key][nonce][ciphertext]
|
| 78 |
encrypted_payload = struct.pack('>I', len(rsa_encrypted_key)) + rsa_encrypted_key + nonce + ciphertext
|
| 79 |
|
| 80 |
-
# Create a base image
|
| 81 |
img = Image.new('RGB', (800, 600), color=(45, 52, 54))
|
| 82 |
draw = ImageDraw.Draw(img)
|
| 83 |
try:
|
|
@@ -86,7 +79,6 @@ def create_encrypted_image(secret_data_str: str, public_key_pem: str) -> Image.I
|
|
| 86 |
font = ImageFont.load_default(size=30)
|
| 87 |
draw.text((400, 300), "KeyLock Secure Data", fill=(223, 230, 233), font=font, anchor="ms")
|
| 88 |
|
| 89 |
-
# LSB Steganography
|
| 90 |
pixel_data = np.array(img.convert("RGB")).ravel()
|
| 91 |
binary_payload = ''.join(format(b, '08b') for b in struct.pack('>I', len(encrypted_payload)) + encrypted_payload)
|
| 92 |
|
|
@@ -99,7 +91,6 @@ def create_encrypted_image(secret_data_str: str, public_key_pem: str) -> Image.I
|
|
| 99 |
return Image.fromarray(stego_pixels, 'RGB')
|
| 100 |
|
| 101 |
def get_server_list():
|
| 102 |
-
"""Fetches and validates the server list from the remote JSON configuration."""
|
| 103 |
status = "Fetching server list from remote config..."
|
| 104 |
yield gr.Dropdown(choices=[], value=None, label="β³ Fetching..."), status, []
|
| 105 |
try:
|
|
@@ -113,7 +104,6 @@ def get_server_list():
|
|
| 113 |
logger.warning(f"Skipping invalid entry (missing name or public_key): {entry}")
|
| 114 |
continue
|
| 115 |
|
| 116 |
-
# **FIX: Auto-generate api_endpoint from link if it's missing**
|
| 117 |
if "api_endpoint" not in entry:
|
| 118 |
if "link" in entry:
|
| 119 |
base_url = entry["link"].strip("/")
|
|
@@ -137,7 +127,6 @@ def get_server_list():
|
|
| 137 |
yield gr.Dropdown(choices=[], value=None, label="Error fetching servers"), status, []
|
| 138 |
|
| 139 |
def create_keylock_wrapper(service_name: str, secret_data: str, available_endpoints: list):
|
| 140 |
-
"""Wrapper function to handle UI for creating the encrypted image."""
|
| 141 |
if not service_name:
|
| 142 |
raise gr.Error("Please select a target server.")
|
| 143 |
public_key = next((e['public_key'] for e in available_endpoints if e['name'] == service_name), None)
|
|
@@ -151,17 +140,20 @@ def create_keylock_wrapper(service_name: str, secret_data: str, available_endpoi
|
|
| 151 |
return None, f"β Error: {e}"
|
| 152 |
|
| 153 |
def send_keylock_wrapper(service_name: str, image: Image.Image, available_endpoints: list):
|
| 154 |
-
"""Wrapper function to handle UI for sending the image to the remote server."""
|
| 155 |
if not service_name:
|
| 156 |
raise gr.Error("Please select a target server.")
|
| 157 |
if image is None:
|
| 158 |
raise gr.Error("Please create or upload an image to send.")
|
| 159 |
|
| 160 |
-
|
| 161 |
-
if not
|
| 162 |
-
raise gr.Error(f"Configuration Error: Could not find
|
| 163 |
-
|
| 164 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 165 |
yield None, status
|
| 166 |
|
| 167 |
try:
|
|
@@ -169,40 +161,29 @@ def send_keylock_wrapper(service_name: str, image: Image.Image, available_endpoi
|
|
| 169 |
image.save(buffer, format="PNG")
|
| 170 |
b64_string = base64.b64encode(buffer.getvalue()).decode("utf-8")
|
| 171 |
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
response.raise_for_status() # **IMPROVEMENT: Raise exception for HTTP errors**
|
| 178 |
|
| 179 |
-
|
| 180 |
-
if
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
except json.JSONDecodeError:
|
| 187 |
-
pass # Keep as string if not valid JSON
|
| 188 |
-
yield decrypted_data, "β
Success! Data decrypted by remote server."
|
| 189 |
-
elif "error" in response_json:
|
| 190 |
-
raise gr.Error(f"API Error: {response_json['error']}")
|
| 191 |
-
else:
|
| 192 |
-
raise gr.Error(f"API returned an unexpected response format: {response_json}")
|
| 193 |
|
| 194 |
except Exception as e:
|
| 195 |
-
logger.error(f"Error calling server
|
| 196 |
yield None, f"β Error calling server API: {e}"
|
| 197 |
|
| 198 |
def refresh_and_update_all():
|
| 199 |
-
"""Calls get_server_list and updates all relevant UI components."""
|
| 200 |
-
# The generator yields updates, we need to iterate to get the final one
|
| 201 |
for dropdown_update, status_update, state_update in get_server_list():
|
| 202 |
pass
|
| 203 |
return dropdown_update, dropdown_update, status_update, state_update
|
| 204 |
|
| 205 |
-
# --- Gradio UI Definition ---
|
| 206 |
theme = gr.themes.Base(
|
| 207 |
primary_hue=gr.themes.colors.blue, secondary_hue=gr.themes.colors.sky, neutral_hue=gr.themes.colors.slate,
|
| 208 |
font=(gr.themes.GoogleFont("Inter"), "system-ui", "sans-serif"),
|
|
@@ -235,7 +216,6 @@ with gr.Blocks(theme=theme, title="KeyLock Operations Dashboard") as demo:
|
|
| 235 |
|
| 236 |
with gr.TabItem("β‘ Send KeyLock", id=1):
|
| 237 |
gr.Markdown("## Step 2: Decrypt via Live API Call")
|
| 238 |
-
gr.Markdown("## This a Demo, don't send personal encrypted secret data to the demo server.")
|
| 239 |
gr.Markdown("This tool acts as the **Client**. It sends the encrypted image you created in Step 1 to the live, remote **Decoder Server** you select from the same configuration list. The server uses its securely stored private key to decrypt the data and sends the result back.")
|
| 240 |
with gr.Row(variant="panel"):
|
| 241 |
with gr.Column(scale=1):
|
|
@@ -267,7 +247,6 @@ with gr.Blocks(theme=theme, title="KeyLock Operations Dashboard") as demo:
|
|
| 267 |
output_private_key = gr.Textbox(lines=10, label="Generated Private Key", interactive=False, show_copy_button=True)
|
| 268 |
gen_keys_button = gr.Button("βοΈ Generate New 2048-bit Key Pair", variant="secondary")
|
| 269 |
|
| 270 |
-
# --- Event Handlers ---
|
| 271 |
gen_keys_button.click(fn=generate_rsa_keys, inputs=None, outputs=[output_private_key, output_public_key])
|
| 272 |
refresh_button.click(fn=refresh_and_update_all, outputs=[creator_service_dropdown, send_service_dropdown, creator_status, endpoints_state])
|
| 273 |
demo.load(fn=refresh_and_update_all, outputs=[creator_service_dropdown, send_service_dropdown, creator_status, endpoints_state])
|
|
|
|
| 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 |
+
from gradio_client import Client
|
| 16 |
|
|
|
|
| 17 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
| 18 |
logger = logging.getLogger(__name__)
|
| 19 |
|
|
|
|
| 20 |
CREATOR_ENDPOINTS_JSON_URL = "https://huggingface.co/spaces/broadfield-dev/KeyLock-Auth-Creator/raw/main/endpoints.json"
|
| 21 |
BASE_HF_URL = "https://huggingface.co/spaces/"
|
| 22 |
CREATOR_SPACE_ID = "broadfield-dev/KeyLock-Auth-Creator"
|
|
|
|
| 28 |
|
| 29 |
|
| 30 |
def generate_rsa_keys():
|
|
|
|
| 31 |
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
| 32 |
private_pem = private_key.private_bytes(
|
| 33 |
encoding=serialization.Encoding.PEM,
|
|
|
|
| 41 |
return private_pem, public_pem
|
| 42 |
|
| 43 |
def create_encrypted_image(secret_data_str: str, public_key_pem: str) -> Image.Image:
|
|
|
|
| 44 |
if not secret_data_str.strip():
|
| 45 |
raise ValueError("Secret data cannot be empty.")
|
| 46 |
if not public_key_pem.strip():
|
|
|
|
| 61 |
json_bytes = json.dumps(data_dict).encode('utf-8')
|
| 62 |
public_key = serialization.load_pem_public_key(public_key_pem.encode('utf-8'))
|
| 63 |
|
|
|
|
| 64 |
aes_key, nonce = os.urandom(32), os.urandom(12)
|
| 65 |
ciphertext = AESGCM(aes_key).encrypt(nonce, json_bytes, None)
|
| 66 |
|
|
|
|
| 67 |
rsa_encrypted_key = public_key.encrypt(
|
| 68 |
aes_key,
|
| 69 |
padding.OAEP(mgf=padding.MGF1(hashes.SHA256()), algorithm=hashes.SHA256(), label=None)
|
| 70 |
)
|
| 71 |
|
|
|
|
| 72 |
encrypted_payload = struct.pack('>I', len(rsa_encrypted_key)) + rsa_encrypted_key + nonce + ciphertext
|
| 73 |
|
|
|
|
| 74 |
img = Image.new('RGB', (800, 600), color=(45, 52, 54))
|
| 75 |
draw = ImageDraw.Draw(img)
|
| 76 |
try:
|
|
|
|
| 79 |
font = ImageFont.load_default(size=30)
|
| 80 |
draw.text((400, 300), "KeyLock Secure Data", fill=(223, 230, 233), font=font, anchor="ms")
|
| 81 |
|
|
|
|
| 82 |
pixel_data = np.array(img.convert("RGB")).ravel()
|
| 83 |
binary_payload = ''.join(format(b, '08b') for b in struct.pack('>I', len(encrypted_payload)) + encrypted_payload)
|
| 84 |
|
|
|
|
| 91 |
return Image.fromarray(stego_pixels, 'RGB')
|
| 92 |
|
| 93 |
def get_server_list():
|
|
|
|
| 94 |
status = "Fetching server list from remote config..."
|
| 95 |
yield gr.Dropdown(choices=[], value=None, label="β³ Fetching..."), status, []
|
| 96 |
try:
|
|
|
|
| 104 |
logger.warning(f"Skipping invalid entry (missing name or public_key): {entry}")
|
| 105 |
continue
|
| 106 |
|
|
|
|
| 107 |
if "api_endpoint" not in entry:
|
| 108 |
if "link" in entry:
|
| 109 |
base_url = entry["link"].strip("/")
|
|
|
|
| 127 |
yield gr.Dropdown(choices=[], value=None, label="Error fetching servers"), status, []
|
| 128 |
|
| 129 |
def create_keylock_wrapper(service_name: str, secret_data: str, available_endpoints: list):
|
|
|
|
| 130 |
if not service_name:
|
| 131 |
raise gr.Error("Please select a target server.")
|
| 132 |
public_key = next((e['public_key'] for e in available_endpoints if e['name'] == service_name), None)
|
|
|
|
| 140 |
return None, f"β Error: {e}"
|
| 141 |
|
| 142 |
def send_keylock_wrapper(service_name: str, image: Image.Image, available_endpoints: list):
|
|
|
|
| 143 |
if not service_name:
|
| 144 |
raise gr.Error("Please select a target server.")
|
| 145 |
if image is None:
|
| 146 |
raise gr.Error("Please create or upload an image to send.")
|
| 147 |
|
| 148 |
+
endpoint_details = next((e for e in available_endpoints if e['name'] == service_name), None)
|
| 149 |
+
if not endpoint_details:
|
| 150 |
+
raise gr.Error(f"Configuration Error: Could not find details for '{service_name}'. Refresh the list.")
|
| 151 |
+
|
| 152 |
+
server_url = endpoint_details.get('link')
|
| 153 |
+
if not server_url:
|
| 154 |
+
raise gr.Error(f"Configuration Error: The selected server '{service_name}' is missing a 'link' to its Space.")
|
| 155 |
+
|
| 156 |
+
status = f"Connecting to remote server: {server_url}"
|
| 157 |
yield None, status
|
| 158 |
|
| 159 |
try:
|
|
|
|
| 161 |
image.save(buffer, format="PNG")
|
| 162 |
b64_string = base64.b64encode(buffer.getvalue()).decode("utf-8")
|
| 163 |
|
| 164 |
+
client = Client(server_url)
|
| 165 |
+
result = client.predict(
|
| 166 |
+
image_base64_string=b64_string,
|
| 167 |
+
api_name="/keylock-auth-decoder"
|
| 168 |
+
)
|
|
|
|
| 169 |
|
| 170 |
+
decrypted_data = result
|
| 171 |
+
if isinstance(decrypted_data, str):
|
| 172 |
+
try:
|
| 173 |
+
decrypted_data = json.loads(decrypted_data)
|
| 174 |
+
except json.JSONDecodeError:
|
| 175 |
+
pass
|
| 176 |
+
yield decrypted_data, "β
Success! Data decrypted by remote server."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 177 |
|
| 178 |
except Exception as e:
|
| 179 |
+
logger.error(f"Error calling server with gradio_client: {e}")
|
| 180 |
yield None, f"β Error calling server API: {e}"
|
| 181 |
|
| 182 |
def refresh_and_update_all():
|
|
|
|
|
|
|
| 183 |
for dropdown_update, status_update, state_update in get_server_list():
|
| 184 |
pass
|
| 185 |
return dropdown_update, dropdown_update, status_update, state_update
|
| 186 |
|
|
|
|
| 187 |
theme = gr.themes.Base(
|
| 188 |
primary_hue=gr.themes.colors.blue, secondary_hue=gr.themes.colors.sky, neutral_hue=gr.themes.colors.slate,
|
| 189 |
font=(gr.themes.GoogleFont("Inter"), "system-ui", "sans-serif"),
|
|
|
|
| 216 |
|
| 217 |
with gr.TabItem("β‘ Send KeyLock", id=1):
|
| 218 |
gr.Markdown("## Step 2: Decrypt via Live API Call")
|
|
|
|
| 219 |
gr.Markdown("This tool acts as the **Client**. It sends the encrypted image you created in Step 1 to the live, remote **Decoder Server** you select from the same configuration list. The server uses its securely stored private key to decrypt the data and sends the result back.")
|
| 220 |
with gr.Row(variant="panel"):
|
| 221 |
with gr.Column(scale=1):
|
|
|
|
| 247 |
output_private_key = gr.Textbox(lines=10, label="Generated Private Key", interactive=False, show_copy_button=True)
|
| 248 |
gen_keys_button = gr.Button("βοΈ Generate New 2048-bit Key Pair", variant="secondary")
|
| 249 |
|
|
|
|
| 250 |
gen_keys_button.click(fn=generate_rsa_keys, inputs=None, outputs=[output_private_key, output_public_key])
|
| 251 |
refresh_button.click(fn=refresh_and_update_all, outputs=[creator_service_dropdown, send_service_dropdown, creator_status, endpoints_state])
|
| 252 |
demo.load(fn=refresh_and_update_all, outputs=[creator_service_dropdown, send_service_dropdown, creator_status, endpoints_state])
|