broadfield-dev commited on
Commit
b1bd8c8
Β·
verified Β·
1 Parent(s): eb48225

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +151 -34
app.py CHANGED
@@ -1,24 +1,130 @@
1
  import gradio as gr
2
- import core # Import all our local logic
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
 
4
  # ==============================================================================
5
- # GRADIO UI HELPER FUNCTIONS
 
 
 
 
 
 
 
 
 
 
6
  # ==============================================================================
7
- def creator_wrapper(public_key: str, secret_data: str):
8
- """UI wrapper for the image creation logic."""
9
- try:
10
- created_image = core.create_encrypted_image(secret_data, public_key)
11
- return created_image, f"βœ… Success! Image created. You can now go to the 'Send KeyLock' tab to test it."
12
- except Exception as e:
13
- return None, f"❌ Error: {e}"
14
 
15
- def decoder_wrapper(image: gr.Image, private_key: str):
16
- """UI wrapper for the image decryption logic."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  try:
18
- decrypted_data = core.decode_data_from_image(image, private_key)
19
- return decrypted_data, "βœ… Success! Data decrypted from image."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  except Exception as e:
21
- return None, f"❌ Error: {e}"
 
 
22
 
23
  # ==============================================================================
24
  # GRADIO DASHBOARD INTERFACE
@@ -34,69 +140,80 @@ theme = gr.themes.Base(
34
 
35
  with gr.Blocks(theme=theme, title="KeyLock Operations Dashboard") as demo:
36
  gr.Markdown("# πŸ”‘ KeyLock Operations Dashboard")
37
- gr.Markdown("A self-contained demonstration of the entire KeyLock workflow: Key Generation, Image Creation, and Decryption.")
38
 
39
  with gr.Tabs() as tabs:
40
  with gr.TabItem("β‘  Generate Keys", id=0):
41
- gr.Markdown("## Step 1: Create a Secure Key Pair")
42
  gr.Markdown(
43
  """
