Update keylock_component.py
Browse files- keylock_component.py +38 -74
keylock_component.py
CHANGED
@@ -1,16 +1,18 @@
|
|
1 |
import gradio as gr
|
2 |
-
from PIL import Image, ImageDraw, ImageFont
|
3 |
-
import
|
|
|
|
|
|
|
4 |
import os
|
5 |
import struct
|
6 |
-
import json
|
7 |
-
import random
|
8 |
import tempfile
|
9 |
-
import
|
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 |
|
15 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
16 |
PREFERRED_FONTS = ["Arial", "Helvetica", "DejaVu Sans", "Verdana", "Calibri", "sans-serif"]
|
@@ -25,17 +27,10 @@ class AppServerLogic:
|
|
25 |
key_pem = os.environ.get('KEYLOCK_PRIV_KEY')
|
26 |
if not key_pem:
|
27 |
pk = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
28 |
-
key_pem = pk.private_bytes(
|
29 |
-
encoding=serialization.Encoding.PEM,
|
30 |
-
format=serialization.PrivateFormat.PKCS8,
|
31 |
-
encryption_algorithm=serialization.NoEncryption()
|
32 |
-
).decode('utf-8')
|
33 |
try:
|
34 |
self.private_key_object = serialization.load_pem_private_key(key_pem.encode(), password=None)
|
35 |
-
self.public_key_pem = self.private_key_object.public_key().public_bytes(
|
36 |
-
encoding=serialization.Encoding.PEM,
|
37 |
-
format=serialization.PublicFormat.SubjectPublicKeyInfo
|
38 |
-
).decode('utf-8')
|
39 |
except Exception as e:
|
40 |
logging.error(f"Key initialization failed: {e}")
|
41 |
|
@@ -53,15 +48,10 @@ class AppServerLogic:
|
|
53 |
crypto_payload = int(data_binary, 2).to_bytes(data_length, byteorder='big')
|
54 |
offset = 4
|
55 |
encrypted_aes_key_len = struct.unpack('>I', crypto_payload[:offset])[0]
|
56 |
-
encrypted_aes_key = crypto_payload[offset:offset + encrypted_aes_key_len]
|
57 |
-
offset +=
|
58 |
-
nonce = crypto_payload[offset:offset + 12]
|
59 |
-
offset += 12
|
60 |
ciphertext = crypto_payload[offset:]
|
61 |
-
recovered_aes_key = self.private_key_object.decrypt(
|
62 |
-
encrypted_aes_key,
|
63 |
-
padding.OAEP(mgf=padding.MGF1(hashes.SHA256()), algorithm=hashes.SHA256(), label=None)
|
64 |
-
)
|
65 |
payload = json.loads(AESGCM(recovered_aes_key).decrypt(nonce, ciphertext, None).decode())
|
66 |
return {"status": "Success", "payload": payload}
|
67 |
except Exception as e:
|
@@ -69,11 +59,11 @@ class AppServerLogic:
|
|
69 |
|
70 |
@staticmethod
|
71 |
def _get_font(preferred_fonts, base_size):
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
except IOError:
|
76 |
-
|
77 |
return ImageFont.load_default(size=base_size)
|
78 |
|
79 |
@staticmethod
|
@@ -91,7 +81,7 @@ class AppServerLogic:
|
|
91 |
for _ in range(int((w * h) / 200)):
|
92 |
x, y = random.randint(0, w - 1), random.randint(0, h - 1)
|
93 |
brightness = random.randint(30, 90)
|
94 |
-
draw.point((x, y), fill=(int(brightness
|
95 |
star_colors = [(255, 255, 255), (220, 230, 255), (255, 240, 220)]
|
96 |
for _ in range(int((w * h) / 1000)):
|
97 |
x, y = random.randint(0, w - 1), random.randint(0, h - 1)
|
@@ -125,15 +115,13 @@ class AppServerLogic:
|
|
125 |
public_key = serialization.load_pem_public_key(self.public_key_pem.encode('utf-8'))
|
126 |
aes_key, nonce = os.urandom(32), os.urandom(12)
|
127 |
ciphertext = AESGCM(aes_key).encrypt(nonce, json_bytes, None)
|
128 |
-
rsa_key = public_key.encrypt(
|
129 |
-
aes_key,
|
130 |
-
padding.OAEP(mgf=padding.MGF1(hashes.SHA256()), algorithm=hashes.SHA256(), label=None)
|
131 |
-
)
|
132 |
payload = struct.pack('>I', len(rsa_key)) + rsa_key + nonce + ciphertext
|
133 |
pixel_data = np.array(image_with_overlay).ravel()
|
134 |
binary_payload = ''.join(format(b, '08b') for b in struct.pack('>I', len(payload)) + payload)
|
135 |
pixel_data[:len(binary_payload)] = (pixel_data[:len(binary_payload)] & 0xFE) | np.array(list(binary_payload), dtype=np.uint8)
|
136 |
final_image = Image.fromarray(pixel_data.reshape(image_with_overlay.size[1], image_with_overlay.size[0], 3), 'RGB')
|
|
|
137 |
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as f:
|
138 |
final_image.save(f.name, "PNG")
|
139 |
return f.name, f.name
|
@@ -141,51 +129,40 @@ class AppServerLogic:
|
|
141 |
@staticmethod
|
142 |
def generate_pem_keys():
|
143 |
pk = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
144 |
-
priv = pk.private_bytes(
|
145 |
-
|
146 |
-
format=serialization.PrivateFormat.PKCS8,
|
147 |
-
encryption_algorithm=serialization.NoEncryption()
|
148 |
-
).decode()
|
149 |
-
pub = pk.public_key().public_bytes(
|
150 |
-
encoding=serialization.Encoding.PEM,
|
151 |
-
format=serialization.PublicFormat.SubjectPublicKeyInfo
|
152 |
-
).decode()
|
153 |
return priv, pub
|
154 |
|
155 |
class KeylockDecoderComponent(gr.components.Component):
|
156 |
EVENTS = ["change"]
|
157 |
|
158 |
-
def __init__(self, server_logic
|
159 |
-
self.server_logic = server_logic
|
160 |
-
self.value = None
|
161 |
super().__init__(value=self.value, **kwargs)
|
162 |
|
163 |
def _format_message(self, result: dict | None) -> str:
|
164 |
-
if not result or not result.get("status"):
|
165 |
-
return "Upload a KeyLock image to decode data."
|
166 |
status = result["status"]
|
167 |
if status == "Success":
|
168 |
-
|
|
|
169 |
else:
|
170 |
message = result.get("message", "An unknown error occurred.")
|
171 |
return f"<p style='color:red; font-weight:bold;'>❌ Error: {message}</p>"
|
172 |
|
173 |
-
def preprocess(self, payload):
|
174 |
-
|
175 |
-
|
176 |
-
def postprocess(self, value):
|
177 |
-
return value
|
178 |
-
|
179 |
-
def api_info(self):
|
180 |
-
return {"type": "object", "example": {"status": "Success", "payload": {"USER": "demo-user", "PASSWORD": "password123"}}}
|
181 |
|
182 |
def render(self):
|
183 |
value_state = gr.State(value=self.value)
|
|
|
184 |
with gr.Column():
|
185 |
image_input = gr.Image(label="KeyLock Image", type="pil", show_label=False)
|
186 |
status_display = gr.Markdown(self._format_message(self.value))
|
187 |
with gr.Accordion("Generate Encrypted Image", open=False):
|
188 |
-
payload_input = gr.JSON(label="Payload to Encrypt", value={"
|
189 |
generate_img_button = gr.Button("Generate Image", variant="secondary")
|
190 |
generated_image_preview = gr.Image(label="Generated Image Preview", type="filepath", interactive=False)
|
191 |
generated_file_download = gr.File(label="Download Uncorrupted PNG", interactive=False)
|
@@ -196,26 +173,13 @@ class KeylockDecoderComponent(gr.components.Component):
|
|
196 |
output_public_key = gr.Code(label="Generated Public Key", language="python")
|
197 |
|
198 |
def on_image_upload(image):
|
199 |
-
if image is None:
|
200 |
-
return None, "Upload a KeyLock image to decode data."
|
201 |
result_dict = self.server_logic.decode_payload(image)
|
202 |
-
self.value = result_dict # Update component value for change event
|
203 |
formatted_message = self._format_message(result_dict)
|
204 |
return result_dict, formatted_message
|
205 |
|
206 |
-
image_input.upload(
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
)
|
211 |
-
generate_img_button.click(
|
212 |
-
fn=self.server_logic.generate_encrypted_image,
|
213 |
-
inputs=[payload_input],
|
214 |
-
outputs=[generated_image_preview, generated_file_download]
|
215 |
-
)
|
216 |
-
generate_keys_button.click(
|
217 |
-
fn=self.server_logic.generate_pem_keys,
|
218 |
-
inputs=None,
|
219 |
-
outputs=[output_private_key, output_public_key]
|
220 |
-
)
|
221 |
return {"value": value_state}
|
|
|
1 |
import gradio as gr
|
2 |
+
from PIL import Image, ImageOps, ImageDraw, ImageFont
|
3 |
+
import requests
|
4 |
+
import io
|
5 |
+
import json
|
6 |
+
import logging
|
7 |
import os
|
8 |
import struct
|
|
|
|
|
9 |
import tempfile
|
10 |
+
import random
|
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 |
+
import numpy as np
|
16 |
|
17 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
18 |
PREFERRED_FONTS = ["Arial", "Helvetica", "DejaVu Sans", "Verdana", "Calibri", "sans-serif"]
|
|
|
27 |
key_pem = os.environ.get('KEYLOCK_PRIV_KEY')
|
28 |
if not key_pem:
|
29 |
pk = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
30 |
+
key_pem = pk.private_bytes(encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption()).decode('utf-8')
|
|
|
|
|
|
|
|
|
31 |
try:
|
32 |
self.private_key_object = serialization.load_pem_private_key(key_pem.encode(), password=None)
|
33 |
+
self.public_key_pem = self.private_key_object.public_key().public_bytes(encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo).decode('utf-8')
|
|
|
|
|
|
|
34 |
except Exception as e:
|
35 |
logging.error(f"Key initialization failed: {e}")
|
36 |
|
|
|
48 |
crypto_payload = int(data_binary, 2).to_bytes(data_length, byteorder='big')
|
49 |
offset = 4
|
50 |
encrypted_aes_key_len = struct.unpack('>I', crypto_payload[:offset])[0]
|
51 |
+
encrypted_aes_key = crypto_payload[offset:offset + encrypted_aes_key_len]; offset += encrypted_aes_key_len
|
52 |
+
nonce = crypto_payload[offset:offset + 12]; offset += 12
|
|
|
|
|
53 |
ciphertext = crypto_payload[offset:]
|
54 |
+
recovered_aes_key = self.private_key_object.decrypt(encrypted_aes_key, padding.OAEP(mgf=padding.MGF1(hashes.SHA256()), algorithm=hashes.SHA256(), label=None))
|
|
|
|
|
|
|
55 |
payload = json.loads(AESGCM(recovered_aes_key).decrypt(nonce, ciphertext, None).decode())
|
56 |
return {"status": "Success", "payload": payload}
|
57 |
except Exception as e:
|
|
|
59 |
|
60 |
@staticmethod
|
61 |
def _get_font(preferred_fonts, base_size):
|
62 |
+
fp = None
|
63 |
+
for n in preferred_fonts:
|
64 |
+
try: ImageFont.truetype(n.lower()+".ttf", 10); fp = n.lower()+".ttf"; break
|
65 |
+
except IOError: continue
|
66 |
+
if fp: return ImageFont.truetype(fp, base_size)
|
67 |
return ImageFont.load_default(size=base_size)
|
68 |
|
69 |
@staticmethod
|
|
|
81 |
for _ in range(int((w * h) / 200)):
|
82 |
x, y = random.randint(0, w - 1), random.randint(0, h - 1)
|
83 |
brightness = random.randint(30, 90)
|
84 |
+
draw.point((x, y), fill=(int(brightness*0.9), int(brightness*0.9), brightness))
|
85 |
star_colors = [(255, 255, 255), (220, 230, 255), (255, 240, 220)]
|
86 |
for _ in range(int((w * h) / 1000)):
|
87 |
x, y = random.randint(0, w - 1), random.randint(0, h - 1)
|
|
|
115 |
public_key = serialization.load_pem_public_key(self.public_key_pem.encode('utf-8'))
|
116 |
aes_key, nonce = os.urandom(32), os.urandom(12)
|
117 |
ciphertext = AESGCM(aes_key).encrypt(nonce, json_bytes, None)
|
118 |
+
rsa_key = public_key.encrypt(aes_key, padding.OAEP(mgf=padding.MGF1(hashes.SHA256()), algorithm=hashes.SHA256(), label=None))
|
|
|
|
|
|
|
119 |
payload = struct.pack('>I', len(rsa_key)) + rsa_key + nonce + ciphertext
|
120 |
pixel_data = np.array(image_with_overlay).ravel()
|
121 |
binary_payload = ''.join(format(b, '08b') for b in struct.pack('>I', len(payload)) + payload)
|
122 |
pixel_data[:len(binary_payload)] = (pixel_data[:len(binary_payload)] & 0xFE) | np.array(list(binary_payload), dtype=np.uint8)
|
123 |
final_image = Image.fromarray(pixel_data.reshape(image_with_overlay.size[1], image_with_overlay.size[0], 3), 'RGB')
|
124 |
+
|
125 |
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as f:
|
126 |
final_image.save(f.name, "PNG")
|
127 |
return f.name, f.name
|
|
|
129 |
@staticmethod
|
130 |
def generate_pem_keys():
|
131 |
pk = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
132 |
+
priv = pk.private_bytes(encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption()).decode()
|
133 |
+
pub = pk.public_key().public_bytes(encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo).decode()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
134 |
return priv, pub
|
135 |
|
136 |
class KeylockDecoderComponent(gr.components.Component):
|
137 |
EVENTS = ["change"]
|
138 |
|
139 |
+
def __init__(self, server_logic, **kwargs):
|
140 |
+
self.server_logic = server_logic
|
141 |
+
self.value = None
|
142 |
super().__init__(value=self.value, **kwargs)
|
143 |
|
144 |
def _format_message(self, result: dict | None) -> str:
|
145 |
+
if not result or not result.get("status"): return "Upload a KeyLock image to auto-fill credentials."
|
|
|
146 |
status = result["status"]
|
147 |
if status == "Success":
|
148 |
+
user = result.get("payload", {}).get("USER", "N/A")
|
149 |
+
return f"<p style='color:green; font-weight:bold;'>✅ Success! Decoded credentials for '{user}'.</p>"
|
150 |
else:
|
151 |
message = result.get("message", "An unknown error occurred.")
|
152 |
return f"<p style='color:red; font-weight:bold;'>❌ Error: {message}</p>"
|
153 |
|
154 |
+
def preprocess(self, payload): return payload
|
155 |
+
def postprocess(self, value): return value
|
156 |
+
def api_info(self): return {"type": "object", "example": {"status": "Success", "payload": {"USER": "demo-user"}}}
|
|
|
|
|
|
|
|
|
|
|
157 |
|
158 |
def render(self):
|
159 |
value_state = gr.State(value=self.value)
|
160 |
+
|
161 |
with gr.Column():
|
162 |
image_input = gr.Image(label="KeyLock Image", type="pil", show_label=False)
|
163 |
status_display = gr.Markdown(self._format_message(self.value))
|
164 |
with gr.Accordion("Generate Encrypted Image", open=False):
|
165 |
+
payload_input = gr.JSON(label="Payload to Encrypt", value={"API_KEY": "sk-12345-abcde", "USER": "demo-user"})
|
166 |
generate_img_button = gr.Button("Generate Image", variant="secondary")
|
167 |
generated_image_preview = gr.Image(label="Generated Image Preview", type="filepath", interactive=False)
|
168 |
generated_file_download = gr.File(label="Download Uncorrupted PNG", interactive=False)
|
|
|
173 |
output_public_key = gr.Code(label="Generated Public Key", language="python")
|
174 |
|
175 |
def on_image_upload(image):
|
176 |
+
if image is None: return None, "Upload a KeyLock image to auto-fill credentials."
|
|
|
177 |
result_dict = self.server_logic.decode_payload(image)
|
|
|
178 |
formatted_message = self._format_message(result_dict)
|
179 |
return result_dict, formatted_message
|
180 |
|
181 |
+
image_input.upload(fn=on_image_upload, inputs=[image_input], outputs=[value_state, status_display])
|
182 |
+
generate_img_button.click(fn=self.server_logic.generate_encrypted_image, inputs=[payload_input], outputs=[generated_image_preview, generated_file_download])
|
183 |
+
generate_keys_button.click(fn=self.server_logic.generate_pem_keys, inputs=None, outputs=[output_private_key, output_public_key])
|
184 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
185 |
return {"value": value_state}
|