-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
240 lines (211 loc) · 8.75 KB
/
server.py
File metadata and controls
240 lines (211 loc) · 8.75 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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
import asyncio
import os
import json
import base64
import time
from aiohttp import web
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.backends import default_backend
def generate_rsa_key_pair():
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
backend=default_backend()
)
public_key = private_key.public_key()
return private_key, public_key
def save_key_to_file(key, filename, is_private=True):
if is_private:
pem = key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption()
)
else:
pem = key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
)
with open(filename, 'wb') as f:
f.write(pem)
def load_key_from_file(filename, is_private=True):
with open(filename, 'rb') as f:
pem = f.read()
if is_private:
return serialization.load_pem_private_key(pem, password=None, backend=default_backend())
return serialization.load_pem_public_key(pem, backend=default_backend())
def calculate_file_hash(file_data):
sha256 = hashes.Hash(hashes.SHA256(), backend=default_backend())
sha256.update(file_data)
return sha256.finalize()
def encrypt_file(file_data, key=None):
if key is None:
key = os.urandom(32)
nonce = os.urandom(12)
aesgcm = AESGCM(key)
ciphertext = aesgcm.encrypt(nonce, file_data, None)
return nonce, ciphertext, key
def sign_metadata(metadata, private_key):
signature = private_key.sign(
json.dumps(metadata).encode('utf-8'),
padding.PSS(
mgf=padding.MGF1(hashes.SHA512()),
salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA512()
)
return signature
async def handle_upload(request):
try:
reader = await request.multipart()
file_field = await reader.next()
if not file_field or file_field.filename != 'podcast.mp3':
return web.Response(text="Error: Please upload a file named podcast.mp3", status=400)
file_data = b""
while True:
chunk = await file_field.read_chunk(65536)
if not chunk:
break
file_data += chunk
storage_dir = 'cloud_storage'
os.makedirs(storage_dir, exist_ok=True)
private_key_path = os.path.join(storage_dir, 'private_key.pem')
public_key_path = os.path.join(storage_dir, 'public_key.pem')
if not os.path.exists(private_key_path) or not os.path.exists(public_key_path):
private_key, public_key = generate_rsa_key_pair()
save_key_to_file(private_key, private_key_path)
save_key_to_file(public_key, public_key_path, is_private=False)
else:
private_key = load_key_from_file(private_key_path)
nonce, ciphertext, key = encrypt_file(file_data)
file_hash = calculate_file_hash(file_data)
metadata = {
'file_name': file_field.filename,
'file_hash': base64.b64encode(file_hash).decode('utf-8'),
'nonce': base64.b64encode(nonce).decode('utf-8'),
'key': base64.b64encode(key).decode('utf-8'),
'timestamp': time.time()
}
signature = sign_metadata(metadata, private_key)
file_path = os.path.join(storage_dir, 'podcast_encrypted.bin')
metadata_path = os.path.join(storage_dir, 'metadata.json')
with open(file_path, 'wb') as f:
f.write(nonce + ciphertext)
with open(metadata_path, 'w') as f:
json.dump({'metadata': metadata, 'signature': base64.b64encode(signature).decode('utf-8')}, f)
history_path = os.path.join(storage_dir, 'upload_history.json')
history = []
if os.path.exists(history_path):
with open(history_path, 'r') as f:
history = json.load(f)
history.append({'file': file_field.filename, 'timestamp': metadata['timestamp']})
with open(history_path, 'w') as f:
json.dump(history, f)
response = {
'status': 'success',
'metadata': metadata,
'signature': base64.b64encode(signature).decode('utf-8')
}
return web.json_response(response)
except Exception as e:
print(f"Server error: {str(e)}")
return web.json_response({'status': 'error', 'message': str(e)}, status=500)
async def handle_download(request):
try:
storage_dir = 'cloud_storage'
metadata_path = os.path.join(storage_dir, 'metadata.json')
file_path = os.path.join(storage_dir, 'podcast_encrypted.bin')
public_key = load_key_from_file(os.path.join(storage_dir, 'public_key.pem'), is_private=False)
with open(metadata_path, 'r') as f:
data = json.load(f)
metadata = data['metadata']
signature = base64.b64decode(data['signature'])
public_key.verify(
signature,
json.dumps(metadata).encode('utf-8'),
padding.PSS(
mgf=padding.MGF1(hashes.SHA512()),
salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA512()
)
key = base64.b64decode(metadata['key'])
nonce = base64.b64decode(metadata['nonce'])
aesgcm = AESGCM(key)
with open(file_path, 'rb') as f:
ciphertext = f.read()
plaintext = aesgcm.decrypt(nonce, ciphertext[12:], None)
decrypted_hash = calculate_file_hash(plaintext)
original_hash = base64.b64decode(metadata['file_hash'])
if decrypted_hash != original_hash:
return web.Response(text="File integrity check failed", status=400)
response = web.StreamResponse(
status=200,
reason='OK',
headers={'Content-Type': 'audio/mpeg', 'Content-Disposition': 'inline; filename="podcast.mp3"'}
)
await response.prepare(request)
chunk_size = 65536
for i in range(0, len(plaintext), chunk_size):
await response.write(plaintext[i:i+chunk_size])
await response.write_eof()
return response
except Exception as e:
print(f"Download error: {str(e)}")
return web.Response(text=f"Download failed: {str(e)}", status=500)
async def handle_verify(request):
try:
storage_dir = 'cloud_storage'
metadata_path = os.path.join(storage_dir, 'metadata.json')
file_path = os.path.join(storage_dir, 'podcast_encrypted.bin')
public_key = load_key_from_file(os.path.join(storage_dir, 'public_key.pem'), is_private=False)
# Load metadata
with open(metadata_path, 'r') as f:
data = json.load(f)
metadata = data['metadata']
signature = base64.b64decode(data['signature'])
# Verify signature
public_key.verify(
signature,
json.dumps(metadata).encode('utf-8'),
padding.PSS(
mgf=padding.MGF1(hashes.SHA512()),
salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA512()
)
key = base64.b64decode(metadata['key'])
nonce = base64.b64decode(metadata['nonce'])
aesgcm = AESGCM(key)
with open(file_path, 'rb') as f:
ciphertext = f.read()
plaintext = aesgcm.decrypt(nonce, ciphertext[12:], None)
decrypted_hash = calculate_file_hash(plaintext)
original_hash = base64.b64decode(metadata['file_hash'])
if decrypted_hash != original_hash:
return web.Response(text="File integrity check failed", status=400)
return web.Response(text="File integrity check passed")
except Exception as e:
print(f"Verify error: {str(e)}")
return web.Response(text=f"Verification failed: {str(e)}", status=500)
async def handle_history(request):
try:
storage_dir = 'cloud_storage'
history_path = os.path.join(storage_dir, 'upload_history.json')
history = []
if os.path.exists(history_path):
with open(history_path, 'r') as f:
history = json.load(f)
return web.json_response({'files': history})
except Exception as e:
print(f"History error: {str(e)}")
return web.json_response({'error': str(e)}, status=500)
app = web.Application()
app.router.add_post('/upload', handle_upload)
app.router.add_get('/download', handle_download)
app.router.add_get('/verify', handle_verify)
app.router.add_get('/history', handle_history)
if __name__ == '__main__':
web.run_app(app, host='localhost', port=8888)