Complete API reference for the fastcrypter library.
High-level interface combining compression and encryption.
class SecureCompressor:
def __init__(
self,
password: str,
compression_algorithm: Union[CompressionAlgorithmType, str] = CompressionAlgorithmType.ZLIB,
compression_level: Union[CompressionLevel, int] = CompressionLevel.BALANCED,
encryption_algorithm: Union[EncryptionAlgorithmType, str] = EncryptionAlgorithmType.AES_256_GCM,
auto_select_compression: bool = True,
kdf_algorithm: str = 'pbkdf2',
kdf_iterations: int = 100000,
custom_charset: Optional[str] = None,
use_fast_extensions: bool = True
)Parameters:
password(str): Password for encryption (minimum 8 characters)compression_algorithm: Compression algorithm to usecompression_level: Compression level (1-9 or CompressionLevel enum)encryption_algorithm: Encryption algorithm to useauto_select_compression(bool): Auto-select best compression algorithmkdf_algorithm(str): Key derivation function ('pbkdf2', 'scrypt', or 'argon2')kdf_iterations(int): Number of KDF iterationscustom_charset(str, optional): Custom character set for encodinguse_fast_extensions(bool): Use C/C++ extensions if available
Methods:
def compress_and_encrypt(
self,
data: Union[str, bytes],
output_format: str = 'binary'
) -> Union[bytes, str]Compress and encrypt data.
Parameters:
data: Data to process (string or bytes)output_format(str): Output format ('binary', 'custom', 'steganographic')
Returns:
- Union[bytes, str]: Encrypted compressed data
Raises:
ValidationError: If input is invalidEncrypterError: If operation fails
def decrypt_and_decompress(
self,
data: Union[bytes, str],
input_format: str = 'binary'
) -> bytesDecrypt and decompress data.
Parameters:
data: Encrypted data to processinput_format(str): Input format ('binary', 'custom', 'steganographic')
Returns:
- bytes: Original decompressed data
def compress_and_encrypt_string(
self,
text: str,
output_format: str = 'binary'
) -> Union[bytes, str]Convenience method for encrypting strings.
def decrypt_and_decompress_to_string(
self,
data: Union[bytes, str],
input_format: str = 'binary',
encoding: str = 'utf-8'
) -> strConvenience method for decrypting to strings.
def validate_password_strength(
self,
password: Optional[str] = None
) -> Dict[str, Any]Validate password strength.
Returns:
- dict: Dictionary with 'strength', 'score', 'checks', and 'recommendations'
def get_info(self) -> Dict[str, Any]Get comprehensive configuration information.
def benchmark_performance(
self,
data_size: int = 1024
) -> Dict[str, Any]Benchmark performance with given data size.
Low-level compression interface.
class Compressor:
def __init__(
self,
algorithm: Union[CompressionAlgorithmType, str] = CompressionAlgorithmType.ZLIB,
level: Union[CompressionLevel, int] = CompressionLevel.BALANCED,
auto_select: bool = False
)Methods:
def compress(self, data: Union[str, bytes]) -> bytesCompress data with metadata header.
def decompress(self, data: bytes) -> bytesDecompress data.
def get_compression_ratio(
self,
original_data: bytes,
compressed_data: bytes
) -> floatCalculate compression ratio.
Low-level encryption interface.
class Encryptor:
def __init__(
self,
algorithm: Union[EncryptionAlgorithmType, str] = EncryptionAlgorithmType.AES_256_GCM,
derive_key: bool = True
)Methods:
def encrypt(
self,
data: Union[str, bytes],
key: Union[str, bytes]
) -> bytesEncrypt data with metadata header.
def decrypt(
self,
data: bytes,
key: Union[str, bytes]
) -> bytesDecrypt data.
def generate_rsa_keypair(self) -> Tuple[bytes, bytes]Generate RSA-4096 key pair (only for RSA algorithm).
Returns:
- Tuple[bytes, bytes]: (private_key_pem, public_key_pem)
def load_rsa_keys(
self,
private_key_pem: Optional[bytes] = None,
public_key_pem: Optional[bytes] = None
)Load RSA keys from PEM format.
Key generation and derivation.
class KeyManager:
def __init__(
self,
kdf_algorithm: str = 'pbkdf2',
iterations: int = 100000,
memory_cost: int = 65536,
parallelism: int = 1
)Methods:
def generate_salt(self, length: int = 16) -> bytesGenerate cryptographically secure random salt.
def generate_key(self, length: int = 32) -> bytesGenerate cryptographically secure random key.
def derive_key(
self,
password: str,
salt: Optional[bytes] = None,
key_length: int = 32
) -> Tuple[bytes, bytes]Derive key from password using configured KDF.
Returns:
- Tuple[bytes, bytes]: (derived_key, salt_used)
def validate_key_strength(
self,
key: bytes,
min_entropy: float = 4.0
) -> boolValidate key strength based on entropy.
def secure_compare(self, a: bytes, b: bytes) -> boolConstant-time comparison of byte strings.
def clear_memory(self, data: bytearray) -> NoneSecurely clear sensitive data from memory.
Custom character set encoding.
class CustomEncoder:
def __init__(
self,
charset: str = "abcdef98Xvbvii",
padding_char: Optional[str] = None
)Methods:
def encode(self, data: Union[bytes, bytearray]) -> strEncode binary data to custom character set.
def decode(self, encoded: str) -> bytesDecode custom encoded string back to binary.
def encode_with_noise(
self,
data: Union[bytes, bytearray],
noise_ratio: float = 0.1
) -> strEncode with random noise characters.
def create_steganographic_text(
self,
data: Union[bytes, bytearray],
template: str = "The quick brown fox jumps over the lazy dog"
) -> strCreate text with hidden data.
def get_charset_info(self) -> dictGet information about current charset.
File encryption operations.
class FileEncryptor:
def __init__(self, password: str, **kwargs)Methods:
def encrypt_file(
self,
input_path: str,
output_path: str
) -> Dict[str, Any]Encrypt a file.
Returns:
- dict: Statistics including sizes and compression ratio
def decrypt_file(
self,
input_path: str,
output_path: str
) -> Dict[str, Any]Decrypt a file.
Returns:
- dict: Statistics including sizes
Enhanced compressor with native acceleration.
class EnhancedCompressor(SecureCompressor):
def __init__(
self,
password: str,
use_native: bool = True,
**kwargs
)Additional Methods:
def is_native_available(self) -> boolCheck if native libraries are loaded and available.
def get_recommended_compressor(password: str, **kwargs)Get the best available compressor (EnhancedCompressor if available, otherwise SecureCompressor).
def get_version_info() -> dictGet comprehensive version and feature information.
def benchmark_available_features(data_size: int = 1024) -> dictBenchmark all available features.
class CompressionAlgorithmType(Enum):
ZLIB = "zlib" # Fast, balanced
LZMA = "lzma" # Best compression
BROTLI = "brotli" # Modern, efficientclass CompressionLevel(Enum):
FASTEST = 1 # Fastest compression
FAST = 3 # Fast compression
BALANCED = 6 # Balanced speed/ratio
BEST = 9 # Best compressionclass EncryptionAlgorithmType(Enum):
AES_256_GCM = "aes-256-gcm" # Recommended
AES_256_CBC = "aes-256-cbc" # With HMAC
CHACHA20_POLY1305 = "chacha20-poly1305" # Modern, fast
RSA_4096 = "rsa-4096" # AsymmetricAll exceptions inherit from EncrypterError.
Base exception class.
class EncrypterError(Exception):
def __init__(
self,
message: str,
error_code: Optional[str] = None,
details: Optional[Any] = None
)Attributes:
message(str): Human-readable error messageerror_code(str): Machine-readable error codedetails: Additional error details
- CompressionError: Compression/decompression errors
- EncryptionError: Encryption/decryption errors
- KeyError: Key management errors
- ValidationError: Input validation errors
- SecurityError: Security-related errors
- FileError: File operation errors
- AlgorithmError: Algorithm-specific errors
- ConfigurationError: Configuration errors
class ErrorCodes:
# Compression
COMPRESSION_FAILED = "COMP_001"
DECOMPRESSION_FAILED = "COMP_002"
UNSUPPORTED_COMPRESSION = "COMP_003"
# Encryption
ENCRYPTION_FAILED = "ENC_001"
DECRYPTION_FAILED = "ENC_002"
UNSUPPORTED_ENCRYPTION = "ENC_003"
INVALID_CIPHERTEXT = "ENC_004"
# Keys
KEY_GENERATION_FAILED = "KEY_001"
KEY_DERIVATION_FAILED = "KEY_002"
INVALID_KEY_FORMAT = "KEY_003"
KEY_TOO_WEAK = "KEY_004"
# Validation
INVALID_INPUT_FORMAT = "VAL_001"
INVALID_INPUT_SIZE = "VAL_002"
CHECKSUM_MISMATCH = "VAL_003"
INTEGRITY_CHECK_FAILED = "VAL_004"
# Security
AUTHENTICATION_FAILED = "SEC_001"
TAMPERING_DETECTED = "SEC_003"
# Configuration
INVALID_CONFIGURATION = "CFG_001"
# Files
FILE_NOT_FOUND = "FILE_001"
FILE_PERMISSION_DENIED = "FILE_002"
FILE_CORRUPTED = "FILE_003"__version__: str # Package version
__author__: str # Author name
__email__: str # Contact email
__license__: str # License type
ENHANCED_AVAILABLE: bool # Enhanced compressor available
NATIVE_SUPPORT: bool # Native libraries available
PACKAGE_INFO: dict # Complete package metadataThe library uses type hints throughout. Key types:
from typing import Union, Optional, Dict, Any, Tuple, List
# Common type aliases
Data = Union[str, bytes]
Key = Union[str, bytes]
Path = str- AES-256: 32 bytes (256 bits)
- ChaCha20: 32 bytes (256 bits)
- RSA-4096: 512 bytes (4096 bits)
- AES-GCM: 12 bytes (96 bits)
- AES-CBC: 16 bytes (128 bits)
- ChaCha20: 12 bytes (96 bits)
- GCM Tag: 16 bytes (128 bits)
- Poly1305 Tag: 16 bytes (128 bits)
- HMAC-SHA256: 32 bytes (256 bits)
Fast Performance:
SecureCompressor(
password="...",
compression_algorithm=CompressionAlgorithmType.ZLIB,
compression_level=3,
encryption_algorithm=EncryptionAlgorithmType.AES_256_GCM,
kdf_algorithm='pbkdf2',
kdf_iterations=100000
)Maximum Compression:
SecureCompressor(
password="...",
compression_algorithm=CompressionAlgorithmType.LZMA,
compression_level=9,
encryption_algorithm=EncryptionAlgorithmType.AES_256_GCM,
kdf_algorithm='pbkdf2',
kdf_iterations=100000
)Maximum Security:
SecureCompressor(
password="...",
compression_algorithm=CompressionAlgorithmType.LZMA,
compression_level=6,
encryption_algorithm=EncryptionAlgorithmType.AES_256_GCM,
kdf_algorithm='argon2',
kdf_iterations=200000
)import fastcrypter
compressor = fastcrypter.SecureCompressor(password="secure_password")
encrypted = compressor.compress_and_encrypt(b"data")
decrypted = compressor.decrypt_and_decompress(encrypted)from fastcrypter import FileEncryptor
encryptor = FileEncryptor(password="password")
encryptor.encrypt_file("input.txt", "output.encrypted")
encryptor.decrypt_file("output.encrypted", "restored.txt")from fastcrypter import CustomEncoder
encoder = CustomEncoder(charset="0123456789abcdef")
encoded = encoder.encode(b"Hello")
decoded = encoder.decode(encoded)from fastcrypter import SecureCompressor, CompressionAlgorithmType, EncryptionAlgorithmType
compressor = SecureCompressor(
password="very_secure_password",
compression_algorithm=CompressionAlgorithmType.BROTLI,
compression_level=6,
encryption_algorithm=EncryptionAlgorithmType.CHACHA20_POLY1305,
kdf_algorithm='argon2',
kdf_iterations=150000
)- Compression Speed: ZLIB > Brotli > LZMA
- Compression Ratio: LZMA > Brotli > ZLIB
- Encryption Speed: ChaCha20 ≈ AES-GCM (with hardware) > AES-CBC
- KDF Security: Argon2 > Scrypt > PBKDF2
- KDF Speed: PBKDF2 > Scrypt > Argon2
Enable native acceleration for best performance:
compressor = fastcrypter.get_recommended_compressor(password="...")SecureCompressor: Not thread-safe, create separate instances per threadCompressor: Not thread-safeEncryptor: Not thread-safeKeyManager: Thread-safe for read operations, not for write operationsCustomEncoder: Thread-safe
Typical memory usage:
- Small data (<1MB): ~2-3x data size
- Large data (>10MB): ~1.5x data size (streaming)
- Native acceleration: Slightly higher memory usage for better speed
For very large files, consider processing in chunks to limit memory usage.