-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
261 lines (211 loc) · 7.68 KB
/
app.py
File metadata and controls
261 lines (211 loc) · 7.68 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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
"""
SecureText: A Web-Based Text Encryption and Decryption App
CS166 - Information Security, Fall 2025
Team 8: Jaspreet Aujla, Akanksha Raghapur, Ryan Shim
"""
from flask import Flask, render_template, request, jsonify
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from Crypto.Random import get_random_bytes
import base64
import time
app = Flask(__name__)
# ============== CAESAR CIPHER ==============
def caesar_encrypt(plaintext, shift):
"""Encrypt using Caesar cipher with given shift value."""
result = []
shift = int(shift) % 26
for char in plaintext:
if char.isalpha():
base = ord('A') if char.isupper() else ord('a')
result.append(chr((ord(char) - base + shift) % 26 + base))
else:
result.append(char)
return ''.join(result)
def caesar_decrypt(ciphertext, shift):
"""Decrypt Caesar cipher by shifting in opposite direction."""
return caesar_encrypt(ciphertext, -int(shift))
# ============== VIGENÈRE CIPHER ==============
def vigenere_encrypt(plaintext, key):
"""Encrypt using Vigenère cipher with given keyword."""
if not key:
return plaintext
result = []
key = key.upper()
key_index = 0
for char in plaintext:
if char.isalpha():
shift = ord(key[key_index % len(key)]) - ord('A')
base = ord('A') if char.isupper() else ord('a')
result.append(chr((ord(char) - base + shift) % 26 + base))
key_index += 1
else:
result.append(char)
return ''.join(result)
def vigenere_decrypt(ciphertext, key):
"""Decrypt Vigenère cipher."""
if not key:
return ciphertext
result = []
key = key.upper()
key_index = 0
for char in ciphertext:
if char.isalpha():
shift = ord(key[key_index % len(key)]) - ord('A')
base = ord('A') if char.isupper() else ord('a')
result.append(chr((ord(char) - base - shift) % 26 + base))
key_index += 1
else:
result.append(char)
return ''.join(result)
# ============== AES CIPHER ==============
def aes_encrypt(plaintext, key):
"""Encrypt using AES-256 in CBC mode."""
# Ensure key is 32 bytes (256 bits) by padding or hashing
key_bytes = key.encode('utf-8')
key_bytes = key_bytes.ljust(32, b'\0')[:32]
iv = get_random_bytes(16)
cipher = AES.new(key_bytes, AES.MODE_CBC, iv)
plaintext_bytes = plaintext.encode('utf-8')
padded_data = pad(plaintext_bytes, AES.block_size)
ciphertext = cipher.encrypt(padded_data)
# Return IV + ciphertext as base64
return base64.b64encode(iv + ciphertext).decode('utf-8')
def aes_decrypt(ciphertext, key):
"""Decrypt AES-256 in CBC mode."""
try:
key_bytes = key.encode('utf-8')
key_bytes = key_bytes.ljust(32, b'\0')[:32]
encrypted_data = base64.b64decode(ciphertext)
iv = encrypted_data[:16]
actual_ciphertext = encrypted_data[16:]
cipher = AES.new(key_bytes, AES.MODE_CBC, iv)
decrypted_padded = cipher.decrypt(actual_ciphertext)
decrypted = unpad(decrypted_padded, AES.block_size)
return decrypted.decode('utf-8')
except Exception as e:
return f"Decryption Error: {str(e)}"
# ============== ROUTES ==============
@app.route('/')
def index():
return render_template('index.html')
@app.route('/encrypt', methods=['POST'])
def encrypt():
data = request.json
plaintext = data.get('plaintext', '')
algorithm = data.get('algorithm', 'caesar')
key = data.get('key', '')
start_time = time.perf_counter()
if algorithm == 'caesar':
try:
shift = int(key) if key else 3
except ValueError:
shift = 3
ciphertext = caesar_encrypt(plaintext, shift)
key_info = f"Shift: {shift}"
security_level = "Very Low"
key_space = "26 possible keys"
elif algorithm == 'vigenere':
if not key:
key = "KEY"
ciphertext = vigenere_encrypt(plaintext, key)
key_info = f"Keyword: {key}"
security_level = "Low"
key_space = f"26^{len(key)} = {26**len(key):,} possible keys"
elif algorithm == 'aes':
if not key:
key = "defaultkey123456"
ciphertext = aes_encrypt(plaintext, key)
key_info = f"Key length: {len(key)} chars (padded to 256 bits)"
security_level = "High"
key_space = "2^256 possible keys"
else:
return jsonify({'error': 'Unknown algorithm'}), 400
end_time = time.perf_counter()
execution_time = (end_time - start_time) * 1000 # Convert to milliseconds
return jsonify({
'ciphertext': ciphertext,
'algorithm': algorithm,
'key_info': key_info,
'security_level': security_level,
'key_space': key_space,
'execution_time': f"{execution_time:.4f} ms"
})
@app.route('/decrypt', methods=['POST'])
def decrypt():
data = request.json
ciphertext = data.get('ciphertext', '')
algorithm = data.get('algorithm', 'caesar')
key = data.get('key', '')
start_time = time.perf_counter()
if algorithm == 'caesar':
try:
shift = int(key) if key else 3
except ValueError:
shift = 3
plaintext = caesar_decrypt(ciphertext, shift)
elif algorithm == 'vigenere':
if not key:
key = "KEY"
plaintext = vigenere_decrypt(ciphertext, key)
elif algorithm == 'aes':
if not key:
key = "defaultkey123456"
plaintext = aes_decrypt(ciphertext, key)
else:
return jsonify({'error': 'Unknown algorithm'}), 400
end_time = time.perf_counter()
execution_time = (end_time - start_time) * 1000
return jsonify({
'plaintext': plaintext,
'algorithm': algorithm,
'execution_time': f"{execution_time:.4f} ms"
})
@app.route('/compare', methods=['POST'])
def compare():
"""Compare all algorithms side by side."""
data = request.json
plaintext = data.get('plaintext', '')
results = []
# Caesar (shift 3)
start = time.perf_counter()
caesar_ct = caesar_encrypt(plaintext, 3)
caesar_time = (time.perf_counter() - start) * 1000
results.append({
'algorithm': 'Caesar Cipher',
'ciphertext': caesar_ct,
'time': f"{caesar_time:.4f} ms",
'key_size': '5 bits (26 keys)',
'security': 'Very Low',
'vulnerability': 'Easily broken by frequency analysis or brute force'
})
# Vigenère (key "SECRET")
start = time.perf_counter()
vigenere_ct = vigenere_encrypt(plaintext, "SECRET")
vigenere_time = (time.perf_counter() - start) * 1000
results.append({
'algorithm': 'Vigenère Cipher',
'ciphertext': vigenere_ct,
'time': f"{vigenere_time:.4f} ms",
'key_size': 'Variable (depends on keyword)',
'security': 'Low',
'vulnerability': 'Vulnerable to Kasiski examination and frequency analysis'
})
# AES-256
start = time.perf_counter()
aes_ct = aes_encrypt(plaintext, "comparekey123456")
aes_time = (time.perf_counter() - start) * 1000
results.append({
'algorithm': 'AES-256',
'ciphertext': aes_ct,
'time': f"{aes_time:.4f} ms",
'key_size': '256 bits',
'security': 'High',
'vulnerability': 'No practical attacks known; considered secure'
})
return jsonify({'results': results})
if __name__ == '__main__':
import os
debug = os.environ.get('FLASK_DEBUG', 'False').lower() == 'true'
port = int(os.environ.get('PORT', 5001))
app.run(debug=debug, host='0.0.0.0', port=port)