-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
189 lines (157 loc) · 5.24 KB
/
Copy pathserver.py
File metadata and controls
189 lines (157 loc) · 5.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
import base64
import math
import time
from random import randrange, getrandbits
import cv2
import numpy as np
from flask import Flask, request, jsonify, send_from_directory
app = Flask(__name__)
# =====================================================
# RSA UTILITIES (1024-bit RSA: 512 + 512)
# =====================================================
def power(a, d, n):
result = 1
a %= n
while d > 0:
if d & 1:
result = (result * a) % n
a = (a * a) % n
d >>= 1
return result
def miller_rabin_test(n, d):
a = randrange(2, n - 2)
x = power(a, d, n)
if x == 1 or x == n - 1:
return True
while d != n - 1:
x = (x * x) % n
d <<= 1
if x == 1:
return False
if x == n - 1:
return True
return False
def is_prime(n, k=16):
if n in (2, 3):
return True
if n <= 1 or n % 2 == 0:
return False
d = n - 1
while d % 2 == 0:
d //= 2
for _ in range(k):
if not miller_rabin_test(n, d):
return False
return True
def generate_prime(bits):
while True:
p = getrandbits(bits)
# ensure p is odd and has the top bit set (correct bit-length)
p |= (1 << (bits - 1)) | 1
if is_prime(p):
return p
def egcd(a, b):
if a == 0:
return b, 0, 1
g, y, x = egcd(b % a, a)
return g, x - (b // a) * y, y
def mod_inverse(e, phi):
g, x, _ = egcd(e, phi)
if g != 1:
raise ValueError("No modular inverse")
return x % phi
def generate_rsa_keypair(bits_per_prime=128):
# 128 + 128 ≈ 256-bit modulus (very fast, ONLY for demo)
while True:
P = generate_prime(bits_per_prime)
Q = generate_prime(bits_per_prime)
if P == Q:
continue
N = P * Q
phi = (P - 1) * (Q - 1)
E = 65537
if math.gcd(E, phi) != 1:
continue
D = mod_inverse(E, phi)
return N, E, D
print("Generating demo RSA keys (~256-bit)...")
N, E, D = generate_rsa_keypair(bits_per_prime=128)
print("RSA-256 Ready")
print("N bits =", N.bit_length())
frame_counter = 0
# =====================================================
# FLASK ROUTES
# =====================================================
@app.route("/")
def index():
# Serve index.html from the SAME folder as app.py
return send_from_directory(app.root_path, "ras_ui.html")
@app.route("/rsa-info")
def rsa_info():
return jsonify({
"N": str(N),
"E": str(E),
"bits": N.bit_length()
})
@app.route("/encrypt", methods=["POST"])
def encrypt_endpoint():
global frame_counter
data = request.get_json()
if not data or "image" not in data:
return jsonify({"error": "No image provided"}), 400
data_url = data["image"]
try:
_, encoded = data_url.split(",", 1)
except ValueError:
return jsonify({"error": "Invalid data URL"}), 400
try:
img_bytes = base64.b64decode(encoded)
nparr = np.frombuffer(img_bytes, np.uint8)
frame = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
if frame is None:
raise ValueError("cv2.imdecode failed")
except Exception as e:
return jsonify({"error": f"Failed to decode image: {e}"}), 400
# Downscale & convert to grayscale for RSA
small = cv2.resize(frame, (80, 60), interpolation=cv2.INTER_AREA)
gray = cv2.cvtColor(small, cv2.COLOR_BGR2GRAY)
flat = gray.flatten()
pixel_count = int(flat.size)
# RSA ENCRYPT
t0 = time.perf_counter()
encrypted_flat = np.array([pow(int(v), E, N) for v in flat], dtype=object)
enc_time_ms = (time.perf_counter() - t0) * 1000.0
# Visualize ciphertext (mod 256)
display_flat = np.array([int(c % 256) for c in encrypted_flat], dtype=np.uint8)
enc_display_small = display_flat.reshape(gray.shape)
# RSA DECRYPT
t1 = time.perf_counter()
decrypted_flat = np.array([pow(int(c), D, N) for c in encrypted_flat], dtype=np.uint8)
dec_time_ms = (time.perf_counter() - t1) * 1000.0
dec_small = decrypted_flat.reshape(gray.shape)
# correctness check
decryption_ok = bool(np.array_equal(dec_small, gray))
# Upscale encrypted and decrypted to original size
enc_up = cv2.resize(enc_display_small, (frame.shape[1], frame.shape[0]),
interpolation=cv2.INTER_NEAREST)
dec_up = cv2.resize(dec_small, (frame.shape[1], frame.shape[0]),
interpolation=cv2.INTER_NEAREST)
ok1, enc_buf = cv2.imencode(".png", enc_up)
ok2, dec_buf = cv2.imencode(".png", dec_up)
if not ok1 or not ok2:
return jsonify({"error": "Failed to encode images"}), 500
enc_b64 = base64.b64encode(enc_buf).decode("ascii")
dec_b64 = base64.b64encode(dec_buf).decode("ascii")
frame_counter += 1
return jsonify({
"encrypted_image": "data:image/png;base64," + enc_b64,
"decrypted_image": "data:image/png;base64," + dec_b64,
"frame_count": frame_counter,
"rsa_time_ms": round(enc_time_ms, 3),
"rsa_decrypt_time_ms": round(dec_time_ms, 3),
"decryption_ok": decryption_ok,
"pixel_count": pixel_count
})
if __name__ == "__main__":
# Port 5500 as you requested
app.run(host="127.0.0.1", port=5500, debug=True)