44
- Every secure system starts with a key pair. This consists of a **Public Key** and a **Private Key**.
45
- - **Public Key πŸ”‘:** You can share this with anyone. It's used only for *encrypting* data. In a real system, you would add this key to a server's configuration file (like an `endpoints.json`) so that clients know how to encrypt data for it.
46
- - **Private Key πŸ”:** This must be kept **absolutely secret**. It is the only key that can *decrypt* data encrypted with its corresponding public key. In a real system, this would be stored as a secure environment variable or secret on the server.
47
  """
48
  )
49
  with gr.Row(variant="panel"):
50
  with gr.Column(scale=1):
51
  gr.Markdown("### Your New Keys")
52
- gen_keys_button = gr.Button("Generate New 2048-bit Key Pair", variant="secondary")
53
- gr.Markdown("⬇️ **Copy these keys for the next steps!**")
54
  with gr.Column(scale=2):
55
  with gr.Row():
56
  output_public_key = gr.Textbox(lines=11, label="Generated Public Key (For Creator)", interactive=False, show_copy_button=True)
57
  output_private_key = gr.Textbox(lines=11, label="Generated Private Key (For Decoder)", interactive=False, show_copy_button=True)
58
 
59
  with gr.TabItem("β‘‘ Create KeyLock", id=1):
60
- gr.Markdown("## Step 2: Create an Encrypted Auth Image")
61
- gr.Markdown("This tool acts as the **Auth Creator**. It takes your secret data and uses the **Public Key** from Step 1 to encrypt it into a new PNG image. This simulates a user preparing their credentials to send to a secure service.")
 
 
 
 
 
 
62
  with gr.Row(variant="panel"):
63
  with gr.Column(scale=1):
64
  gr.Markdown("### Configuration")
65
  creator_pubkey_input = gr.Textbox(lines=8, label="Paste the Public Key Here", placeholder="Copy the public key generated in Step 1...")
66
- creator_secret_input = gr.Textbox(lines=5, label="Secret Data to Encrypt", placeholder="API_KEY: sk-123...\nUSER: demo-user")
67
  creator_button = gr.Button("✨ Create Auth Image", variant="primary")
68
  with gr.Column(scale=1):
69
  gr.Markdown("### Output")
70
  creator_status = gr.Textbox(label="Status", interactive=False, lines=2)
71
- # format="png" is the key to ensuring the download button creates a proper PNG file.
72
  creator_image_output = gr.Image(label="Generated Encrypted Image", type="pil", show_download_button=True, format="png", show_share_button=False)
73
 
74
  with gr.TabItem("β‘’ Send KeyLock", id=2):
75
- gr.Markdown("## Step 3: Decrypt the Image (Client Simulation)")
76
- gr.Markdown("This tool acts as the **Client** sending the image to a secure **Server**. To prove it can decrypt the data, the 'Server' needs the corresponding **Private Key** from Step 1. In a real application, you would only send the image; the server would already have its private key.")
 
 
 
 
 
 
 
 
77
  with gr.Row(variant="panel"):
78
  with gr.Column(scale=1):
79
  gr.Markdown("### Input")
80
  client_image_input = gr.Image(type="pil", label="Upload or Drag Encrypted Image Here", sources=["upload", "clipboard"])
81
- client_private_key_input = gr.Textbox(lines=8, label="Paste the Private Key Here", placeholder="Copy the private key generated in Step 1...")
82
- client_button = gr.Button("πŸ”“ Decrypt Image", variant="primary")
83
  with gr.Column(scale=1):
84
  gr.Markdown("### Decrypted Data")
85
  client_status = gr.Textbox(label="Status", interactive=False, lines=2)
86
- client_json_output = gr.JSON(label="Result from 'Server'")
87
 
88
  # --- Wire up the component logic ---
89
- gen_keys_button.click(fn=core.generate_rsa_keys, inputs=None, outputs=[output_private_key, output_public_key])
90
 
91
  creator_button.click(
92
- fn=creator_wrapper,
93
  inputs=[creator_pubkey_input, creator_secret_input],
94
  outputs=[creator_image_output, creator_status]
95
  )
96
 
97
  client_button.click(
98
- fn=decoder_wrapper,
99
- inputs=[client_image_input, client_private_key_input],
100
  outputs=[client_json_output, client_status]
101
  )
102
 
 
1
  import gradio as gr
2
+ import json
3
+ import os
4
+ import io
5
+ import base64
6
+ import struct
7
+ import logging
8
+ import requests
9
+ from PIL import Image, ImageDraw, ImageFont
10
+ import numpy as np
11
+ from cryptography.hazmat.primitives.ciphers.aead import AESGCM
12
+ from cryptography.hazmat.primitives import hashes
13
+ from cryptography.hazmat.primitives import serialization
14
+ from cryptography.hazmat.primitives.asymmetric import rsa, padding
15
+ from cryptography.exceptions import InvalidTag
16
+
17
+ # --- Configure Logging ---
18
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
19
+ logger = logging.getLogger(__name__)
20
 
21
  # ==============================================================================
22
+ # CONFIGURATION: URL of the Remote SERVER Service
23
+ # ==============================================================================
24
+ SERVER_SPACE_ID = "broadfield-dev/KeyLock-Auth-Server"
25
+ BASE_HF_URL = "https://huggingface.co/spaces/"
26
+ SERVER_URL = f"{BASE_HF_URL}{SERVER_SPACE_ID}"
27
+ # The API endpoint is constructed from the server's direct URL, not the hub URL.
28
+ SERVER_DIRECT_URL_BASE = f"https://{SERVER_SPACE_ID.replace('/', '-')}.hf.space"
29
+ SERVER_API_ENDPOINT = f"{SERVER_DIRECT_URL_BASE}/run/keylock-auth-decoder"
30
+
31
+ # ==============================================================================
32
+ # LOCAL LOGIC (Key and Image Generation)
33
  # ==============================================================================
 
 
 
 
 
 
 
34
 
35
+ def generate_rsa_keys():
36
+ """Generates a new 2048-bit RSA key pair LOCALLY."""
37
+ logger.info("Generating new RSA key pair locally.")
38
+ private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
39
+ private_pem = private_key.private_bytes(
40
+ encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8,
41
+ encryption_algorithm=serialization.NoEncryption()
42
+ ).decode('utf-8')
43
+ public_pem = private_key.public_key().public_bytes(
44
+ encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo
45
+ ).decode('utf-8')
46
+ return private_pem, public_pem
47
+
48
+ def create_encrypted_image(secret_data_str: str, public_key_pem: str) -> Image.Image:
49
+ """Creates the encrypted image LOCALLY."""
50
+ logger.info("Starting local image creation process...")
51
+ if not secret_data_str.strip(): raise ValueError("Secret data cannot be empty.")
52
+ if not public_key_pem.strip(): raise ValueError("Public Key cannot be empty.")
53
+
54
+ data_dict = {}
55
+ for line in secret_data_str.splitlines():
56
+ if not line.strip() or line.strip().startswith('#'): continue
57
+ parts = line.split(':', 1) if ':' in line else line.split('=', 1)
58
+ if len(parts) != 2: continue
59
+ data_dict[parts[0].strip()] = parts[1].strip().strip("'\"")
60
+ if not data_dict: raise ValueError("No valid key-value pairs found.")
61
+
62
+ json_bytes = json.dumps(data_dict).encode('utf-8')
63
+ public_key = serialization.load_pem_public_key(public_key_pem.encode('utf-8'))
64
+ aes_key, nonce = os.urandom(32), os.urandom(12)
65
+ ciphertext_with_tag = AESGCM(aes_key).encrypt(nonce, json_bytes, None)
66
+ rsa_encrypted_aes_key = public_key.encrypt(
67
+ aes_key, padding.OAEP(mgf=padding.MGF1(hashes.SHA256()), algorithm=hashes.SHA256(), label=None)
68
+ )
69
+ encrypted_payload = struct.pack('>I', len(rsa_encrypted_aes_key)) + rsa_encrypted_aes_key + nonce + ciphertext_with_tag
70
+
71
+ img = Image.new('RGB', (800, 600), color=(45, 52, 54))
72
+ draw = ImageDraw.Draw(img)
73
+ try: font = ImageFont.truetype("DejaVuSans.ttf", 40)
74
+ except IOError: font = ImageFont.load_default(size=30)
75
+ draw.text((400, 300), "KeyLock Secure Data", fill=(223, 230, 233), font=font, anchor="ms")
76
+
77
+ pixel_data = np.array(img.convert("RGB")).ravel()
78
+ binary_payload = ''.join(format(byte, '08b') for byte in struct.pack('>I', len(encrypted_payload)) + encrypted_payload)
79
+ if len(binary_payload) > pixel_data.size: raise ValueError("Data too large for image capacity.")
80
+ for i in range(len(binary_payload)): pixel_data[i] = (pixel_data[i] & 0xFE) | int(binary_payload[i])
81
+
82
+ stego_pixels = pixel_data.reshape((600, 800, 3))
83
+ return Image.fromarray(stego_pixels, 'RGB')
84
+
85
+ # ==============================================================================
86
+ # REMOTE API CALL LOGIC
87
+ # ==============================================================================
88
+
89
+ def decrypt_image_via_api(image: Image.Image):
90
+ """Makes a LIVE API call to the deployed server to decrypt an image."""
91
+ if image is None: raise gr.Error("Please provide an image to send.")
92
+
93
+ status = f"Connecting to server: {SERVER_SPACE_ID}..."
94
+ yield None, status
95
+
96
  try:
97
+ with io.BytesIO() as buffer:
98
+ image.save(buffer, format="PNG")
99
+ b64_string = base64.b64encode(buffer.getvalue()).decode("utf-8")
100
+
101
+ payload = {"data": [b64_string]}
102
+ headers = {"Content-Type": "application/json"}
103
+
104
+ status = f"Sending image to API endpoint:\n{SERVER_API_ENDPOINT}"
105
+ yield None, status
106
+
107
+ response = requests.post(SERVER_API_ENDPOINT, headers=headers, json=payload, timeout=45)
108
+ response_json = response.json()
109
+
110
+ if response.status_code == 200:
111
+ if "data" in response_json:
112
+ decrypted_data = response_json["data"][0]
113
+ status = "βœ… Success! Data decrypted by the remote server."
114
+ return decrypted_data, status
115
+ elif "error" in response_json:
116
+ raise gr.Error(f"API returned an error: {response_json['error']}")
117
+ else:
118
+ error_detail = response_json.get("error", "Unknown error.")
119
+ raise gr.Error(f"API Error (Status {response.status_code}): {error_detail}")
120
+
121
+ except requests.exceptions.RequestException as e:
122
+ logger.error(f"Network error calling API: {e}")
123
+ raise gr.Error(f"Could not connect to the API. Check the server space is running and the URL is correct. Error: {e}")
124
  except Exception as e:
125
+ logger.error(f"An unexpected error occurred: {e}", exc_info=True)
126
+ raise gr.Error(f"An unexpected error occurred: {e}")
127
+
128
 
129
  # ==============================================================================
130
  # GRADIO DASHBOARD INTERFACE
 
140
 
141
  with gr.Blocks(theme=theme, title="KeyLock Operations Dashboard") as demo:
142
  gr.Markdown("# πŸ”‘ KeyLock Operations Dashboard")
143
+ gr.Markdown("A self-contained dashboard to demonstrate the KeyLock ecosystem. Key/Image creation is performed locally, while decryption is handled by a **live, remote API call** to a secure server.")
144
 
145
  with gr.Tabs() as tabs:
146
  with gr.TabItem("β‘  Generate Keys", id=0):
147
+ gr.Markdown("## Step 1: Create a Secure Key Pair (Local)")
148
  gr.Markdown(
149
  """
