Create keylock_component.py
Browse files- keylock_component.py +162 -0
keylock_component.py
ADDED
@@ -0,0 +1,162 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from PIL import Image, ImageOps
|
3 |
+
import requests
|
4 |
+
import io
|
5 |
+
import json
|
6 |
+
import logging
|
7 |
+
import os
|
8 |
+
import struct
|
9 |
+
import tempfile
|
10 |
+
from cryptography.hazmat.primitives import serialization
|
11 |
+
from cryptography.hazmat.primitives.asymmetric import rsa, padding
|
12 |
+
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
|
13 |
+
from cryptography.hazmat.primitives import hashes
|
14 |
+
import numpy as np
|
15 |
+
|
16 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
17 |
+
|
18 |
+
# --- Backend Logic Class (Enhanced with more methods) ---
|
19 |
+
class AppServerLogic:
|
20 |
+
"""Contains all backend logic and mock data needed by the application."""
|
21 |
+
def __init__(self):
|
22 |
+
self.private_key_object = None
|
23 |
+
self.public_key_pem = ""
|
24 |
+
self.mock_user_db = {
|
25 |
+
"demo-user": {"api_key": "sk-12345-abcde", "password": "password123"},
|
26 |
+
"admin-user": {"api_key": "sk-67890-fghij", "password": "adminpass"}
|
27 |
+
}
|
28 |
+
self._initialize_keys()
|
29 |
+
|
30 |
+
def _initialize_keys(self):
|
31 |
+
key_pem = os.environ.get('KEYLOCK_PRIV_KEY')
|
32 |
+
if not key_pem:
|
33 |
+
pk = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
34 |
+
key_pem = pk.private_bytes(encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption()).decode('utf-8')
|
35 |
+
try:
|
36 |
+
self.private_key_object = serialization.load_pem_private_key(key_pem.encode(), password=None)
|
37 |
+
self.public_key_pem = self.private_key_object.public_key().public_bytes(encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo).decode('utf-8')
|
38 |
+
except Exception as e:
|
39 |
+
logging.error(f"Key initialization failed: {e}")
|
40 |
+
|
41 |
+
def decode_payload(self, image_input):
|
42 |
+
if not self.private_key_object:
|
43 |
+
return {"status": "Error", "message": "Server key not configured."}
|
44 |
+
try:
|
45 |
+
pixel_data = np.array(image_input.convert("RGB")).ravel()
|
46 |
+
header_binary = "".join(str(p & 1) for p in pixel_data[:32])
|
47 |
+
data_length = int(header_binary, 2)
|
48 |
+
required_pixels = 32 + data_length * 8
|
49 |
+
if required_pixels > len(pixel_data):
|
50 |
+
raise ValueError("Incomplete payload in image.")
|
51 |
+
data_binary = "".join(str(p & 1) for p in pixel_data[32:required_pixels])
|
52 |
+
crypto_payload = int(data_binary, 2).to_bytes(data_length, byteorder='big')
|
53 |
+
offset = 4
|
54 |
+
encrypted_aes_key_len = struct.unpack('>I', crypto_payload[:offset])[0]
|
55 |
+
encrypted_aes_key = crypto_payload[offset:offset + encrypted_aes_key_len]; offset += encrypted_aes_key_len
|
56 |
+
nonce = crypto_payload[offset:offset + 12]; offset += 12
|
57 |
+
ciphertext = crypto_payload[offset:]
|
58 |
+
recovered_aes_key = self.private_key_object.decrypt(encrypted_aes_key, padding.OAEP(mgf=padding.MGF1(hashes.SHA256()), algorithm=hashes.SHA256(), label=None))
|
59 |
+
payload = json.loads(AESGCM(recovered_aes_key).decrypt(nonce, ciphertext, None).decode())
|
60 |
+
return {"status": "Success", "payload": payload}
|
61 |
+
except Exception as e:
|
62 |
+
return {"status": "Error", "message": f"Decryption Failed: {e}"}
|
63 |
+
|
64 |
+
def generate_encrypted_image(self, payload_dict):
|
65 |
+
"""
|
66 |
+
Creates a KeyLock image and returns both a Pillow object for preview
|
67 |
+
and a filepath to a saved, uncorrupted PNG for download.
|
68 |
+
"""
|
69 |
+
try:
|
70 |
+
response = requests.get("https://images.unsplash.com/photo-1506318137071-a8e063b4bec0?q=80&w=1200", timeout=10)
|
71 |
+
img = ImageOps.fit(Image.open(io.BytesIO(response.content)).convert("RGB"), (600, 600))
|
72 |
+
except:
|
73 |
+
img = Image.new('RGB', (600, 600), color=(15, 23, 42))
|
74 |
+
|
75 |
+
json_bytes = json.dumps(payload_dict).encode('utf-8')
|
76 |
+
public_key = serialization.load_pem_public_key(self.public_key_pem.encode('utf-8'))
|
77 |
+
aes_key, nonce = os.urandom(32), os.urandom(12)
|
78 |
+
ciphertext = AESGCM(aes_key).encrypt(nonce, json_bytes, None)
|
79 |
+
rsa_key = public_key.encrypt(aes_key, padding.OAEP(mgf=padding.MGF1(hashes.SHA256()), algorithm=hashes.SHA256(), label=None))
|
80 |
+
payload = struct.pack('>I', len(rsa_key)) + rsa_key + nonce + ciphertext
|
81 |
+
|
82 |
+
pixel_data = np.array(img).ravel()
|
83 |
+
binary_payload = ''.join(format(b, '08b') for b in struct.pack('>I', len(payload)) + payload)
|
84 |
+
pixel_data[:len(binary_payload)] = (pixel_data[:len(binary_payload)] & 0xFE) | np.array(list(binary_payload), dtype=np.uint8)
|
85 |
+
final_image = Image.fromarray(pixel_data.reshape(img.size[1], img.size[0], 3), 'RGB')
|
86 |
+
|
87 |
+
# Save the pristine PNG to a temporary file and return its path for the download link.
|
88 |
+
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as f:
|
89 |
+
final_image.save(f.name, "PNG")
|
90 |
+
# Return both the Pillow image for preview and the filepath for download.
|
91 |
+
return final_image, f.name
|
92 |
+
|
93 |
+
@staticmethod
|
94 |
+
def generate_pem_keys():
|
95 |
+
pk = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
96 |
+
priv = pk.private_bytes(encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption()).decode()
|
97 |
+
pub = pk.public_key().public_bytes(encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo).decode()
|
98 |
+
return priv, pub
|
99 |
+
|
100 |
+
# --- UI Component Class (Enhanced with download functionality) ---
|
101 |
+
class KeylockDecoderComponent(gr.components.Component):
|
102 |
+
"""A Gradio Component that decodes a KeyLock image and provides advanced tools."""
|
103 |
+
EVENTS = ["change"]
|
104 |
+
|
105 |
+
def __init__(self, server_logic, **kwargs):
|
106 |
+
self.server_logic = server_logic
|
107 |
+
self.value = None
|
108 |
+
super().__init__(**kwargs)
|
109 |
+
|
110 |
+
def _format_message(self, result: dict | None) -> str:
|
111 |
+
if not result or not result.get("status"): return "Upload a KeyLock image to auto-fill credentials."
|
112 |
+
status = result["status"]
|
113 |
+
if status == "Success":
|
114 |
+
user = result.get("payload", {}).get("USER", "N/A")
|
115 |
+
return f"<p style='color:green; font-weight:bold;'>✅ Success! Decoded credentials for '{user}'.</p>"
|
116 |
+
else:
|
117 |
+
message = result.get("message", "An unknown error occurred.")
|
118 |
+
return f"<p style='color:red; font-weight:bold;'>❌ Error: {message}</p>"
|
119 |
+
|
120 |
+
def preprocess(self, payload): return payload
|
121 |
+
def postprocess(self, value): return value
|
122 |
+
def api_info(self): return {"type": "object", "example": {"status": "Success", "payload": {"USER": "demo-user"}}}
|
123 |
+
|
124 |
+
def render(self):
|
125 |
+
value_state = gr.State(value=self.value)
|
126 |
+
|
127 |
+
with gr.Column():
|
128 |
+
image_input = gr.Image(label="KeyLock Image", type="pil", show_label=False)
|
129 |
+
status_display = gr.Markdown(self._format_message(self.value))
|
130 |
+
|
131 |
+
with gr.Accordion("Generate Encrypted Image", open=False):
|
132 |
+
gr.Markdown("Create a test image using the site's public key.")
|
133 |
+
payload_input = gr.JSON(label="Payload to Encrypt", value={"API_KEY": "sk-12345-abcde", "USER": "demo-user"})
|
134 |
+
generate_img_button = gr.Button("Generate Image", variant="secondary")
|
135 |
+
# Use two components: an Image for preview and a File for download
|
136 |
+
generated_image_preview = gr.Image(label="Generated Image Preview", interactive=False)
|
137 |
+
generated_file_download = gr.File(label="Download Uncorrupted PNG", interactive=False)
|
138 |
+
|
139 |
+
with gr.Accordion("Create New Standalone Key Pair", open=False):
|
140 |
+
gr.Markdown("Generate a new, random key pair for testing or other uses.")
|
141 |
+
generate_keys_button = gr.Button("Generate Keys", variant="secondary")
|
142 |
+
with gr.Row():
|
143 |
+
output_private_key = gr.Code(label="Generated Private Key", language="pem")
|
144 |
+
output_public_key = gr.Code(label="Generated Public Key", language="pem")
|
145 |
+
|
146 |
+
def on_image_upload(image):
|
147 |
+
if image is None: return None, "Upload a KeyLock image to auto-fill credentials."
|
148 |
+
result_dict = self.server_logic.decode_payload(image)
|
149 |
+
formatted_message = self._format_message(result_dict)
|
150 |
+
return result_dict, formatted_message
|
151 |
+
|
152 |
+
# Wire all event handlers
|
153 |
+
image_input.upload(fn=on_image_upload, inputs=[image_input], outputs=[value_state, status_display])
|
154 |
+
# The button now populates both the preview and the download link.
|
155 |
+
generate_img_button.click(
|
156 |
+
fn=self.server_logic.generate_encrypted_image,
|
157 |
+
inputs=[payload_input],
|
158 |
+
outputs=[generated_image_preview, generated_file_download]
|
159 |
+
)
|
160 |
+
generate_keys_button.click(fn=self.server_logic.generate_pem_keys, inputs=None, outputs=[output_private_key, output_public_key])
|
161 |
+
|
162 |
+
return {"value": value_state}
|