Metadata-Version: 2.4
Name: crypteria
Version: 1.0.3
Summary: A powerful local-first encryption and secure cloud-storage management toolkit in Python.
Author-email: Senani Derradji <derradji.senani.1@gmail.com>
License: MIT
Project-URL: Homepage, https://github.com/senani-derradji/crypteria
Project-URL: Repository, https://github.com/senani-derradji/crypteria
Project-URL: Issues, https://github.com/senani-derradji/crypteria/issues
Keywords: encryption,security,cryptography,cloud,google-drive,backup,aes
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Topic :: Security :: Cryptography
Classifier: Topic :: System :: Filesystems
Classifier: Topic :: System :: Archiving :: Backup
Requires-Python: >=3.8
Description-Content-Type: text/markdown
Requires-Dist: cryptography>=45.0.0
Requires-Dist: keyring>=25.0.0
Requires-Dist: SQLAlchemy>=2.0.0
Requires-Dist: google-api-python-client>=2.0.0
Requires-Dist: google-auth-oauthlib>=1.0.0
Provides-Extra: all
Requires-Dist: pydantic>=2.0.0; extra == "all"
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
Requires-Dist: black>=23.0.0; extra == "dev"
Requires-Dist: ruff>=0.1.0; extra == "dev"
Provides-Extra: docs
Requires-Dist: sphinx>=7.0.0; extra == "docs"
Requires-Dist: myst-parser>=2.0.0; extra == "docs"

# Crypteria

<p align="center">
  <a href="https://pypi.org/project/crypteria/">
    <img src="https://img.shields.io/pypi/v/crypteria.svg" alt="PyPI Version">
  </a>
  <a href="https://pypi.org/project/crypteria/">
    <img src="https://img.shields.io/pypi/py_versions/crypteria.svg" alt="Python Versions">
  </a>
  <a href="https://opensource.org/licenses/MIT">
    <img src="https://img.shields.io/pypi/l/crypteria.svg" alt="License: MIT">
  </a>
</p>

Crypteria is a secure file encryption and cloud backup library for Python. It provides a simple yet powerful API to encrypt files, store encryption keys securely in the system keyring, and synchronize encrypted files to cloud storage providers like Google Drive.

## Overview

Crypteria enables developers to build secure applications that:

- **Encrypt files** using industry-standard AES-256-GCM encryption
- **Store encryption keys** securely in the system keyring
- **Upload encrypted files** to Google Drive automatically
- **Download and decrypt** files seamlessly
- **Track all operations** with built-in logging

## Features

- **AES-256-GCM Encryption** - Military-grade authenticated encryption
- **System Keyring Integration** - Keys stored securely in OS keyring (Windows Credential Manager, macOS Keychain, Linux Secret Service)
- **Google Drive Support** - Built-in cloud storage integration
- **SQLite Database** - Local metadata storage for file tracking
- **Comprehensive Logging** - Detailed operation logs for auditing
- **Integrity Verification** - SHA-256 file verification
- **Multiple Encryption Modes** - AES-256-GCM (recommended) and Fernet (legacy)

## Installation

```bash
pip install crypteria
```

### Requirements

- Python 3.8+
- cryptography
- keyring
- google-api-python-client
- sqlalchemy

## Quick Start

```python
import crypteria

# Encrypt a file locally
encrypted_file, nonce, key = crypteria.encrypt("secret.pdf")
print(f"Encrypted: {encrypted_file}")

# Decrypt the file
decrypted_file = crypteria.decrypt(encrypted_file, key=key, nonce=nonce)
print(f"Decrypted: {decrypted_file}")

# Upload to Google Drive (automatic encryption)
file_id = crypteria.upload("document.pdf", cloud_provider="google_drive")
print(f"Uploaded! File ID: {file_id}")

# Download and decrypt from Google Drive
downloaded = crypteria.download(file_id=file_id)
print(f"Downloaded: {downloaded}")
```

## Architecture

Crypteria is organized into modular components:

```
crypteria/
├── cloud/          # Cloud storage integrations
├── dbs/            # Database and CRUD operations
├── methods/        # Upload and download handlers
├── security/       # Encryption and key management
├── services/       # Logging and utilities
└── utils/          # General utilities
```

### Module Overview

| Module | Description |
|--------|-------------|
| `crypteria.cloud` | Google Drive API integration |
| `crypteria.dbs` | SQLite database with SQLAlchemy |
| `crypteria.methods` | UploadDatacloud and DownloadDatacloud classes |
| `crypteria.security` | AES-256-GCM encryption, key management |
| `crypteria.services` | Logging service |
| `crypteria.utils` | Path management and validation |

## Usage Examples

### Local File Encryption

Encrypt files locally without cloud storage:

```python
import crypteria
from pathlib import Path

# Create a test file
test_file = Path("sensitive_data.json")
test_file.write_text('{"api_key": "secret"}')

# Encrypt with AES-256-GCM (recommended)
encrypted_path, nonce, key = crypteria.encrypt(
    input_path=test_file,
    mode=crypteria.CryptoMode.GCM
)

print(f"Original: {test_file}")
print(f"Encrypted: {encrypted_path}")
print(f"Key stored in keyring: True")
```

### Cloud Upload with Encryption

Upload files to Google Drive with automatic encryption:

```python
import crypteria

# Upload and encrypt to Google Drive
file_id = crypteria.upload(
    file_path="important_document.pdf",
    cloud_provider="google_drive",
    use_advanced_encryption=True  # AES-256-GCM
)

print(f"File uploaded with ID: {file_id}")

# The encryption key is automatically stored in your system keyring
# and will be used for decryption when downloading
```

