zyracrypt 2.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. advanced_features/__init__.py +35 -0
  2. advanced_features/blockchain_cryptography_functions.py +33 -0
  3. advanced_features/cryptographic_audit_log.py +39 -0
  4. advanced_features/group_e2e_api.py +313 -0
  5. advanced_features/group_e2e_encryption.py +331 -0
  6. advanced_features/homomorphic_encryption.py +518 -0
  7. advanced_features/hybrid_pqc_engine.py +0 -0
  8. advanced_features/hybrid_pqc_enhanced.py +486 -0
  9. advanced_features/ibe_cryptography.py +337 -0
  10. advanced_features/memory_encryption_unit.py +29 -0
  11. advanced_features/pqc_cryptography.py +251 -0
  12. advanced_features/secure_enclave_mpc.py +520 -0
  13. advanced_features/secure_messaging_protocol.py +53 -0
  14. advanced_features/secure_mpc_enclaves.py +634 -0
  15. advanced_features/secure_multi_party_computation.py +604 -0
  16. advanced_features/security_hardening.py +476 -0
  17. advanced_features/side_channel_protection.py +463 -0
  18. advanced_features/tamper_resistant_data_structures.py +77 -0
  19. advanced_features/threshold_multisig.py +682 -0
  20. advanced_features/threshold_multisig_enhanced.py +605 -0
  21. advanced_features/white_box_cryptography.py +615 -0
  22. core_cryptography/__init__.py +24 -0
  23. core_cryptography/algorithm_agility_versioning.py +535 -0
  24. core_cryptography/algorithm_manager.py +37 -0
  25. core_cryptography/asymmetric_encryption.py +65 -0
  26. core_cryptography/crypto_suite_registry.py +320 -0
  27. core_cryptography/encryption_framework.py +109 -0
  28. core_cryptography/enhanced_algorithm_manager.py +381 -0
  29. core_cryptography/plausible_deniability.py +65 -0
  30. core_cryptography/symmetric_encryption.py +59 -0
  31. data_protection/__init__.py +22 -0
  32. data_protection/compression_unit.py +17 -0
  33. data_protection/data_obfuscation_unit.py +17 -0
  34. data_protection/data_protection_manager.py +50 -0
  35. data_protection/data_type_manager.py +74 -0
  36. data_protection/secure_memory_handling.py +15 -0
  37. key_management/__init__.py +23 -0
  38. key_management/enhanced_kdf.py +555 -0
  39. key_management/enhanced_kdf_password.py +626 -0
  40. key_management/enhanced_key_manager.py +361 -0
  41. key_management/envelope_encryption_kms.py +547 -0
  42. key_management/key_exchange.py +57 -0
  43. key_management/key_generator.py +61 -0
  44. key_management/key_manager.py +74 -0
  45. key_management/kms_provider.py +618 -0
  46. key_management/secure_key_store.py +59 -0
  47. post_quantum_cryptography/__init__.py +24 -0
  48. post_quantum_cryptography/post_quantum_cryptography_unit.py +34 -0
  49. specialized_security/__init__.py +22 -0
  50. specialized_security/file_encryption_manager.py +44 -0
  51. specialized_security/secure_deletion_unit.py +45 -0
  52. specialized_security/secure_session_manager.py +52 -0
  53. specialized_security/steganography_unit.py +82 -0
  54. zyracrypt-2.0.0.dist-info/METADATA +398 -0
  55. zyracrypt-2.0.0.dist-info/RECORD +58 -0
  56. zyracrypt-2.0.0.dist-info/WHEEL +5 -0
  57. zyracrypt-2.0.0.dist-info/licenses/LICENSE +21 -0
  58. zyracrypt-2.0.0.dist-info/top_level.txt +6 -0