150
+ This tool generates a new RSA key pair within your browser session. In a real-world scenario, the **Private Key** would be immediately stored as a secure secret on a server (like the `KEYLOCK_PRIV_KEY` secret on our demo server), and would never be shown in a UI like this. The **Public Key** would be distributed to clients or other services that need to encrypt data for that server.
151
+
152
+ **Action:** Click the button below, then copy both keys for the next steps.
153
  """
154
  )
155
  with gr.Row(variant="panel"):
156
  with gr.Column(scale=1):
157
  gr.Markdown("### Your New Keys")
158
+ gen_keys_button = gr.Button("Generate New 2048-bit Key Pair", icon="πŸ”‘", variant="secondary")
 
159
  with gr.Column(scale=2):
160
  with gr.Row():
161
  output_public_key = gr.Textbox(lines=11, label="Generated Public Key (For Creator)", interactive=False, show_copy_button=True)
162
  output_private_key = gr.Textbox(lines=11, label="Generated Private Key (For Decoder)", interactive=False, show_copy_button=True)
163
 
164
  with gr.TabItem("β‘‘ Create KeyLock", id=1):
165
+ gr.Markdown("## Step 2: Create an Encrypted Auth Image (Local)")
166
+ gr.Markdown(
167
+ """
168
+ This tool acts as the **Auth Creator**. It takes your secret data and uses the **Public Key** you generated in Step 1 to encrypt it into a new PNG image. This entire process happens locally in this application. This simulates a user or an automated client preparing credentials to send to the secure server.
169
+
170
+ **Action:** Paste the **Public Key** from Step 1, enter some secrets, and click create.
171
+ """
172
+ )
173
  with gr.Row(variant="panel"):
174
  with gr.Column(scale=1):
175
  gr.Markdown("### Configuration")
176
  creator_pubkey_input = gr.Textbox(lines=8, label="Paste the Public Key Here", placeholder="Copy the public key generated in Step 1...")
177
+ creator_secret_input = gr.Textbox(lines=5, label="Secret Data to Encrypt", placeholder="SESSION_ID: abc-123\nUSER: demo@example.com")
178
  creator_button = gr.Button("✨ Create Auth Image", variant="primary")
179
  with gr.Column(scale=1):
180
  gr.Markdown("### Output")
181
  creator_status = gr.Textbox(label="Status", interactive=False, lines=2)
 
182
  creator_image_output = gr.Image(label="Generated Encrypted Image", type="pil", show_download_button=True, format="png", show_share_button=False)
183
 
184
  with gr.TabItem("β‘’ Send KeyLock", id=2):
185
+ gr.Markdown("## Step 3: Decrypt via Live API Call")
186
+ gr.Markdown(
187
+ f"""
188
+ This is the core demonstration. This tool acts as a **Client** sending the encrypted image to our live, remote **Server** at [{SERVER_SPACE_ID}]({SERVER_URL}).
189
+
190
+ For this demo to work, the **Private Key** you generated in Step 1 must be **the same one** set as the `KEYLOCK_PRIV_KEY` secret in the `{SERVER_SPACE_ID}` Space settings. The client sends the image, and the server uses its own secret key to decrypt it.
191
+
192
+ **Action:** Upload the image from Step 2. The dashboard will make a live API call to `{SERVER_API_ENDPOINT}`.
193
+ """
194
+ )
195
  with gr.Row(variant="panel"):
196
  with gr.Column(scale=1):
197
  gr.Markdown("### Input")
198
  client_image_input = gr.Image(type="pil", label="Upload or Drag Encrypted Image Here", sources=["upload", "clipboard"])
199
+ client_button = gr.Button("πŸ”“ Decrypt Image via Remote Server", variant="primary")
 
200
  with gr.Column(scale=1):
201
  gr.Markdown("### Decrypted Data")
202
  client_status = gr.Textbox(label="Status", interactive=False, lines=2)
203
+ client_json_output = gr.JSON(label="Result from Server")
204
 
205
  # --- Wire up the component logic ---
206
+ gen_keys_button.click(fn=generate_rsa_keys, inputs=None, outputs=[output_private_key, output_public_key])
207
 
208
  creator_button.click(
209
+ fn=create_encrypted_image,
210
  inputs=[creator_pubkey_input, creator_secret_input],
211
  outputs=[creator_image_output, creator_status]
212
  )
213
 
214
  client_button.click(
215
+ fn=decrypt_image_via_api,
216
+ inputs=[client_image_input],
217
  outputs=[client_json_output, client_status]
218
  )
219