raviix46 commited on
Commit
db13c8b
·
verified ·
1 Parent(s): c78fcb8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +85 -36
app.py CHANGED
@@ -6,8 +6,12 @@ from qiskit_aer import Aer
6
  from cryptography.fernet import Fernet
7
  import random
8
  import base64
 
 
 
 
9
 
10
- # 1. Quantum Key Distribution (BB84 Protocol)
11
  def generate_qkd_key(length=128):
12
  shared_key = ""
13
  while len(shared_key) < length:
@@ -18,49 +22,56 @@ def generate_qkd_key(length=128):
18
  shared_key += str(alice_bit)
19
  return shared_key
20
 
21
- # 2. Convert QKD binary key to 32-byte Fernet-compatible key
22
  def bb84_to_fernet_key(qkey_binary_str):
23
  if len(qkey_binary_str) < 256:
24
  raise ValueError("QKD key must be at least 256 bits to generate Fernet key.")
25
-
26
  binary_256 = qkey_binary_str[:256]
27
  int_val = int(binary_256, 2)
28
- byte_val = int_val.to_bytes(32, 'big') # 256 bits = 32 bytes
29
  fernet_key = base64.urlsafe_b64encode(byte_val)
30
-
31
  if len(fernet_key) != 44:
32
- raise ValueError("Generated Fernet key is not 32 url-safe base64-encoded bytes")
33
-
34
  return fernet_key
35
 
36
- # 3. Encrypt message using QKD key
37
  def quantum_encrypt(message, qkd_key):
38
  if not qkd_key or len(qkd_key) < 72:
39
- return "❌ QKD key too short. Minimum usable bits: 72", ""
40
-
41
  try:
42
  fernet_key = bb84_to_fernet_key(qkd_key)
43
  f = Fernet(fernet_key)
44
  encrypted_message = f.encrypt(message.encode())
45
- return encrypted_message.decode(), fernet_key.decode()
 
46
  except Exception as e:
47
- return f"Encryption error: {str(e)}", ""
48
 
49
- # 4. Decrypt message using QKD key
50
  def quantum_decrypt(encrypted_message, key):
51
  try:
52
  f = Fernet(key.encode())
53
- decrypted_message = f.decrypt(encrypted_message.encode())
54
- return decrypted_message.decode()
55
  except Exception as e:
56
  return f"Decryption error: {str(e)}"
57
 
58
- # 5. Quantum Intrusion Detection using PennyLane
 
 
 
 
 
 
 
 
 
 
 
59
  def quantum_intrusion_detection(data_stream):
60
  dev = qml.device("default.qubit", wires=2)
61
 
62
  @qml.qnode(dev)
63
- def quantum_classifier(x):
64
  qml.RY(x[0], wires=0)
65
  qml.RY(x[1], wires=1)
66
  qml.CNOT(wires=[0, 1])
@@ -68,12 +79,38 @@ def quantum_intrusion_detection(data_stream):
68
 
69
  try:
70
  x = [float(i) for i in data_stream.split(',')]
71
- anomaly_score = abs(quantum_classifier(x))
72
- return "🚨 Intrusion Detected" if anomaly_score > 0.7 else "✅ Normal Activity"
73
  except:
74
- return "❌ Invalid input. Please enter two comma-separated numbers like 0.3,0.7"
75
-
76
- # 6. Quantum Random Number Generator
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  def quantum_random_number():
78
  backend = Aer.get_backend('aer_simulator')
79
  circuit = QuantumCircuit(1, 1)
@@ -84,17 +121,15 @@ def quantum_random_number():
84
  counts = result.get_counts()
85
  return list(counts.keys())[0]
86
 
87
- # 7. Gradio Interface
88
  def create_interface():
89
  with gr.Blocks(title="Quantum Cybersecurity Suite") as demo:
90
  gr.Markdown("# 🛡️ Quantum Cybersecurity Suite")
91
- gr.Markdown("Simulate secure quantum protocols for key distribution, encryption, intrusion detection, and randomness.")
92
-
93
  qkd_key_state = gr.State("")
94
 
95
- # Tab 1: QKD Key Generation
96
  with gr.Tab("1️⃣ Quantum Key Distribution"):
97
- key_length = gr.Slider(minimum=72, maximum=512, step=8, value=128, label="Select QKD Key Length (≥ 72 bits)")
98
  qkd_btn = gr.Button("Generate Quantum Key")
99
  qkd_output = gr.Textbox(label="Generated QKD Key")
100
 
@@ -102,45 +137,59 @@ def create_interface():
102
  key = generate_qkd_key(length)
103
  return key, key
104
 
105
- qkd_btn.click(fn=generate_and_store_key,
106
  inputs=[key_length],
107
  outputs=[qkd_output, qkd_key_state])
108
 
109
- # Tab 2: Quantum Encryption
110
  with gr.Tab("2️⃣ Quantum Encryption"):
111
  msg_input = gr.Textbox(label="Message to Encrypt")
112
  encrypt_btn = gr.Button("Encrypt with QKD Key")
