1+ {
2+ "nbformat" : 4 ,
3+ "nbformat_minor" : 0 ,
4+ "metadata" : {
5+ "colab" : {
6+ "provenance" : []
7+ },
8+ "kernelspec" : {
9+ "name" : " python3" ,
10+ "display_name" : " Python 3"
11+ },
12+ "language_info" : {
13+ "name" : " python"
14+ }
15+ },
16+ "cells" : [
17+ {
18+ "cell_type" : " code" ,
19+ "execution_count" : 8 ,
20+ "metadata" : {
21+ "id" : " p-ytHCPV2Ywy"
22+ },
23+ "outputs" : [],
24+ "source" : [
25+ " import hashlib, hmac, json, time, secrets, numpy as np\n " ,
26+ " from dataclasses import dataclass\n " ,
27+ " from typing import Dict, List\n " ,
28+ " from cryptography.hazmat.primitives.asymmetric import rsa, padding\n " ,
29+ " from cryptography.hazmat.primitives import hashes, serialization\n " ,
30+ " from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes\n " ,
31+ " from cryptography.hazmat.backends import default_backend\n " ,
32+ " \n " ,
33+ " @dataclass\n " ,
34+ " class SecurityEvent:\n " ,
35+ " timestamp: float\n " ,
36+ " event_type: str\n " ,
37+ " risk_score: float\n " ,
38+ " details: Dict"
39+ ]
40+ },
41+ {
42+ "cell_type" : " code" ,
43+ "source" : [
44+ " class CryptoAgent:\n " ,
45+ " def __init__(self, agent_id: str):\n " ,
46+ " self.agent_id = agent_id\n " ,
47+ " self.private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=default_backend())\n " ,
48+ " self.public_key = self.private_key.public_key()\n " ,
49+ " self.session_keys = {}\n " ,
50+ " self.security_events = []\n " ,
51+ " self.encryption_count = 0\n " ,
52+ " self.key_rotation_threshold = 100\n " ,
53+ " \n " ,
54+ " def get_public_key_bytes(self) -> bytes:\n " ,
55+ " return self.public_key.public_bytes(\n " ,
56+ " encoding=serialization.Encoding.PEM,\n " ,
57+ " format=serialization.PublicFormat.SubjectPublicKeyInfo\n " ,
58+ " )\n " ,
59+ " \n " ,
60+ " def establish_session(self, partner_id: str, partner_public_key_bytes: bytes) -> bytes:\n " ,
61+ " session_key = secrets.token_bytes(32)\n " ,
62+ " self.session_keys[partner_id] = session_key\n " ,
63+ " partner_public_key = serialization.load_pem_public_key(partner_public_key_bytes, backend=default_backend())\n " ,
64+ " encrypted_session_key = partner_public_key.encrypt(\n " ,
65+ " session_key,\n " ,
66+ " padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)\n " ,
67+ " )\n " ,
68+ " self.log_security_event(\" SESSION_ESTABLISHED\" , 0.1, {\" partner\" : partner_id})\n " ,
69+ " return encrypted_session_key\n " ,
70+ " \n " ,
71+ " def receive_session_key(self, partner_id: str, encrypted_session_key: bytes):\n " ,
72+ " session_key = self.private_key.decrypt(\n " ,
73+ " encrypted_session_key,\n " ,
74+ " padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)\n " ,
75+ " )\n " ,
76+ " self.session_keys[partner_id] = session_key"
77+ ],
78+ "metadata" : {
79+ "id" : " AFU3agul5iLa"
80+ },
81+ "execution_count" : 9 ,
82+ "outputs" : []
83+ },
84+ {
85+ "cell_type" : " code" ,
86+ "source" : [
87+ " def encrypt_message(self, partner_id: str, plaintext: str) -> Dict:\n " ,
88+ " if partner_id not in self.session_keys:\n " ,
89+ " raise ValueError(f\" No session established with {partner_id}\" )\n " ,
90+ " self.encryption_count += 1\n " ,
91+ " if self.encryption_count >= self.key_rotation_threshold:\n " ,
92+ " self.log_security_event(\" KEY_ROTATION_NEEDED\" , 0.3, {\" count\" : self.encryption_count})\n " ,
93+ " iv = secrets.token_bytes(12)\n " ,
94+ " cipher = Cipher(algorithms.AES(self.session_keys[partner_id]), modes.GCM(iv), backend=default_backend())\n " ,
95+ " encryptor = cipher.encryptor()\n " ,
96+ " ciphertext = encryptor.update(plaintext.encode()) + encryptor.finalize()\n " ,
97+ " message_data = iv + ciphertext + encryptor.tag\n " ,
98+ " signature = self.sign_data(message_data)\n " ,
99+ " risk_score = self.analyze_encryption_pattern(len(plaintext))\n " ,
100+ " return {\n " ,
101+ " \" sender\" : self.agent_id,\n " ,
102+ " \" recipient\" : partner_id,\n " ,
103+ " \" iv\" : iv.hex(),\n " ,
104+ " \" ciphertext\" : ciphertext.hex(),\n " ,
105+ " \" tag\" : encryptor.tag.hex(),\n " ,
106+ " \" signature\" : signature.hex(),\n " ,
107+ " \" timestamp\" : time.time(),\n " ,
108+ " \" risk_score\" : risk_score\n " ,
109+ " }\n " ,
110+ " \n " ,
111+ " def decrypt_message(self, encrypted_msg: Dict) -> str:\n " ,
112+ " sender_id = encrypted_msg[\" sender\" ]\n " ,
113+ " if sender_id not in self.session_keys:\n " ,
114+ " raise ValueError(f\" No session established with {sender_id}\" )\n " ,
115+ " iv = bytes.fromhex(encrypted_msg[\" iv\" ])\n " ,
116+ " ciphertext = bytes.fromhex(encrypted_msg[\" ciphertext\" ])\n " ,
117+ " tag = bytes.fromhex(encrypted_msg[\" tag\" ])\n " ,
118+ " cipher = Cipher(algorithms.AES(self.session_keys[sender_id]), modes.GCM(iv, tag), backend=default_backend())\n " ,
119+ " decryptor = cipher.decryptor()\n " ,
120+ " plaintext = decryptor.update(ciphertext) + decryptor.finalize()\n " ,
121+ " if encrypted_msg.get(\" risk_score\" , 0) > 0.7:\n " ,
122+ " self.log_security_event(\" HIGH_RISK_MESSAGE\" , 0.8, {\" sender\" : sender_id})\n " ,
123+ " return plaintext.decode()"
124+ ],
125+ "metadata" : {
126+ "id" : " 5-9LM1Q65jPb"
127+ },
128+ "execution_count" : 10 ,
129+ "outputs" : []
130+ },
131+ {
132+ "cell_type" : " code" ,
133+ "source" : [
134+ " def sign_data(self, data: bytes) -> bytes:\n " ,
135+ " return self.private_key.sign(\n " ,
136+ " data,\n " ,
137+ " padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH),\n " ,
138+ " hashes.SHA256()\n " ,
139+ " )\n " ,
140+ " \n " ,
141+ " def analyze_encryption_pattern(self, message_length: int) -> float:\n " ,
142+ " recent_events = self.security_events[-10:] if len(self.security_events) >= 10 else self.security_events\n " ,
143+ " avg_risk = np.mean([e.risk_score for e in recent_events]) if recent_events else 0.1\n " ,
144+ " risk_score = 0.1\n " ,
145+ " if message_length > 10000:\n " ,
146+ " risk_score += 0.3\n " ,
147+ " if self.encryption_count % 50 == 0 and self.encryption_count > 0:\n " ,
148+ " risk_score += 0.2\n " ,
149+ " risk_score = (risk_score + avg_risk) / 2\n " ,
150+ " self.log_security_event(\" ENCRYPTION_ANALYSIS\" , risk_score, {\" msg_len\" : message_length})\n " ,
151+ " return min(risk_score, 1.0)\n " ,
152+ " \n " ,
153+ " def log_security_event(self, event_type: str, risk_score: float, details: Dict):\n " ,
154+ " event = SecurityEvent(timestamp=time.time(), event_type=event_type, risk_score=risk_score, details=details)\n " ,
155+ " self.security_events.append(event)\n " ,
156+ " \n " ,
157+ " def generate_security_report(self) -> Dict:\n " ,
158+ " if not self.security_events:\n " ,
159+ " return {\" status\" : \" No events recorded\" }\n " ,
160+ " total_events = len(self.security_events)\n " ,
161+ " high_risk_events = [e for e in self.security_events if e.risk_score > 0.7]\n " ,
162+ " avg_risk = np.mean([e.risk_score for e in self.security_events])\n " ,
163+ " event_types = {}\n " ,
164+ " for event in self.security_events:\n " ,
165+ " event_types[event.event_type] = event_types.get(event.event_type, 0) + 1\n " ,
166+ " return {\n " ,
167+ " \" agent_id\" : self.agent_id,\n " ,
168+ " \" total_events\" : total_events,\n " ,
169+ " \" high_risk_events\" : len(high_risk_events),\n " ,
170+ " \" average_risk_score\" : round(avg_risk, 3),\n " ,
171+ " \" encryption_count\" : self.encryption_count,\n " ,
172+ " \" key_rotation_needed\" : self.encryption_count >= self.key_rotation_threshold,\n " ,
173+ " \" event_breakdown\" : event_types,\n " ,
174+ " \" security_status\" : \" CRITICAL\" if avg_risk > 0.7 else \" WARNING\" if avg_risk > 0.4 else \" NORMAL\"\n " ,
175+ " }"
176+ ],
177+ "metadata" : {
178+ "id" : " qY4kzY_e5llq"
179+ },
180+ "execution_count" : 11 ,
181+ "outputs" : []
182+ },
183+ {
184+ "cell_type" : " code" ,
185+ "source" : [
186+ " def demo_crypto_agent_system():\n " ,
187+ " print(\" 🔐 Advanced Cryptographic Agent System Demo\\ n\" )\n " ,
188+ " print(\" =\" * 60)\n " ,
189+ " alice = CryptoAgent(\" Alice\" )\n " ,
190+ " bob = CryptoAgent(\" Bob\" )\n " ,
191+ " print(\"\\ n1. Agents Created\" )\n " ,
192+ " print(f\" Alice ID: {alice.agent_id}\" )\n " ,
193+ " print(f\" Bob ID: {bob.agent_id}\" )\n " ,
194+ " print(\"\\ n2. Establishing Secure Session (Hybrid Encryption)\" )\n " ,
195+ " alice_public_key = alice.get_public_key_bytes()\n " ,
196+ " bob_public_key = bob.get_public_key_bytes()\n " ,
197+ " encrypted_session_key = alice.establish_session(\" Bob\" , bob_public_key)\n " ,
198+ " bob.receive_session_key(\" Alice\" , encrypted_session_key)\n " ,
199+ " print(f\" ✓ Session established with {len(encrypted_session_key)} byte encrypted key\" )\n " ,
200+ " print(\"\\ n3. Encrypting and Transmitting Messages\" )\n " ,
201+ " messages = [\n " ,
202+ " \" Hello Bob! This is a secure message.\" ,\n " ,
203+ " \" The launch codes are: Alpha-7-Charlie-9\" ,\n " ,
204+ " \" Meeting at 3 PM tomorrow.\" ,\n " ,
205+ " \" This is a very long message \" * 100\n " ,
206+ " ]\n " ,
207+ " for i, msg in enumerate(messages, 1):\n " ,
208+ " encrypted = alice.encrypt_message(\" Bob\" , msg)\n " ,
209+ " print(f\"\\ n Message {i}:\" )\n " ,
210+ " print(f\" - Plaintext length: {len(msg)} chars\" )\n " ,
211+ " print(f\" - Ciphertext: {encrypted['ciphertext'][:60]}...\" )\n " ,
212+ " print(f\" - Risk Score: {encrypted['risk_score']:.3f}\" )\n " ,
213+ " print(f\" - Signature: {encrypted['signature'][:40]}...\" )\n " ,
214+ " decrypted = bob.decrypt_message(encrypted)\n " ,
215+ " print(f\" - Decrypted: {decrypted[:60]}{'...' if len(decrypted) > 60 else ''}\" )\n " ,
216+ " print(f\" - Verification: {'✓ SUCCESS' if decrypted == msg else '✗ FAILED'}\" )\n " ,
217+ " print(\"\\ n4. AI-Powered Security Analysis\" )\n " ,
218+ " print(\"\\ n Alice's Security Report:\" )\n " ,
219+ " alice_report = alice.generate_security_report()\n " ,
220+ " for k, v in alice_report.items(): print(f\" - {k}: {v}\" )\n " ,
221+ " print(\"\\ n Bob's Security Report:\" )\n " ,
222+ " bob_report = bob.generate_security_report()\n " ,
223+ " for k, v in bob_report.items(): print(f\" - {k}: {v}\" )\n " ,
224+ " print(\"\\ n\" + \" =\" * 60)\n " ,
225+ " print(\" Demo Complete! Key Features Demonstrated:\" )\n " ,
226+ " print(\" ✓ Hybrid encryption (RSA + AES-GCM)\" )\n " ,
227+ " print(\" ✓ Digital signatures for authentication\" )\n " ,
228+ " print(\" ✓ AI-powered anomaly detection\" )\n " ,
229+ " print(\" ✓ Intelligent key rotation recommendations\" )\n " ,
230+ " print(\" ✓ Real-time security monitoring\" )\n " ,
231+ " \n " ,
232+ " if __name__ == \" __main__\" :\n " ,
233+ " demo_crypto_agent_system()"
234+ ],
235+ "metadata" : {
236+ "colab" : {
237+ "base_uri" : " https://localhost:8080/"
238+ },
239+ "id" : " ZsSsabEK6gIf" ,
240+ "outputId" : " 2d4ac767-e5d1-401c-dbf5-3dae59dee2af"
241+ },
242+ "execution_count" : 13 ,
243+ "outputs" : [
244+ {
245+ "output_type" : " stream" ,
246+ "name" : " stdout" ,
247+ "text" : [
248+ " 🔐 Advanced Cryptographic Agent System Demo\n " ,
249+ " \n " ,
250+ " ============================================================\n " ,
251+ " \n " ,
252+ " 1. Agents Created\n " ,
253+ " Alice ID: Alice\n " ,
254+ " Bob ID: Bob\n " ,
255+ " \n " ,
256+ " 2. Establishing Secure Session (Hybrid Encryption)\n " ,
257+ " ✓ Session established with 256 byte encrypted key\n " ,
258+ " \n " ,
259+ " 3. Encrypting and Transmitting Messages\n " ,
260+ " \n " ,
261+ " Message 1:\n " ,
262+ " - Plaintext length: 36 chars\n " ,
263+ " - Ciphertext: c551b1da2e3713064473969db483824880141b86a1b9960e87fcca1c5bc5...\n " ,
264+ " - Risk Score: 0.100\n " ,
265+ " - Signature: 3cec14a1f6d77e78640297607198f953c83c2161...\n " ,
266+ " - Decrypted: Hello Bob! This is a secure message.\n " ,
267+ " - Verification: ✓ SUCCESS\n " ,
268+ " \n " ,
269+ " Message 2:\n " ,
270+ " - Plaintext length: 39 chars\n " ,
271+ " - Ciphertext: 64a04e9b6cc6e0a5be64c4315213e19aa6b82d055bbf4a2f1feb0b985e50...\n " ,
272+ " - Risk Score: 0.100\n " ,
273+ " - Signature: 4e0108862c4c59682c989f93ed5c90d349eca76e...\n " ,
274+ " - Decrypted: The launch codes are: Alpha-7-Charlie-9\n " ,
275+ " - Verification: ✓ SUCCESS\n " ,
276+ " \n " ,
277+ " Message 3:\n " ,
278+ " - Plaintext length: 25 chars\n " ,
279+ " - Ciphertext: 025023da9f026e840ff7e9d6a3d2697fc4ea661134859c277b...\n " ,
280+ " - Risk Score: 0.100\n " ,
281+ " - Signature: 17c89473e99fd95de7063ab8816413ac4022de48...\n " ,
282+ " - Decrypted: Meeting at 3 PM tomorrow.\n " ,
283+ " - Verification: ✓ SUCCESS\n " ,
284+ " \n " ,
285+ " Message 4:\n " ,
286+ " - Plaintext length: 2800 chars\n " ,
287+ " - Ciphertext: 2390844c20a082dae63b288fc5a7af19a54291a92fdc098e6823c521033b...\n " ,
288+ " - Risk Score: 0.100\n " ,
289+ " - Signature: 68e5d45c7e5fca353049e0d8706644d7322e93e1...\n " ,
290+ " - Decrypted: This is a very long message This is a very long message This...\n " ,
291+ " - Verification: ✓ SUCCESS\n " ,
292+ " \n " ,
293+ " 4. AI-Powered Security Analysis\n " ,
294+ " \n " ,
295+ " Alice's Security Report:\n " ,
296+ " - agent_id: Alice\n " ,
297+ " - total_events: 5\n " ,
298+ " - high_risk_events: 0\n " ,
299+ " - average_risk_score: 0.1\n " ,
300+ " - encryption_count: 4\n " ,
301+ " - key_rotation_needed: False\n " ,
302+ " - event_breakdown: {'SESSION_ESTABLISHED': 1, 'ENCRYPTION_ANALYSIS': 4}\n " ,
303+ " - security_status: NORMAL\n " ,
304+ " \n " ,
305+ " Bob's Security Report:\n " ,
306+ " - status: No events recorded\n " ,
307+ " \n " ,
308+ " ============================================================\n " ,
309+ " Demo Complete! Key Features Demonstrated:\n " ,
310+ " ✓ Hybrid encryption (RSA + AES-GCM)\n " ,
311+ " ✓ Digital signatures for authentication\n " ,
312+ " ✓ AI-powered anomaly detection\n " ,
313+ " ✓ Intelligent key rotation recommendations\n " ,
314+ " ✓ Real-time security monitoring\n "
315+ ]
316+ }
317+ ]
318+ }
319+ ]
320+ }
0 commit comments