fastcrypter 2.3.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.
@@ -0,0 +1,285 @@
1
+ """
2
+ 🚀 fastCrypter - Professional Compression and Encryption Library
3
+
4
+ A powerful Python package for secure data compression and encryption
5
+ using modern cryptographic algorithms and compression techniques with
6
+ native C/C++ acceleration for maximum performance.
7
+
8
+ Author: Mmdrza
9
+ Version: 2.0.0
10
+ License: MIT
11
+ """
12
+
13
+ __version__ = "2.3.0"
14
+ __author__ = "Mmdrza"
15
+ __email__ = "pymmdrza@gmail.com"
16
+ __license__ = "MIT"
17
+
18
+ # Core imports
19
+ from .core.compressor import Compressor, CompressionAlgorithmType, CompressionLevel
20
+ from .core.encryptor import Encryptor, EncryptionAlgorithmType
21
+ from .core.key_manager import KeyManager
22
+ from .core.custom_encoder import CustomEncoder
23
+
24
+ # High-level interfaces
25
+ from .secure_compressor import SecureCompressor
26
+ from .file_encryptor import FileEncryptor
27
+ from .advanced_encryptor import AdvancedEncryptor
28
+
29
+ # Enhanced components with native acceleration
30
+ try:
31
+ from .core.enhanced_compressor import EnhancedCompressor
32
+ ENHANCED_AVAILABLE = True
33
+ except ImportError:
34
+ ENHANCED_AVAILABLE = False
35
+
36
+ # Native library support
37
+ try:
38
+ from .native.native_loader import (
39
+ get_native_manager, get_crypto_core, get_hash_algorithms,
40
+ is_native_available, NativeLibraryManager
41
+ )
42
+ NATIVE_SUPPORT = True
43
+ except ImportError:
44
+ NATIVE_SUPPORT = False
45
+
46
+ # Exceptions
47
+ from .exceptions import (
48
+ EncrypterError,
49
+ CompressionError,
50
+ EncryptionError,
51
+ ValidationError,
52
+ KeyError,
53
+ ErrorCodes,
54
+ )
55
+
56
+ __all__ = [
57
+ # Version info
58
+ "__version__",
59
+ "__author__",
60
+ "__email__",
61
+ "__license__",
62
+
63
+ # Core classes
64
+ "Compressor",
65
+ "Encryptor",
66
+ "KeyManager",
67
+ "CustomEncoder",
68
+
69
+ # High-level interfaces
70
+ "SecureCompressor",
71
+ "FileEncryptor",
72
+ "AdvancedEncryptor",
73
+
74
+ # Algorithm types
75
+ "CompressionAlgorithmType",
76
+ "CompressionLevel",
77
+ "EncryptionAlgorithmType",
78
+
79
+ # Exceptions
80
+ "EncrypterError",
81
+ "CompressionError",
82
+ "EncryptionError",
83
+ "ValidationError",
84
+ "KeyError",
85
+ "ErrorCodes",
86
+
87
+ # Feature flags
88
+ "ENHANCED_AVAILABLE",
89
+ "NATIVE_SUPPORT",
90
+ ]
91
+
92
+ # Add enhanced components if available
93
+ if ENHANCED_AVAILABLE:
94
+ __all__.append('EnhancedCompressor')
95
+
96
+ # Add native library components if available
97
+ if NATIVE_SUPPORT:
98
+ __all__.extend([
99
+ 'get_native_manager',
100
+ 'get_crypto_core',
101
+ 'get_hash_algorithms',
102
+ 'is_native_available',
103
+ 'NativeLibraryManager'
104
+ ])
105
+
106
+ # Package metadata
107
+ PACKAGE_INFO = {
108
+ "name": "fastCrypter",
109
+ "version": __version__,
110
+ "description": "Professional compression and encryption library with native C/C++ acceleration",
111
+ "author": __author__,
112
+ "email": __email__,
113
+ "license": __license__,
114
+ "url": "https://github.com/Pymmdrza/fastCrypter",
115
+ "keywords": [
116
+ "encryption", "compression", "security", "cryptography",
117
+ "aes", "chacha20", "rsa", "zlib", "lzma", "brotli",
118
+ "native", "performance", "c++", "custom-encoding", "fast"
119
+ ],
120
+ "features": {
121
+ "enhanced_compressor": ENHANCED_AVAILABLE,
122
+ "native_acceleration": NATIVE_SUPPORT,
123
+ "custom_encoding": True,
124
+ "multiple_algorithms": True,
125
+ "file_encryption": True,
126
+ }
127
+ }
128
+
129
+
130
+ def get_version_info():
131
+ """Get comprehensive version and feature information."""
132
+ info = PACKAGE_INFO.copy()
133
+
134
+ if NATIVE_SUPPORT:
135
+ try:
136
+ manager = get_native_manager()
137
+ native_info = manager.get_info()
138
+ info['native_libraries'] = native_info
139
+ except:
140
+ info['native_libraries'] = {'error': 'Failed to load native library info'}
141
+
142
+ return info
143
+
144
+
145
+ def get_recommended_compressor(password: str, **kwargs):
146
+ """
147
+ Get the recommended compressor based on available features.
148
+
149
+ This function automatically selects the best available compressor:
150
+ - EnhancedCompressor if native libraries are available
151
+ - SecureCompressor as fallback
152
+
153
+ Args:
154
+ password (str): Password for encryption.
155
+ **kwargs: Additional arguments passed to the compressor.
156
+
157
+ Returns:
158
+ Compressor instance (EnhancedCompressor or SecureCompressor).
159
+ """
160
+ if ENHANCED_AVAILABLE and NATIVE_SUPPORT:
161
+ try:
162
+ if is_native_available():
163
+ return EnhancedCompressor(password=password, **kwargs)
164
+ except:
165
+ pass
166
+
167
+ # Fallback to standard compressor
168
+ return SecureCompressor(password=password, **kwargs)
169
+
170
+
171
+ def benchmark_available_features(data_size: int = 1024) -> dict:
172
+ """
173
+ Benchmark all available features and return performance information.
174
+
175
+ Args:
176
+ data_size (int): Size of test data in bytes.
177
+
178
+ Returns:
179
+ dict: Benchmark results for all available features.
180
+ """
181
+ import time
182
+ import secrets
183
+
184
+ results = {
185
+ 'data_size': data_size,
186
+ 'features_tested': [],
187
+ 'performance': {}
188
+ }
189
+
190
+ test_data = secrets.token_bytes(data_size)
191
+ password = "BenchmarkPassword123!"
192
+
193
+ # Test standard compressor
194
+ try:
195
+ compressor = SecureCompressor(password=password)
196
+
197
+ start_time = time.time()
198
+ encrypted = compressor.compress_and_encrypt(test_data)
199
+ decrypted = compressor.decrypt_and_decompress(encrypted)
200
+ end_time = time.time()
201
+
202
+ results['features_tested'].append('SecureCompressor')
203
+ results['performance']['standard'] = {
204
+ 'time': end_time - start_time,
205
+ 'correctness': test_data == decrypted,
206
+ 'compression_ratio': len(encrypted) / len(test_data)
207
+ }
208
+ except Exception as e:
209
+ results['performance']['standard'] = {'error': str(e)}
210
+
211
+ # Test enhanced compressor if available
212
+ if ENHANCED_AVAILABLE:
213
+ try:
214
+ enhanced = EnhancedCompressor(password=password)
215
+
216
+ start_time = time.time()
217
+ encrypted = enhanced.compress_and_encrypt(test_data)
218
+ decrypted = enhanced.decrypt_and_decompress(encrypted)
219
+ end_time = time.time()
220
+
221
+ results['features_tested'].append('EnhancedCompressor')
222
+ results['performance']['enhanced'] = {
223
+ 'time': end_time - start_time,
224
+ 'correctness': test_data == decrypted,
225
+ 'compression_ratio': len(encrypted) / len(test_data),
226
+ 'native_available': enhanced.is_native_available()
227
+ }
228
+
229
+ # Compare performance
230
+ if 'standard' in results['performance']:
231
+ standard_time = results['performance']['standard'].get('time', 0)
232
+ enhanced_time = results['performance']['enhanced']['time']
233
+ if enhanced_time > 0:
234
+ results['performance']['speedup'] = standard_time / enhanced_time
235
+
236
+ except Exception as e:
237
+ results['performance']['enhanced'] = {'error': str(e)}
238
+
239
+ # Test native libraries if available
240
+ if NATIVE_SUPPORT:
241
+ try:
242
+ manager = get_native_manager()
243
+ native_info = manager.get_info()
244
+
245
+ results['features_tested'].append('NativeLibraries')
246
+ results['performance']['native'] = {
247
+ 'available': native_info.get('crypto_core_loaded', False) or native_info.get('hash_algorithms_loaded', False),
248
+ 'crypto_core': native_info.get('crypto_core_loaded', False),
249
+ 'hash_algorithms': native_info.get('hash_algorithms_loaded', False),
250
+ 'platform': native_info.get('platform', 'unknown')
251
+ }
252
+
253
+ except Exception as e:
254
+ results['performance']['native'] = {'error': str(e)}
255
+
256
+ return results
257
+
258
+
259
+ # Package initialization message
260
+ def _show_startup_info():
261
+ """Show package startup information."""
262
+ features = []
263
+
264
+ if ENHANCED_AVAILABLE:
265
+ features.append("Enhanced Compressor")
266
+
267
+ if NATIVE_SUPPORT:
268
+ try:
269
+ if is_native_available():
270
+ features.append("Native Acceleration")
271
+ else:
272
+ features.append("Native Support (libraries not loaded)")
273
+ except:
274
+ features.append("Native Support (error)")
275
+
276
+ if not features:
277
+ features.append("Standard Features")
278
+
279
+ # Only show in debug mode or if explicitly requested
280
+ import os
281
+ if os.environ.get('fastCrypter_SHOW_INFO', '').lower() in ('1', 'true', 'yes'):
282
+ print(f"🚀 fastCrypter v{__version__} loaded with: {', '.join(features)}")
283
+
284
+ # Show startup info if requested
285
+ _show_startup_info()
@@ -0,0 +1,368 @@
1
+ """
2
+ Advanced Encryptor - Professional interface for advanced encryption scenarios.
3
+
4
+ This module provides advanced encryption capabilities with full control
5
+ over algorithms, parameters, and security settings.
6
+ """
7
+
8
+ from typing import Union, Optional, Dict, Any, List
9
+ from .core.compressor import Compressor, CompressionAlgorithmType
10
+ from .core.encryptor import Encryptor, EncryptionAlgorithmType
11
+ from .core.key_manager import KeyManager
12
+ from .algorithms import CompressionAlgorithm, EncryptionAlgorithm
13
+ from .exceptions import EncrypterError, ValidationError, ErrorCodes
14
+
15
+
16
+ class AdvancedEncryptor:
17
+ """
18
+ Advanced encryption interface for professional use.
19
+
20
+ This class provides full control over encryption and compression
21
+ algorithms, security parameters, and advanced features like
22
+ streaming encryption and custom algorithm implementations.
23
+ """
24
+
25
+ def __init__(self,
26
+ encryption_algorithm: Union[EncryptionAlgorithmType, str, EncryptionAlgorithm] = EncryptionAlgorithmType.AES_256_GCM,
27
+ compression_algorithm: Union[CompressionAlgorithmType, str, CompressionAlgorithm] = CompressionAlgorithmType.ZLIB,
28
+ key_derivation_algorithm: str = 'pbkdf2',
29
+ key_derivation_iterations: int = 100000,
30
+ memory_cost: int = 65536,
31
+ parallelism: int = 1,
32
+ auto_select_algorithms: bool = False):
33
+ """
34
+ Initialize the AdvancedEncryptor.
35
+
36
+ Args:
37
+ encryption_algorithm: Encryption algorithm to use.
38
+ compression_algorithm: Compression algorithm to use.
39
+ key_derivation_algorithm: Key derivation function algorithm.
40
+ key_derivation_iterations: Number of KDF iterations.
41
+ memory_cost: Memory cost for Scrypt/Argon2.
42
+ parallelism: Parallelism factor for Argon2.
43
+ auto_select_algorithms: Whether to automatically select best algorithms.
44
+ """
45
+ self.auto_select = auto_select_algorithms
46
+
47
+ # Initialize key manager
48
+ self.key_manager = KeyManager(
49
+ kdf_algorithm=key_derivation_algorithm,
50
+ iterations=key_derivation_iterations,
51
+ memory_cost=memory_cost,
52
+ parallelism=parallelism
53
+ )
54
+
55
+ # Initialize compressor
56
+ if isinstance(compression_algorithm, CompressionAlgorithm):
57
+ # Custom algorithm implementation
58
+ self.custom_compressor = compression_algorithm
59
+ self.compressor = None
60
+ else:
61
+ self.compressor = Compressor(
62
+ algorithm=compression_algorithm,
63
+ auto_select=auto_select_algorithms
64
+ )
65
+ self.custom_compressor = None
66
+
67
+ # Initialize encryptor
68
+ if isinstance(encryption_algorithm, EncryptionAlgorithm):
69
+ # Custom algorithm implementation
70
+ self.custom_encryptor = encryption_algorithm
71
+ self.encryptor = None
72
+ else:
73
+ self.encryptor = Encryptor(
74
+ algorithm=encryption_algorithm,
75
+ derive_key=True
76
+ )
77
+ self.custom_encryptor = None
78
+
79
+ # Store configuration
80
+ self.config = {
81
+ 'encryption_algorithm': encryption_algorithm,
82
+ 'compression_algorithm': compression_algorithm,
83
+ 'key_derivation_algorithm': key_derivation_algorithm,
84
+ 'key_derivation_iterations': key_derivation_iterations,
85
+ 'memory_cost': memory_cost,
86
+ 'parallelism': parallelism,
87
+ 'auto_select_algorithms': auto_select_algorithms,
88
+ }
89
+
90
+ def process(self, data: Union[str, bytes], password: str,
91
+ operation: str = 'encrypt') -> bytes:
92
+ """
93
+ Process data with compression and encryption.
94
+
95
+ Args:
96
+ data: Data to process.
97
+ password: Password for encryption.
98
+ operation: Operation to perform ('encrypt' or 'decrypt').
99
+
100
+ Returns:
101
+ bytes: Processed data.
102
+
103
+ Raises:
104
+ EncrypterError: If processing fails.
105
+ ValidationError: If parameters are invalid.
106
+ """
107
+ if operation not in ['encrypt', 'decrypt']:
108
+ raise ValidationError(
109
+ "Operation must be 'encrypt' or 'decrypt'",
110
+ ErrorCodes.INVALID_CONFIGURATION
111
+ )
112
+
113
+ try:
114
+ if operation == 'encrypt':
115
+ return self._encrypt_process(data, password)
116
+ else:
117
+ return self._decrypt_process(data, password)
118
+
119
+ except Exception as e:
120
+ raise EncrypterError(
121
+ f"Advanced processing failed: {str(e)}",
122
+ details={"operation": operation, "error": str(e)}
123
+ )
124
+
125
+ def _encrypt_process(self, data: Union[str, bytes], password: str) -> bytes:
126
+ """Internal encryption process."""
127
+ # Convert string to bytes if necessary
128
+ if isinstance(data, str):
129
+ data = data.encode('utf-8')
130
+
131
+ # Step 1: Compress data
132
+ if self.custom_compressor:
133
+ compressed_data = self.custom_compressor.compress(data)
134
+ else:
135
+ compressed_data = self.compressor.compress(data)
136
+
137
+ # Step 2: Encrypt compressed data
138
+ if self.custom_encryptor:
139
+ # For custom encryptors, we need to derive the key first
140
+ key, salt = self.key_manager.derive_key(password)
141
+ encrypted_data = self.custom_encryptor.encrypt(compressed_data, key)
142
+ # Add salt to the beginning for custom encryptors
143
+ return salt + encrypted_data
144
+ else:
145
+ return self.encryptor.encrypt(compressed_data, password)
146
+
147
+ def _decrypt_process(self, data: bytes, password: str) -> bytes:
148
+ """Internal decryption process."""
149
+ # Step 1: Decrypt data
150
+ if self.custom_encryptor:
151
+ # For custom encryptors, extract salt and derive key
152
+ salt = data[:16] # Assume 16-byte salt
153
+ encrypted_data = data[16:]
154
+ key, _ = self.key_manager.derive_key(password, salt)
155
+ decrypted_data = self.custom_encryptor.decrypt(encrypted_data, key)
156
+ else:
157
+ decrypted_data = self.encryptor.decrypt(data, password)
158
+
159
+ # Step 2: Decompress decrypted data
160
+ if self.custom_compressor:
161
+ return self.custom_compressor.decompress(decrypted_data)
162
+ else:
163
+ return self.compressor.decompress(decrypted_data)
164
+
165
+ def stream_processor(self, password: str, operation: str = 'encrypt'):
166
+ """
167
+ Create a streaming processor for large data.
168
+
169
+ Args:
170
+ password: Password for encryption.
171
+ operation: Operation to perform ('encrypt' or 'decrypt').
172
+
173
+ Returns:
174
+ StreamProcessor: Streaming processor instance.
175
+ """
176
+ return StreamProcessor(self, password, operation)
177
+
178
+ def benchmark_algorithms(self, test_data: bytes, password: str) -> Dict[str, Dict[str, Any]]:
179
+ """
180
+ Benchmark different algorithm combinations.
181
+
182
+ Args:
183
+ test_data: Data to use for benchmarking.
184
+ password: Password for encryption.
185
+
186
+ Returns:
187
+ Dict[str, Dict[str, Any]]: Benchmark results.
188
+ """
189
+ import time
190
+
191
+ results = {}
192
+
193
+ # Test different compression algorithms
194
+ compression_algos = [
195
+ CompressionAlgorithmType.ZLIB,
196
+ CompressionAlgorithmType.LZMA,
197
+ CompressionAlgorithmType.BROTLI,
198
+ ]
199
+
200
+ # Test different encryption algorithms
201
+ encryption_algos = [
202
+ EncryptionAlgorithmType.AES_256_GCM,
203
+ EncryptionAlgorithmType.AES_256_CBC,
204
+ EncryptionAlgorithmType.CHACHA20_POLY1305,
205
+ ]
206
+
207
+ for comp_algo in compression_algos:
208
+ for enc_algo in encryption_algos:
209
+ combo_name = f"{comp_algo.value}+{enc_algo.value}"
210
+
211
+ try:
212
+ # Create temporary encryptor
213
+ temp_encryptor = AdvancedEncryptor(
214
+ encryption_algorithm=enc_algo,
215
+ compression_algorithm=comp_algo
216
+ )
217
+
218
+ # Measure encryption time
219
+ start_time = time.time()
220
+ encrypted = temp_encryptor.process(test_data, password, 'encrypt')
221
+ encrypt_time = time.time() - start_time
222
+
223
+ # Measure decryption time
224
+ start_time = time.time()
225
+ decrypted = temp_encryptor.process(encrypted, password, 'decrypt')
226
+ decrypt_time = time.time() - start_time
227
+
228
+ # Calculate metrics
229
+ compression_ratio = len(encrypted) / len(test_data)
230
+
231
+ results[combo_name] = {
232
+ 'compression_algorithm': comp_algo.value,
233
+ 'encryption_algorithm': enc_algo.value,
234
+ 'original_size': len(test_data),
235
+ 'compressed_encrypted_size': len(encrypted),
236
+ 'compression_ratio': compression_ratio,
237
+ 'encrypt_time': encrypt_time,
238
+ 'decrypt_time': decrypt_time,
239
+ 'total_time': encrypt_time + decrypt_time,
240
+ 'throughput_mbps': (len(test_data) / (1024 * 1024)) / (encrypt_time + decrypt_time),
241
+ 'success': len(decrypted) == len(test_data),
242
+ }
243
+
244
+ except Exception as e:
245
+ results[combo_name] = {
246
+ 'error': str(e),
247
+ 'success': False,
248
+ }
249
+
250
+ return results
251
+
252
+ def get_security_analysis(self) -> Dict[str, Any]:
253
+ """
254
+ Get security analysis of current configuration.
255
+
256
+ Returns:
257
+ Dict[str, Any]: Security analysis results.
258
+ """
259
+ analysis = {
260
+ 'encryption_strength': 'Unknown',
261
+ 'compression_efficiency': 'Unknown',
262
+ 'key_derivation_strength': 'Unknown',
263
+ 'overall_security_level': 'Unknown',
264
+ 'recommendations': [],
265
+ }
266
+
267
+ # Analyze encryption algorithm
268
+ if self.encryptor:
269
+ algo = self.encryptor.algorithm
270
+ if algo in [EncryptionAlgorithmType.AES_256_GCM, EncryptionAlgorithmType.CHACHA20_POLY1305]:
271
+ analysis['encryption_strength'] = 'Military Grade'
272
+ elif algo == EncryptionAlgorithmType.AES_256_CBC:
273
+ analysis['encryption_strength'] = 'High'
274
+ elif algo == EncryptionAlgorithmType.RSA_4096:
275
+ analysis['encryption_strength'] = 'Very High'
276
+
277
+ # Analyze key derivation
278
+ kdf_algo = self.key_manager.kdf_algorithm
279
+ iterations = self.key_manager.iterations
280
+
281
+ if kdf_algo == 'argon2':
282
+ analysis['key_derivation_strength'] = 'Excellent'
283
+ elif kdf_algo == 'scrypt':
284
+ analysis['key_derivation_strength'] = 'Very Good'
285
+ elif kdf_algo == 'pbkdf2' and iterations >= 100000:
286
+ analysis['key_derivation_strength'] = 'Good'
287
+ else:
288
+ analysis['key_derivation_strength'] = 'Weak'
289
+ analysis['recommendations'].append('Increase KDF iterations or use Argon2')
290
+
291
+ # Overall security assessment
292
+ strengths = [analysis['encryption_strength'], analysis['key_derivation_strength']]
293
+ if all(s in ['Military Grade', 'Excellent', 'Very High'] for s in strengths):
294
+ analysis['overall_security_level'] = 'Maximum'
295
+ elif all(s in ['High', 'Very Good', 'Good'] for s in strengths):
296
+ analysis['overall_security_level'] = 'High'
297
+ else:
298
+ analysis['overall_security_level'] = 'Medium'
299
+ analysis['recommendations'].append('Consider upgrading algorithms for better security')
300
+
301
+ return analysis
302
+
303
+ def get_info(self) -> Dict[str, Any]:
304
+ """
305
+ Get comprehensive information about the AdvancedEncryptor.
306
+
307
+ Returns:
308
+ Dict[str, Any]: Configuration and analysis information.
309
+ """
310
+ info = {
311
+ 'version': '1.0.0',
312
+ 'configuration': self.config,
313
+ 'security_analysis': self.get_security_analysis(),
314
+ }
315
+
316
+ if self.compressor:
317
+ info['compressor_info'] = self.compressor.get_info()
318
+
319
+ if self.encryptor:
320
+ info['encryptor_info'] = self.encryptor.get_info()
321
+
322
+ info['key_manager_info'] = self.key_manager.get_info()
323
+
324
+ return info
325
+
326
+
327
+ class StreamProcessor:
328
+ """
329
+ Streaming processor for large data encryption/decryption.
330
+
331
+ This class allows processing of large data streams without
332
+ loading everything into memory at once.
333
+ """
334
+
335
+ def __init__(self, advanced_encryptor: AdvancedEncryptor,
336
+ password: str, operation: str):
337
+ """
338
+ Initialize the StreamProcessor.
339
+
340
+ Args:
341
+ advanced_encryptor: Parent AdvancedEncryptor instance.
342
+ password: Password for encryption.
343
+ operation: Operation to perform ('encrypt' or 'decrypt').
344
+ """
345
+ self.encryptor = advanced_encryptor
346
+ self.password = password
347
+ self.operation = operation
348
+ self.chunk_size = 64 * 1024 # 64KB chunks
349
+
350
+ def process(self, chunk: bytes) -> bytes:
351
+ """
352
+ Process a data chunk.
353
+
354
+ Args:
355
+ chunk: Data chunk to process.
356
+
357
+ Returns:
358
+ bytes: Processed chunk.
359
+ """
360
+ return self.encryptor.process(chunk, self.password, self.operation)
361
+
362
+ def __enter__(self):
363
+ """Context manager entry."""
364
+ return self
365
+
366
+ def __exit__(self, exc_type, exc_val, exc_tb):
367
+ """Context manager exit."""
368
+ pass