Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,215 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 tempfile
|
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 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 |
+
# LOAD KEYS AND CONFIG
|
23 |
+
# ==============================================================================
|
24 |
+
KEYLOCK_PRIV_KEY = os.environ.get('KEYLOCK_PRIV_KEY')
|
25 |
+
PUBLIC_KEY_PEM_STRING = ""
|
26 |
+
try:
|
27 |
+
with open("keylock_pub.pem", "r") as f:
|
28 |
+
PUBLIC_KEY_PEM_STRING = f.read()
|
29 |
+
logger.info("Successfully loaded public key from keylock_pub.pem.")
|
30 |
+
except FileNotFoundError:
|
31 |
+
PUBLIC_KEY_PEM_STRING = "Error: keylock_pub.pem file not found. 'Creator' tab will not work."
|
32 |
+
|
33 |
+
# ==============================================================================
|
34 |
+
# CREATOR LOGIC
|
35 |
+
# ==============================================================================
|
36 |
+
def create_encrypted_image(secret_data_str: str, public_key_pem: str) -> Image.Image:
|
37 |
+
if not secret_data_str.strip(): raise ValueError("Secret data cannot be empty.")
|
38 |
+
|
39 |
+
# 1. Parse & Encrypt Data
|
40 |
+
data_dict = {}
|
41 |
+
for line in secret_data_str.splitlines():
|
42 |
+
if not line.strip() or line.strip().startswith('#'): continue
|
43 |
+
key, value = line.split(':', 1) if ':' in line else line.split('=', 1)
|
44 |
+
data_dict[key.strip()] = value.strip().strip("'\"")
|
45 |
+
|
46 |
+
json_bytes = json.dumps(data_dict).encode('utf-8')
|
47 |
+
public_key = serialization.load_pem_public_key(public_key_pem.encode('utf-8'))
|
48 |
+
aes_key = os.urandom(32)
|
49 |
+
nonce = os.urandom(12)
|
50 |
+
ciphertext_with_tag = AESGCM(aes_key).encrypt(nonce, json_bytes, None)
|
51 |
+
rsa_encrypted_aes_key = public_key.encrypt(
|
52 |
+
aes_key, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)
|
53 |
+
)
|
54 |
+
encrypted_aes_key_len_bytes = struct.pack('>I', len(rsa_encrypted_aes_key))
|
55 |
+
encrypted_payload = encrypted_aes_key_len_bytes + rsa_encrypted_aes_key + nonce + ciphertext_with_tag
|
56 |
+
|
57 |
+
# 2. Create Carrier Image and Embed Data
|
58 |
+
img = Image.new('RGB', (800, 600), color=(45, 52, 54))
|
59 |
+
draw = ImageDraw.Draw(img)
|
60 |
+
try:
|
61 |
+
font = ImageFont.truetype("DejaVuSans.ttf", 40)
|
62 |
+
except IOError:
|
63 |
+
font = ImageFont.load_default()
|
64 |
+
draw.text((400, 300), "KeyLock Secure Data", fill=(223, 230, 233), font=font, anchor="ms")
|
65 |
+
|
66 |
+
img_rgb = img.convert("RGB")
|
67 |
+
pixel_data = np.array(img_rgb).ravel()
|
68 |
+
data_length_header = struct.pack('>I', len(encrypted_payload))
|
69 |
+
binary_payload = ''.join(format(byte, '08b') for byte in data_length_header + encrypted_payload)
|
70 |
+
if len(binary_payload) > pixel_data.size:
|
71 |
+
raise ValueError("Data is too large for the image capacity.")
|
72 |
+
for i in range(len(binary_payload)):
|
73 |
+
pixel_data[i] = (pixel_data[i] & 0xFE) | int(binary_payload[i])
|
74 |
+
stego_pixels = pixel_data.reshape(img_rgb.size[1], img_rgb.size[0], 3)
|
75 |
+
return Image.fromarray(stego_pixels, 'RGB')
|
76 |
+
|
77 |
+
# ==============================================================================
|
78 |
+
# SERVER (DECODER) LOGIC
|
79 |
+
# ==============================================================================
|
80 |
+
def decode_data_from_image(image: Image.Image) -> dict:
|
81 |
+
if not KEYLOCK_PRIV_KEY:
|
82 |
+
raise gr.Error("Server Error: The API is not configured with a private key.")
|
83 |
+
if image is None:
|
84 |
+
raise gr.Error("Please provide an image to decode.")
|
85 |
+
|
86 |
+
try:
|
87 |
+
private_key = serialization.load_pem_private_key(KEYLOCK_PRIV_KEY.encode(), password=None)
|
88 |
+
with io.BytesIO() as buffer:
|
89 |
+
image.save(buffer, format="PNG")
|
90 |
+
image_buffer = buffer.getvalue()
|
91 |
+
|
92 |
+
img_rgb = Image.open(io.BytesIO(image_buffer)).convert("RGB")
|
93 |
+
pixel_data = np.array(img_rgb).ravel()
|
94 |
+
|
95 |
+
header_binary_string = "".join(str(p & 1) for p in pixel_data[:32])
|
96 |
+
data_length = int(header_binary_string, 2)
|
97 |
+
end_offset = 32 + (data_length * 8)
|
98 |
+
if pixel_data.size < end_offset: raise ValueError("Image data corrupt or truncated.")
|
99 |
+
|
100 |
+
data_binary_string = "".join(str(p & 1) for p in pixel_data[32:end_offset])
|
101 |
+
crypto_payload = int(data_binary_string, 2).to_bytes(data_length, byteorder='big')
|
102 |
+
|
103 |
+
rsa_key_len = private_key.key_size // 8
|
104 |
+
len_header = struct.unpack('>I', crypto_payload[:4])[0]
|
105 |
+
if len_header != rsa_key_len: raise ValueError("Key pair mismatch or corrupt data.")
|
106 |
+
|
107 |
+
encrypted_key = crypto_payload[4:4 + rsa_key_len]
|
108 |
+
nonce = crypto_payload[4 + rsa_key_len : 4 + rsa_key_len + 12]
|
109 |
+
ciphertext = crypto_payload[4 + rsa_key_len + 12:]
|
110 |
+
|
111 |
+
aes_key = private_key.decrypt(encrypted_key, padding.OAEP(mgf=padding.MGF1(hashes.SHA256()), algorithm=hashes.SHA256(), label=None))
|
112 |
+
decrypted_bytes = AESGCM(aes_key).decrypt(nonce, ciphertext, None)
|
113 |
+
|
114 |
+
logger.info("Successfully decoded an image via internal call.")
|
115 |
+
return json.loads(decrypted_bytes.decode('utf-8'))
|
116 |
+
|
117 |
+
except Exception as e:
|
118 |
+
logger.error(f"Decryption failed: {e}", exc_info=True)
|
119 |
+
raise gr.Error(f"Decryption failed. The image may be corrupt, not encrypted with the correct key, or the server is misconfigured. Details: {e}")
|
120 |
+
|
121 |
+
# ==============================================================================
|
122 |
+
# GRADIO UI HELPER FUNCTIONS
|
123 |
+
# ==============================================================================
|
124 |
+
def creator_wrapper(secret_data_str: str):
|
125 |
+
"""Wrapper for the Gradio UI to call the creator function."""
|
126 |
+
if not PUBLIC_KEY_PEM_STRING or "Error" in PUBLIC_KEY_PEM_STRING:
|
127 |
+
raise gr.Error("Cannot create image: public key file is missing or invalid.")
|
128 |
+
try:
|
129 |
+
encrypted_image = create_encrypted_image(secret_data_str, PUBLIC_KEY_PEM_STRING)
|
130 |
+
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp:
|
131 |
+
encrypted_image.save(tmp.name)
|
132 |
+
return encrypted_image, tmp.name, "β
Success! Image created and ready for download."
|
133 |
+
except Exception as e:
|
134 |
+
return None, None, f"β Error: {e}"
|
135 |
+
|
136 |
+
# ==============================================================================
|
137 |
+
# GRADIO DASHBOARD INTERFACE
|
138 |
+
# ==============================================================================
|
139 |
+
theme = gr.themes.Base(
|
140 |
+
primary_hue="blue",
|
141 |
+
secondary_hue="blue",
|
142 |
+
neutral_hue="slate",
|
143 |
+
font=(gr.themes.GoogleFont("Inter"), "system-ui", "sans-serif"),
|
144 |
+
).set(
|
145 |
+
body_background_fill="#F0F2F5",
|
146 |
+
block_background_fill="white",
|
147 |
+
block_border_width="1px",
|
148 |
+
block_shadow="*shadow_drop_lg",
|
149 |
+
button_primary_background_fill="*primary_500",
|
150 |
+
button_primary_background_fill_hover="*primary_600",
|
151 |
+
button_primary_text_color="white",
|
152 |
+
)
|
153 |
+
|
154 |
+
with gr.Blocks(theme=theme, title="KeyLock Operations Dashboard") as demo:
|
155 |
+
gr.Markdown("# π KeyLock Operations Dashboard")
|
156 |
+
gr.Markdown("A unified dashboard to demonstrate the KeyLock ecosystem: API Server, Image Creator, and API Client.")
|
157 |
+
|
158 |
+
with gr.Tabs():
|
159 |
+
with gr.TabItem("π‘ API Server Status & Docs", id=0):
|
160 |
+
gr.Markdown("## Server Status")
|
161 |
+
key_status = "β
Loaded successfully from secrets." if KEYLOCK_PRIV_KEY else "β NOT FOUND. The API will not work. Set the `KEYLOCK_PRIV_KEY` secret in the Space settings."
|
162 |
+
gr.Textbox(label="Private Key Status", value=key_status, interactive=False)
|
163 |
+
|
164 |
+
with gr.Accordion("View Service Public Key", open=False):
|
165 |
+
gr.Code(value=PUBLIC_KEY_PEM_STRING, language="pem", label="Service Public Key (from keylock_pub.pem)")
|
166 |
+
|
167 |
+
gr.Markdown("## API Documentation")
|
168 |
+
gr.Markdown("This server exposes a conceptual API endpoint for external clients.")
|
169 |
+
gr.Code(language="markdown", value="""
|
170 |
+
- **Endpoint**: `/run/keylock-auth-decoder`
|
171 |
+
- **Method**: `POST`
|
172 |
+
- **Body**: JSON payload `{ "data": ["<base64_encoded_image_string>"] }`
|
173 |
+
""")
|
174 |
+
|
175 |
+
with gr.TabItem("π Image Creator", id=1):
|
176 |
+
gr.Markdown("## Create an Encrypted Image for the Server")
|
177 |
+
gr.Markdown("Use this tool to encrypt data using the server's public key.")
|
178 |
+
with gr.Row():
|
179 |
+
with gr.Column(scale=2):
|
180 |
+
creator_input = gr.Textbox(
|
181 |
+
lines=7,
|
182 |
+
label="Secret Data (Key-Value Pairs)",
|
183 |
+
placeholder="USERNAME: [email protected]\nAPI_KEY: sk-12345..."
|
184 |
+
)
|
185 |
+
creator_button = gr.Button("Create Encrypted Image", variant="primary")
|
186 |
+
with gr.Column(scale=1):
|
187 |
+
creator_status = gr.Textbox(label="Status", interactive=False)
|
188 |
+
creator_image_output = gr.Image(label="Generated Encrypted Image", type="pil")
|
189 |
+
creator_download_output = gr.File(label="Download Image")
|
190 |
+
|
191 |
+
with gr.TabItem("π» API Client (Simulator)", id=2):
|
192 |
+
gr.Markdown("## Decrypt an Image via Simulated API Call")
|
193 |
+
gr.Markdown("Upload an image created by the 'Creator' tab to test the server's decryption logic.")
|
194 |
+
with gr.Row():
|
195 |
+
with gr.Column(scale=1):
|
196 |
+
client_input_image = gr.Image(type="pil", label="Upload Encrypted Image", sources=["upload", "clipboard"])
|
197 |
+
client_decrypt_button = gr.Button("Decrypt Image", variant="primary")
|
198 |
+
with gr.Column(scale=1):
|
199 |
+
client_output_json = gr.JSON(label="Decrypted Data from Server")
|
200 |
+
|
201 |
+
# --- Wire up the component logic ---
|
202 |
+
creator_button.click(
|
203 |
+
fn=creator_wrapper,
|
204 |
+
inputs=[creator_input],
|
205 |
+
outputs=[creator_image_output, creator_download_output, creator_status]
|
206 |
+
)
|
207 |
+
|
208 |
+
client_decrypt_button.click(
|
209 |
+
fn=decode_data_from_image,
|
210 |
+
inputs=[client_input_image],
|
211 |
+
outputs=[client_output_json]
|
212 |
+
)
|
213 |
+
|
214 |
+
if __name__ == "__main__":
|
215 |
+
demo.launch()
|