### Download and Decrypt

Download encrypted files from the cloud:

```python
import crypteria

# Download and decrypt - key is retrieved from keyring automatically
downloaded_path = crypteria.download(
    file_id=123,
    use_advanced_encryption=True
)

print(f"File downloaded and decrypted to: {downloaded_path}")
```

### Using Advanced Security Features

```python
from crypteria.security.crypto import KeyManager, derive_key_from_password
import hashlib

# Generate and manage keys
key_manager = KeyManager()

# Generate a new AES-256 key
new_key = key_manager.generate_key(crypteria.CryptoMode.GCM)

# Store in keyring
key_manager.store_key(new_key, "my_app_key")

# Retrieve later
retrieved_key = key_manager.get_key("my_app_key")

# Derive key from password (PBKDF2)
password = "MySecurePassword123"
derived_key, salt = derive_key_from_password(password)
print(f"Key derived from password: {derived_key.hex()}")
print(f"Salt: {salt.hex()}")
```

### Database Operations

Track file metadata locally:

```python
import crypteria
from crypteria.dbs.crud import get_all_files

# Initialize database
crypteria.init_db()

# List all tracked files
files = crypteria.list_files()
for f in files:
    print(f"ID: {f.id}, Name: {f.file_name}, Provider: {f.providor}")
```

### Logging Configuration

```python
import crypteria

# Use the built-in logger
crypteria.logger.info("Starting upload process")
crypteria.logger.warning("File size exceeds recommended limit")
crypteria.logger.error("Upload failed")
```

## Security Design

### Encryption

Crypteria uses **AES-256-GCM** (Galois/Counter Mode) for authenticated encryption, which provides:

- **Confidentiality**: Only authorized parties can read the data
- **Integrity**: Tampering is detected automatically
- **Authentication**: Confirms the identity of the encrypting party

### Key Management

- Encryption keys are stored in the **system keyring** (not in files)
- Keys are generated using cryptographically secure random number generators
- Support for **PBKDF2** key derivation from passwords
- Each file can have its own unique encryption key

### File Format

Encrypted files contain:
```
[12-byte nonce][ciphertext][authentication tag]
```

The nonce is prepended to the encrypted data for efficient decryption.

## Production Use Cases

### Secure Backup System

```python
import crypteria
from pathlib import Path
import schedule
import time

def backup_secure():
    """Scheduled secure backup to Google Drive"""
    backup_dir = Path("/path/to/important/files")

    for file in backup_dir.glob("*.sql"):
        file_id = crypteria.upload(
            file_path=file,
            cloud_provider="google_drive",
            use_advanced_encryption=True
        )
        print(f"Backed up {file.name} with ID {file_id}")

# Schedule daily backups
schedule.every().day.at("02:00").do(backup_secure)
```

### Encrypted Data Pipeline

```python
import crypteria

def process_sensitive_data(input_file, output_file):
    """Process sensitive data with encryption at rest"""

    # Download latest data
    decrypted = crypteria.download(file_id=123)

    # Process the data
    data = decrypted.read_text()
    processed = transform(data)

    # Save locally with encryption
    output_path = Path(output_file)
    output_path.write_text(processed)

    # Re-encrypt for storage
    encrypted, nonce, key = crypteria.encrypt(output_path)

    # Upload encrypted version
    crypteria.upload(encrypted, use_advanced_encryption=True)
```

### Protecting Application Secrets

```python
from crypteria.security.crypto import KeyManager, CryptoMode

# Generate application encryption key
key_manager = KeyManager()
app_key = key_manager.generate_key(CryptoMode.GCM)
key_manager.store_key(app_key, "production_app_key")

# Use for encrypting configuration files
import crypt
config = {"api_key": "xxx", "password": "yyy"}
encrypted = crypt.encrypt(config, app_key)
```

## Configuration

### Google Drive Setup

1. Go to Google Cloud Console
2. Create a project and enable Google Drive API
3. Download `credentials.json`
4. Place in your project directory

### Database

Crypteria uses SQLite by default. The database is created automatically in:
- **Windows**: `%APPDATA%\Crypteria\files.db`
- **Linux/macOS**: `~/.local/share/Crypteria/files.db`

### Logging

Logs are configured via `crypteria.services.logs_service`:
- Log levels: DEBUG, INFO, WARNING, ERROR
- Default location: AppData folder

## API Reference

### Main Functions

| Function | Description |
|----------|-------------|
| `crypteria.encrypt()` | Encrypt a file |
| `crypteria.decrypt()` | Decrypt a file |
| `crypteria.upload()` | Upload encrypted file to cloud |
| `crypteria.download()` | Download and decrypt from cloud |
| `crypteria.init_db()` | Initialize database |
| `crypteria.list_files()` | List tracked files |

### Classes

| Class | Description |
|-------|-------------|
| `UploadDatacloud` | Handle encrypted uploads |
| `DownloadDatacloud` | Handle encrypted downloads |
| `UniversalCrypto` | Direct encryption operations |
| `KeyManager` | Key generation and storage |

### Enums

| Enum | Description |
|------|-------------|
| `CryptoMode.GCM` | AES-256-GCM (recommended) |
| `CryptoMode.CBC` | AES-256-CBC |
| `CryptoMode.FERNET` | Fernet (legacy) |

## License

MIT License

## Author

Derradji Senani

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

---

<p align="center">Built with 🔒 for secure Python applications</p>
