-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.py
More file actions
164 lines (130 loc) · 5.87 KB
/
server.py
File metadata and controls
164 lines (130 loc) · 5.87 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
# this is the flask server that runs the whole app
# basically it takes the html frontend and connects it to the python steganography stuff
# i chose flask because it's super simple and i already knew it from a tutorial lol
import os
import sys
import base64
import tempfile
import threading
import webbrowser
from io import BytesIO
from pathlib import Path
try:
from flask import Flask, request, jsonify, send_from_directory
except ImportError:
print("[✗] Flask not installed. Run: pip install flask")
sys.exit(1)
try:
from PIL import Image
except ImportError:
print("[✗] Pillow not installed. Run: pip install Pillow")
sys.exit(1)
from steganography import encode_message, decode_message, image_capacity
# figure out where this file lives so we can serve index.html from the same folder
BASE_DIR = Path(__file__).parent
app = Flask(__name__, static_folder=str(BASE_DIR), static_url_path="")
# serves the main page - literally just sends index.html
@app.route("/")
def index():
return send_from_directory(BASE_DIR, "index.html")
# this endpoint takes an image and returns info about it
# like how big it is, dimensions, and how many chars we can hide in it
# also sends back a base64 thumbnail so the frontend can show a preview
@app.route("/api/info", methods=["POST"])
def api_info():
if "image" not in request.files:
return jsonify({"success": False, "message": "No image provided"}), 400
file = request.files["image"]
# save to a temp file so we can open it with pillow
with tempfile.NamedTemporaryFile(delete=False, suffix=".png") as tmp:
file.save(tmp.name)
tmp_path = tmp.name
try:
result = image_capacity(tmp_path)
# make a small preview thumbnail and encode it as base64
# the frontend just sticks this straight into an <img> tag, pretty clean
img = Image.open(tmp_path).convert("RGB")
img.thumbnail((400, 300))
buf = BytesIO()
img.save(buf, format="JPEG", quality=80)
preview_b64 = base64.b64encode(buf.getvalue()).decode()
result["preview"] = f"data:image/jpeg;base64,{preview_b64}"
result["filename"] = file.filename
return jsonify(result)
finally:
os.unlink(tmp_path) # always clean up temp files, don't want junk piling up
# the main encode endpoint - takes an image + message + optional password
# hides the message in the image and sends the new image back as base64
@app.route("/api/encode", methods=["POST"])
def api_encode():
if "image" not in request.files:
return jsonify({"success": False, "message": "No image provided"}), 400
file = request.files["image"]
message = request.form.get("message", "")
password = request.form.get("password", "")
if not message.strip():
return jsonify({"success": False, "message": "Message cannot be empty"}), 400
# save the uploaded image to a temp file
suffix = Path(file.filename).suffix or ".png"
with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp_in:
file.save(tmp_in.name)
in_path = tmp_in.name
out_path = in_path + "_stego.png" # output goes right next to the input
try:
result = encode_message(in_path, message, out_path, password)
if result["success"]:
# read the stego image back and convert to base64 so browser can download it
# (browsers can't just read files off the server's filesystem obviously)
with open(out_path, "rb") as f:
stego_b64 = base64.b64encode(f.read()).decode()
# also make a preview thumbnail like in the info endpoint
img = Image.open(out_path).convert("RGB")
img.thumbnail((400, 300))
buf = BytesIO()
img.save(buf, format="JPEG", quality=80)
preview_b64 = base64.b64encode(buf.getvalue()).decode()
stem = Path(file.filename).stem
result["stego_image"] = f"data:image/png;base64,{stego_b64}"
result["preview"] = f"data:image/jpeg;base64,{preview_b64}"
result["filename"] = f"{stem}_stego.png" # name the download nicely
return jsonify(result)
finally:
# clean up both temp files no matter what happens
os.unlink(in_path)
if os.path.exists(out_path):
os.unlink(out_path)
# decode endpoint - takes a stego image and digs the hidden message out
# sends the message back as plain text in the json response
@app.route("/api/decode", methods=["POST"])
def api_decode():
if "image" not in request.files:
return jsonify({"success": False, "message": "No image provided"}), 400
file = request.files["image"]
password = request.form.get("password", "")
suffix = Path(file.filename).suffix or ".png"
with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
file.save(tmp.name)
tmp_path = tmp.name
try:
result = decode_message(tmp_path, password)
# still send a preview even on decode so the user sees the image they uploaded
img = Image.open(tmp_path).convert("RGB")
img.thumbnail((400, 300))
buf = BytesIO()
img.save(buf, format="JPEG", quality=80)
result["preview"] = f"data:image/jpeg;base64,{base64.b64encode(buf.getvalue()).decode()}"
result["filename"] = file.filename
return jsonify(result)
finally:
os.unlink(tmp_path) # cleanup!
# opens the browser automatically so the user doesn't have to copy paste the url
def open_browser():
webbrowser.open("http://127.0.0.1:5050")
if __name__ == "__main__":
print("\n" + "═" * 55)
print(" 🔐 StegoCrypt Server")
print(" → Open: http://127.0.0.1:5050")
print(" → Stop: Ctrl + C")
print("═" * 55 + "\n")
threading.Timer(1.2, open_browser).start() # small delay so the server starts first
app.run(host="127.0.0.1", port=5050, debug=False)