113
  encrypted_output = gr.Textbox(label="Encrypted Message")
114
  key_used_output = gr.Textbox(label="Fernet Key Used")
 
115
 
116
- encrypt_btn.click(fn=quantum_encrypt,
117
  inputs=[msg_input, qkd_key_state],
118
- outputs=[encrypted_output, key_used_output])
119
 
120
- # Tab 3: Quantum Decryption
121
  with gr.Tab("3️⃣ Quantum Decryption"):
122
  encrypted_input = gr.Textbox(label="Encrypted Message")
123
  key_input = gr.Textbox(label="Fernet Key")
124
  decrypt_btn = gr.Button("Decrypt")
125
  decrypted_output = gr.Textbox(label="Decrypted Message")
126
 
127
- decrypt_btn.click(fn=quantum_decrypt,
128
  inputs=[encrypted_input, key_input],
129
  outputs=[decrypted_output])
130
 
131
- # Tab 4: Quantum Intrusion Detection
132
  with gr.Tab("4️⃣ Quantum Intrusion Detection"):
133
  data_input = gr.Textbox(label="Data Stream (e.g. 0.3,0.7)")
134
  detect_btn = gr.Button("Analyze")
135
  detection_output = gr.Textbox(label="Detection Result")
136
-
137
  detect_btn.click(quantum_intrusion_detection,
138
  inputs=[data_input],
139
  outputs=[detection_output])
140
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
141
  return demo
142
 
143
- # 8. Launch App
144
  if __name__ == "__main__":
145
  demo = create_interface()
146
  demo.launch(share=True)
 
6
  from cryptography.fernet import Fernet
7
  import random
8
  import base64
9
+ import matplotlib.pyplot as plt
10
+ import qrcode
11
+ from io import BytesIO
12
+ from PIL import Image
13
 
14
+ # 1. Generate QKD Key (respects target usable length)
15
  def generate_qkd_key(length=128):
16
  shared_key = ""
17
  while len(shared_key) < length:
 
22
  shared_key += str(alice_bit)
23
  return shared_key
24
 
25
+ # 2. Convert QKD key to Fernet key (needs 256 bits)
26
  def bb84_to_fernet_key(qkey_binary_str):
27
  if len(qkey_binary_str) < 256:
28
  raise ValueError("QKD key must be at least 256 bits to generate Fernet key.")
 
29
  binary_256 = qkey_binary_str[:256]
30
  int_val = int(binary_256, 2)
31
+ byte_val = int_val.to_bytes(32, 'big')
32
  fernet_key = base64.urlsafe_b64encode(byte_val)
 
33
  if len(fernet_key) != 44:
34
+ raise ValueError("Generated Fernet key is invalid.")
 
35
  return fernet_key
36
 
37
+ # 3. Encrypt using Fernet key
38
  def quantum_encrypt(message, qkd_key):
39
  if not qkd_key or len(qkd_key) < 72:
40
+ return "❌ QKD key too short. Minimum 72 bits required.", "", None
 
41
  try:
42
  fernet_key = bb84_to_fernet_key(qkd_key)
43
  f = Fernet(fernet_key)
44
  encrypted_message = f.encrypt(message.encode())
45
+ qr_img = generate_qr_image(fernet_key.decode())
46
+ return encrypted_message.decode(), fernet_key.decode(), qr_img
47
  except Exception as e:
48
+ return f"Encryption error: {str(e)}", "", None
49
 
50
+ # 4. Decrypt
51
  def quantum_decrypt(encrypted_message, key):
52
  try:
53
  f = Fernet(key.encode())
54
+ return f.decrypt(encrypted_message.encode()).decode()
 
55
  except Exception as e:
56
  return f"Decryption error: {str(e)}"
57
 
58
+ # 5. QR Code Generator
59
+ def generate_qr_image(data):
60
+ qr = qrcode.QRCode(box_size=6, border=2)
61
+ qr.add_data(data)
62
+ qr.make(fit=True)
63
+ img = qr.make_image(fill_color="black", back_color="white")
64
+ buffer = BytesIO()
65
+ img.save(buffer, format="PNG")
66
+ buffer.seek(0)
67
+ return Image.open(buffer)
68
+
69
+ # 6. Intrusion Detection
70
  def quantum_intrusion_detection(data_stream):
71
  dev = qml.device("default.qubit", wires=2)
72
 
73
  @qml.qnode(dev)
74
+ def classifier(x):
75
  qml.RY(x[0], wires=0)
76
  qml.RY(x[1], wires=1)
77
  qml.CNOT(wires=[0, 1])
 
79
 
80
  try:
81
  x = [float(i) for i in data_stream.split(',')]
82
+ score = abs(classifier(x))
83
+ return "🚨 Intrusion Detected" if score > 0.7 else "✅ Normal Activity"
84
  except:
85
+ return "❌ Invalid input. Format: 0.3,0.7"
86
+
87
+ # 7. Quantum Noise Simulation
88
+ def simulate_noise(bits=100):
89
+ original = np.random.choice([0, 1], size=bits)
90
+ noisy = [bit if random.random() > 0.1 else 1 - bit for bit in original]
91
+ plt.figure(figsize=(10, 1))
92
+ plt.plot(original, 'bo', label="Original")
93
+ plt.plot(noisy, 'rx', label="With Noise")
94
+ plt.yticks([0, 1])
95
+ plt.legend()
96
+ plt.title("Quantum Noise Simulation (Eavesdropper Effect)")
97
+ buf = BytesIO()
98
+ plt.savefig(buf, format='png')
99
+ buf.seek(0)
100
+ return Image.open(buf)
101
+
102
+ # 8. Randomness Visualizer
103
+ def visualize_qkd_bits(qkd_key):
104
+ ones = qkd_key.count('1')
105
+ zeros = qkd_key.count('0')
106
+ plt.bar(['0', '1'], [zeros, ones], color=['blue', 'green'])
107
+ plt.title("Randomness Distribution in QKD Key")
108
+ buf = BytesIO()
109
+ plt.savefig(buf, format='png')
110
+ buf.seek(0)
111
+ return Image.open(buf)
112
+
113
+ # 9. Quantum Random Number Generator
114
  def quantum_random_number():
115
  backend = Aer.get_backend('aer_simulator')
116
  circuit = QuantumCircuit(1, 1)
 
121
  counts = result.get_counts()
122
  return list(counts.keys())[0]
123
 
124
+ # 10. Gradio Interface
125
  def create_interface():
126
  with gr.Blocks(title="Quantum Cybersecurity Suite") as demo:
127
  gr.Markdown("# 🛡️ Quantum Cybersecurity Suite")
 
 
128
  qkd_key_state = gr.State("")
129
 
130
+ # Tab 1: QKD Key
131
  with gr.Tab("1️⃣ Quantum Key Distribution"):
132
+ key_length = gr.Slider(72, 512, step=8, value=128, label="Select QKD Key Length (≥ 72 bits)")
133
  qkd_btn = gr.Button("Generate Quantum Key")
134
  qkd_output = gr.Textbox(label="Generated QKD Key")
135
 
 
137
  key = generate_qkd_key(length)
138
  return key, key
139
 
140
+ qkd_btn.click(generate_and_store_key,
141
  inputs=[key_length],
142
  outputs=[qkd_output, qkd_key_state])
143
 
144
+ # Tab 2: Encryption
145
  with gr.Tab("2️⃣ Quantum Encryption"):
146
  msg_input = gr.Textbox(label="Message to Encrypt")
147
  encrypt_btn = gr.Button("Encrypt with QKD Key")
148
  encrypted_output = gr.Textbox(label="Encrypted Message")
149
  key_used_output = gr.Textbox(label="Fernet Key Used")
150
+ qr_code_output = gr.Image(label="QR Code of Key")
151
 
152
+ encrypt_btn.click(quantum_encrypt,
153
  inputs=[msg_input, qkd_key_state],
154
+ outputs=[encrypted_output, key_used_output, qr_code_output])
155
 
156
+ # Tab 3: Decryption
157
  with gr.Tab("3️⃣ Quantum Decryption"):
158
  encrypted_input = gr.Textbox(label="Encrypted Message")
159
  key_input = gr.Textbox(label="Fernet Key")
160
  decrypt_btn = gr.Button("Decrypt")
161
  decrypted_output = gr.Textbox(label="Decrypted Message")
162
 
163
+ decrypt_btn.click(quantum_decrypt,
164
  inputs=[encrypted_input, key_input],
165
  outputs=[decrypted_output])
166
 
167
+ # Tab 4: Intrusion Detection
168
  with gr.Tab("4️⃣ Quantum Intrusion Detection"):
169
  data_input = gr.Textbox(label="Data Stream (e.g. 0.3,0.7)")
170
  detect_btn = gr.Button("Analyze")
171
  detection_output = gr.Textbox(label="Detection Result")
 
172
  detect_btn.click(quantum_intrusion_detection,
173
  inputs=[data_input],
174
  outputs=[detection_output])
175
 
176
+ # Tab 5: Quantum Noise Simulation
177
+ with gr.Tab("5️⃣ Eavesdropper Noise Simulation"):
178
+ noise_btn = gr.Button("Simulate Noise")
179
+ noise_output = gr.Image(label="Quantum Channel with Noise")
180
+ noise_btn.click(simulate_noise, outputs=noise_output)
181
+
182
+ # Tab 6: Randomness Distribution
183
+ with gr.Tab("6️⃣ QKD Key Randomness Visualizer"):
184
+ viz_btn = gr.Button("Visualize Randomness")
185
+ viz_output = gr.Image(label="Randomness Bar Graph")
186
+ viz_btn.click(fn=visualize_qkd_bits,
187
+ inputs=[qkd_key_state],
188
+ outputs=[viz_output])
189
+
190
  return demo
191
 
192
+ # 11. Launch
193
  if __name__ == "__main__":
194
  demo = create_interface()
195
  demo.launch(share=True)