@@ -0,0 +1,35 @@
1
+ """
2
+ Advanced Features Module
3
+ ========================
4
+
5
+ Provides advanced cryptographic features including:
6
+ - Threshold signatures and multi-signature schemes
7
+ - Multi-party computation (MPC)
8
+ - Secure enclaves (software and hardware-backed)
9
+ - Side-channel resistance
10
+ - White-box cryptography
11
+ - Homomorphic encryption
12
+ - Group end-to-end encryption
13
+ - Identity-based encryption (IBE)
14
+ - Blockchain cryptography functions
15
+ """
16
+
17
+ from .threshold_multisig_enhanced import ThresholdECDSA, MultisigManager, ShamirSecretSharing
18
+ from .side_channel_protection import (
19
+ SideChannelGuard,
20
+ TimingAttackProtection,
21
+ ConstantTimeOperations,
22
+ SecureMemoryManager
23
+ )
24
+ from .security_hardening import SecurityHardeningManager
25
+
26
+ __all__ = [
27
+ "ThresholdECDSA",
28
+ "MultisigManager",
29
+ "ShamirSecretSharing",
30
+ "SideChannelGuard",
31
+ "TimingAttackProtection",
32
+ "ConstantTimeOperations",
33
+ "SecureMemoryManager",
34
+ "SecurityHardeningManager",
35
+ ]
@@ -0,0 +1,33 @@
1
+
2
+
3
+ import hashlib
4
+ import time
5
+
6
+ class BlockchainCryptographyFunctions:
7
+ def __init__(self):
8
+ pass
9
+
10
+ def calculate_block_hash(self, index: int, timestamp: float, data: str, previous_hash: str, nonce: int) -> str:
11
+ """Calculates the hash for a blockchain block."""
12
+ block_string = f"{index}{timestamp}{data}{previous_hash}{nonce}"
13
+ return hashlib.sha256(block_string.encode("utf-8")).hexdigest()
14
+
15
+ def proof_of_work(self, last_proof: int) -> int:
16
+ """Simple Proof of Work algorithm: Find a number p' such that hash(pp') contains 4 leading zeros."""
17
+ proof = 0
18
+ while self.valid_proof(last_proof, proof) is False:
19
+ proof += 1
20
+ return proof
21
+
22
+ def valid_proof(self, last_proof: int, proof: int) -> bool:
23
+ """Validates the proof of work."""
24
+ guess = f"{last_proof}{proof}".encode("utf-8")
25
+ guess_hash = hashlib.sha256(guess).hexdigest()
26
+ return guess_hash[:4] == "0000"
27
+
28
+ def create_transaction_hash(self, sender: str, recipient: str, amount: float) -> str:
29
+ """Creates a hash for a transaction."""
30
+ transaction_string = f"{sender}{recipient}{amount}{time.time()}"
31
+ return hashlib.sha256(transaction_string.encode("utf-8")).hexdigest()
32
+
33
+
@@ -0,0 +1,39 @@
1
+
2
+
3
+ from datetime import datetime
4
+ import json
5
+ import os
6
+
7
+ class CryptographicAuditLog:
8
+ def __init__(self, log_file: str = "./audit.log"):
9
+ self.log_file = log_file
10
+
11
+ def _write_log(self, entry: dict):
12
+ """Writes a log entry to the audit log file."""
13
+ with open(self.log_file, "a") as f:
14
+ f.write(json.dumps(entry) + "\n")
15
+
16
+ def log_event(self, event_type: str, user_id: str = "system", details: dict = None):
17
+ """Logs a cryptographic event."""
18
+ log_entry = {
19
+ "timestamp": datetime.now().isoformat(),
20
+ "event_type": event_type,
21
+ "user_id": user_id,
22
+ "details": details if details is not None else {}
23
+ }
24
+ self._write_log(log_entry)
25
+
26
+ def get_logs(self) -> list[dict]:
27
+ """Retrieves all log entries."""
28
+ logs = []
29
+ if os.path.exists(self.log_file):
30
+ with open(self.log_file, "r") as f:
31
+ for line in f:
32
+ try:
33
+ logs.append(json.loads(line))
34
+ except json.JSONDecodeError:
35
+ # Handle malformed log entries
36
+ pass
37
+ return logs
38
+
39
+
@@ -0,0 +1,313 @@
1
+ """
2
+ Group E2E Encryption API
3
+ واجهة برمجة التطبيقات لنظام تشفير المجموعات من طرف إلى طرف
4
+ """
5
+
6
+ from flask import Flask, request, jsonify
7
+ from flask_cors import CORS
8
+ import base64
9
+ import json
10
+ from typing import Dict, Any
11
+
12
+ from .group_e2e_encryption import (
13
+ GroupE2EEncryption,
14
+ GroupKeyDistribution,
15
+ GroupMessageHistory
16
+ )
17
+ from ..core_cryptography.encryption_framework import EncryptionFramework
18
+ from ..key_management.key_manager import KeyManager
19
+
20
+
21
+ class GroupE2EAPI:
22
+ """
23
+ واجهة برمجة التطبيقات لنظام تشفير المجموعات
24
+ """
25
+
26
+ def __init__(self):
27
+ self.app = Flask(__name__)
28
+ CORS(self.app) # تمكين CORS للتطبيقات الخارجية
29
+
30
+ # تهيئة المكونات
31
+ self.key_manager = KeyManager()
32
+ self.encryption_framework = EncryptionFramework()
33
+ self.group_encryption = GroupE2EEncryption(self.key_manager, self.encryption_framework)
34
+ self.key_distribution = GroupKeyDistribution(self.group_encryption)
35
+ self.message_history = GroupMessageHistory()
36
+
37
+ # تسجيل المسارات
38
+ self._register_routes()
39
+
40
+ def _register_routes(self):
41
+ """تسجيل مسارات API"""
42
+
43
+ @self.app.route('/api/health', methods=['GET'])
44
+ def health_check():
45
+ """فحص حالة الخدمة"""
46
+ return jsonify({
47
+ 'status': 'healthy',
48
+ 'service': 'Group E2E Encryption API',
49
+ 'version': '1.0.0'
50
+ })
51
+
52
+ @self.app.route('/api/groups', methods=['POST'])
53
+ def create_group():
54
+ """إنشاء مجموعة جديدة"""
55
+ try:
56
+ data = request.get_json()
57
+
58
+ # التحقق من البيانات المطلوبة
59
+ required_fields = ['group_id', 'creator_id', 'creator_public_key']
60
+ for field in required_fields:
61
+ if field not in data:
62
+ return jsonify({'error': f'حقل مطلوب مفقود: {field}'}), 400
63
+
64
+ # إنشاء المجموعة
65
+ result = self.group_encryption.create_group(
66
+ data['group_id'],
67
+ data['creator_id'],
68
+ data['creator_public_key']
69
+ )
70
+
71
+ return jsonify({
72
+ 'success': True,
73
+ 'data': result
74
+ })
75
+
76
+ except Exception as e:
77
+ return jsonify({'error': str(e)}), 500
78
+
79
+ @self.app.route('/api/groups/<group_id>/members', methods=['POST'])
80
+ def add_member(group_id):
81
+ """إضافة عضو إلى المجموعة"""
82
+ try:
83
+ data = request.get_json()
84
+
85
+ required_fields = ['new_member_id', 'new_member_public_key', 'inviter_id']
86
+ for field in required_fields:
87
+ if field not in data:
88
+ return jsonify({'error': f'حقل مطلوب مفقود: {field}'}), 400
89
+
90
+ result = self.group_encryption.add_member_to_group(
91
+ group_id,
92
+ data['new_member_id'],
93
+ data['new_member_public_key'],
94
+ data['inviter_id']
95
+ )
96
+
97
+ # توزيع مفتاح المجموعة للعضو الجديد
98
+ key_distribution_result = self.key_distribution.distribute_group_key_to_new_member(
99
+ group_id,
100
+ data['new_member_id'],
101
+ data['inviter_id']
102
+ )
103
+
104
+ return jsonify({
105
+ 'success': True,
106
+ 'data': {
107
+ 'member_addition': result,
108
+ 'key_distribution': key_distribution_result
109
+ }
110
+ })
111
+
112
+ except Exception as e:
113
+ return jsonify({'error': str(e)}), 500
114
+
115
+ @self.app.route('/api/groups/<group_id>/members/<member_id>', methods=['DELETE'])
116
+ def remove_member(group_id, member_id):
117
+ """إزالة عضو من المجموعة"""
118
+ try:
119
+ data = request.get_json()
120
+
121
+ if 'remover_id' not in data:
122
+ return jsonify({'error': 'حقل مطلوب مفقود: remover_id'}), 400
123
+
124
+ result = self.group_encryption.remove_member_from_group(
125
+ group_id,
126
+ member_id,
127
+ data['remover_id']
128
+ )
129
+
130
+ return jsonify({
131
+ 'success': True,
132
+ 'data': result
133
+ })
134
+
135
+ except Exception as e:
136
+ return jsonify({'error': str(e)}), 500
137
+
138
+ @self.app.route('/api/groups/<group_id>/messages', methods=['POST'])
139
+ def send_message(group_id):
140
+ """إرسال رسالة مشفرة للمجموعة"""
141
+ try:
142
+ data = request.get_json()
143
+
144
+ required_fields = ['sender_id', 'message']
145
+ for field in required_fields:
146
+ if field not in data:
147
+ return jsonify({'error': f'حقل مطلوب مفقود: {field}'}), 400
148
+
149
+ # تحويل الرسالة إلى bytes
150
+ message_bytes = data['message'].encode('utf-8')
151
+
152
+ # تشفير الرسالة
153
+ encrypted_message = self.group_encryption.encrypt_group_message(
154
+ group_id,
155
+ data['sender_id'],
156
+ message_bytes
157
+ )
158
+
159
+ # حفظ الرسالة في التاريخ
160
+ self.message_history.store_encrypted_message(group_id, encrypted_message)
161
+
162
+ # تحويل البيانات الثنائية إلى base64 للإرسال
163
+ response_data = self._encode_binary_data(encrypted_message)
164
+
165
+ return jsonify({
166
+ 'success': True,
167
+ 'data': response_data
168
+ })
169
+
170
+ except Exception as e:
171
+ return jsonify({'error': str(e)}), 500
172
+
173
+ @self.app.route('/api/groups/<group_id>/messages/<int:message_counter>', methods=['GET'])
174
+ def decrypt_message(group_id, message_counter):
175
+ """فك تشفير رسالة من المجموعة"""
176
+ try:
177
+ recipient_id = request.args.get('recipient_id')
178
+ if not recipient_id:
179
+ return jsonify({'error': 'معرف المستقبل مطلوب'}), 400
180
+
181
+ # البحث عن الرسالة في التاريخ
182
+ messages = self.message_history.get_group_message_history(group_id)
183
+ target_message = None
184
+
185
+ for msg in messages:
186
+ if msg['message_counter'] == message_counter:
187
+ target_message = msg
188
+ break
189
+
190
+ if not target_message:
191
+ return jsonify({'error': 'الرسالة غير موجودة'}), 404
192
+
193
+ # فك تشفير الرسالة
194
+ decrypted_message = self.group_encryption.decrypt_group_message(
195
+ target_message,
196
+ recipient_id
197
+ )
198
+
199
+ return jsonify({
200
+ 'success': True,
201
+ 'data': {
202
+ 'message': decrypted_message.decode('utf-8'),
203
+ 'sender_id': target_message['sender_id'],
204
+ 'timestamp': target_message['timestamp']
205
+ }
206
+ })
207
+
208
+ except Exception as e:
209
+ return jsonify({'error': str(e)}), 500
210
+
211
+ @self.app.route('/api/groups/<group_id>', methods=['GET'])
212
+ def get_group_info(group_id):
213
+ """الحصول على معلومات المجموعة"""
214
+ try:
215
+ result = self.group_encryption.get_group_info(group_id)
216
+
217
+ return jsonify({
218
+ 'success': True,
219
+ 'data': result
220
+ })
221
+
222
+ except Exception as e:
223
+ return jsonify({'error': str(e)}), 500
224
+
225
+ @self.app.route('/api/groups/<group_id>/messages', methods=['GET'])
226
+ def get_message_history(group_id):
227
+ """الحصول على تاريخ رسائل المجموعة"""
228
+ try:
229
+ limit = request.args.get('limit', 50, type=int)
230
+ messages = self.message_history.get_group_message_history(group_id, limit)
231
+
232
+ # تحويل البيانات الثنائية إلى base64
233
+ encoded_messages = [self._encode_binary_data(msg) for msg in messages]
234
+
235
+ return jsonify({
236
+ 'success': True,
237
+ 'data': {
238
+ 'messages': encoded_messages,
239
+ 'count': len(encoded_messages)
240
+ }
241
+ })
242
+
243
+ except Exception as e:
244
+ return jsonify({'error': str(e)}), 500
245
+
246
+ @self.app.route('/api/groups/<group_id>/key-export/<member_id>', methods=['GET'])
247
+ def export_group_key(group_id, member_id):
248
+ """تصدير مفتاح المجموعة للعضو"""
249
+ try:
250
+ # الحصول على المفتاح العام للعضو من المجموعة
251
+ group_info = self.group_encryption.get_group_info(group_id)
252
+ if member_id not in group_info['members']:
253
+ return jsonify({'error': 'العضو ليس في المجموعة'}), 404
254
+
255
+ member_public_key = self.group_encryption.groups[group_id]['members'][member_id]['public_key']
256
+
257
+ encrypted_key_data = self.group_encryption.export_group_key_for_member(
258
+ group_id,
259
+ member_id,
260
+ member_public_key
261
+ )
262
+
263
+ # تحويل البيانات الثنائية إلى base64
264
+ response_data = self._encode_binary_data(encrypted_key_data)
265
+
266
+ return jsonify({
267
+ 'success': True,
268
+ 'data': response_data
269
+ })
270
+
271
+ except Exception as e:
272
+ return jsonify({'error': str(e)}), 500
273
+
274
+ def _encode_binary_data(self, data: Dict) -> Dict:
275
+ """تحويل البيانات الثنائية إلى base64 للإرسال عبر JSON"""
276
+ encoded_data = {}
277
+
278
+ for key, value in data.items():
279
+ if isinstance(value, bytes):
280
+ encoded_data[key] = base64.b64encode(value).decode('utf-8')
281
+ else:
282
+ encoded_data[key] = value
283
+
284
+ return encoded_data
285
+
286
+ def _decode_binary_data(self, data: Dict) -> Dict:
287
+ """تحويل البيانات من base64 إلى bytes"""
288
+ decoded_data = {}
289
+
290
+ for key, value in data.items():
291
+ if isinstance(value, str) and key in ['iv', 'ciphertext', 'tag', 'encrypted_group_key']:
292
+ try:
293
+ decoded_data[key] = base64.b64decode(value)
294
+ except:
295
+ decoded_data[key] = value
296
+ else:
297
+ decoded_data[key] = value
298
+
299
+ return decoded_data
300
+
301
+ def run(self, host='0.0.0.0', port=5000, debug=False):
302
+ """تشغيل خادم API"""
303
+ self.app.run(host=host, port=port, debug=debug)
304
+
305
+
306
+ # مثال على الاستخدام
307
+ if __name__ == '__main__':
308
+ api = GroupE2EAPI()
309
+ print("تشغيل خادم Group E2E Encryption API...")
310
+ print("الوصول إلى API عبر: http://localhost:5000")
311
+ print("فحص الحالة: http://localhost:5000/api/health")
312
+ api.run(debug=True)
313
+