-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
88 lines (64 loc) · 2.74 KB
/
server.py
File metadata and controls
88 lines (64 loc) · 2.74 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
from flask import Flask, request, jsonify
app = Flask(__name__)
from rcncipher import encrypt, decrypt
def text_to_128_bit_hex_chunks(text):
# Convert text to bytes
text_bytes = text.encode('utf-8')
# Calculate the number of 128-bit chunks
num_chunks = (len(text_bytes) + 15) // 16
# Pad the text_bytes to make its length a multiple of 16 bytes
padded_bytes = text_bytes.ljust(num_chunks * 16, b'\0')
# Divide the padded bytes into 128-bit chunks
chunks = [padded_bytes[i:i+16] for i in range(0, len(padded_bytes), 16)]
# Convert each chunk to hexadecimal representation
hex_chunks = [chunk.hex() for chunk in chunks]
# print(hex_chunks)
return hex_chunks
def text_to_hex(text):
# Convert text to bytes
text_bytes = text.encode('utf-8')
# Convert bytes to hexadecimal representation
hex_representation = text_bytes.hex()
return hex_representation
def hex_to_text(hex_string):
# Convert hexadecimal string to bytes
byte_string = bytes.fromhex(hex_string)
# Decode bytes to text using UTF-8 encoding
text = byte_string.decode('utf-8')
return text
#allow cors
@app.after_request
def after_request(response):
response.headers.add('Access-Control-Allow-Origin', '*')
response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE')
return response
@app.route('/encrypt', methods=['POST'])
def encrypt_endpoint():
data = request.get_json()
text = data.get('text')
key = data.get('key')
key = text_to_hex(key)
if text is None or key is None:
return jsonify({'error': 'Text and key are required.'}), 400
chunks = text_to_128_bit_hex_chunks(text)
# Encrypt each 128-bit chunk
ciphertext = ''.join(encrypt(chunk, key) for chunk in chunks)
# print("Ciphertext:", ciphertext)
# encrypted_text = encrypt(text, key)
return jsonify({'encrypted_text': ciphertext}), 200
@app.route('/decrypt', methods=['POST'])
def decrypt_endpoint():
data = request.get_json()
encrypted_text = data.get('encrypted_text')
key = data.get('key')
key = text_to_hex(key)
if encrypted_text is None or key is None:
return jsonify({'error': 'Encrypted text and key are required.'}), 400
print(encrypted_text, key)
decrypted_chunks = [hex_to_text(decrypt(encrypted_text[i:i+32], key)) for i in range(0, len(encrypted_text), 32)]
decrypted_text = ''.join(decrypted_chunks)
# decrypted_text = decrypt(encrypted_text, key)
return jsonify({'decrypted_text': decrypted_text}), 200
if __name__ == '__main__':
app.run(debug=True)