Skip to content

Ian-bug/anything-encryption-algorithm

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

16 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

banner

Anything Encryption Algorithm

True entropy encryption from anything your camera sees

Python Tests License

How it works · Install · Usage · Security · Architecture · Development


A hardware-based true entropy encryption system inspired by Cloudflare's Lava Lamp Wall. It captures frames from any camera every 5 seconds, extracts cryptographic entropy from the pixel data, and uses it to seed a CSPRNG that drives AES-256-GCM encryption.

Unlike LavaRand which requires 100 lava lamps, this works with anything your camera can see -- a wall, objects, people, nature, or even the ambient light in a room. Camera sensor noise adds another layer of genuine, irreproducible randomness.

How it works

Computers are deterministic. They cannot produce true randomness on their own. This project bridges that gap by harvesting entropy from the physical world:

 Camera frame (every 5s)          Entropy extraction          Encryption
 ┌─────────────────────┐      ┌────────────────────────┐    ┌─────────────────┐
 │                     │      │                        │    │                 │
 │  Physical world     │─────▶│  SHA-3-512 + BLAKE2b  │───▶│  AES-256-GCM    │
 │  + sensor noise     │      │  + OS entropy mixing   │    │  keys & nonces  │
 │  = true entropy     │      │  = 96 bytes/frame      │    │                 │
 │                     │      │                        │    │                 │
 └─────────────────────┘      └──────────┬─────────────┘    └─────────────────┘
                                          │
                                          ▼
                               ┌────────────────────────┐
                               │  ChaCha20-based CSPRNG  │
                               │  auto-rekey every 100KB │
                               │  continuously reseeded   │
                               └────────────────────────┘

Each frame goes through a multi-stage hashing pipeline:

  1. Raw pixel data is hashed with SHA-3-512
  2. Frame metadata (dimensions, timestamp) is hashed separately with SHA-3-256
  3. OS-provided randomness (os.urandom) is mixed in as defense in depth
  4. Previous frame hash is chained to prevent state compromise
  5. All inputs are combined and hashed again with SHA-3-512 + BLAKE2b
  6. Results are XOR-folded into a 1024-byte entropy pool
  7. Pool output is used to seed a ChaCha20 CSPRNG
  8. The CSPRNG generates AES-256-GCM keys and nonces on demand

Technology Stack

Component Technology Version
Language Python >= 3.10
Computer Vision OpenCV (opencv-python) >= 4.8.0
Numerical Computing NumPy >= 1.24.0
Cryptography cryptography (AES-256-GCM, ChaCha20) >= 41.0.0
Hashing stdlib hashlib (SHA-3-512, SHA-3-256, BLAKE2b, SHAKE-256) built-in
OS Entropy stdlib os.urandom built-in
Web Dashboard Flask >= 3.0.0
Testing pytest + pytest-cov >= 7.4.0
Build System setuptools >= 68.0

Installation

# Clone the repo
git clone https://github.com/your-username/anything-encryption-algorithm.git
cd anything-encryption-algorithm

# Install with pip (editable mode)
pip install -e .

# Or install dev dependencies for testing
pip install -e ".[dev]"

# Or install web dashboard dependencies
pip install -e ".[web]"

Prerequisites: Python 3.10+, a camera (webcam or built-in), OpenCV.

Usage

Encrypt a file

python -m src.cli encrypt --input secret.txt --output secret.enc

Opens the camera, captures 3 frames at 5-second intervals, extracts entropy, runs quality tests, then encrypts with AES-256-GCM.

Decrypt a file

python -m src.cli decrypt --input secret.enc --output secret_decrypted.txt

Generate random bytes from entropy

# Print 64 random bytes as hex
python -m src.cli entropy

# Generate 256 random bytes and save to file
python -m src.cli entropy --bytes 256 --output random.bin

Test entropy quality

python -m src.cli test-entropy

Runs 4 NIST-inspired statistical tests (frequency, runs, block frequency, serial) on 8KB of generated data.

CLI options

Option Default Description
--camera <index> 0 Camera device index
--frames <n> 3 Number of frames to capture
--interval <sec> 5.0 Seconds between captures
--skip-test off Skip entropy quality tests
-v, --verbose off Enable debug logging

Web Dashboard

pip install -e ".[web]"
python server.py

Opens an interactive dashboard at http://127.0.0.1:5000 with:

  • Live camera feed with entropy collection controls
  • Animated signal path pipeline visualization
  • Real-time stats (frames processed, bytes generated, reseed count)
  • Entropy heatmap visualization (256x256 grayscale from random bytes)
  • NIST randomness tests with pass/fail display
  • Random byte generator with hex output and copy button
  • Drag-and-drop file encrypt/decrypt with automatic download

Use as a library

from src.camera_capture import CameraCapture
from src.entropy_extractor import EntropyExtractor
from src.csprng import CSPRNG
from src.encryption import Encryptor

camera = CameraCapture()
extractor = EntropyExtractor()
csprng = CSPRNG()

with camera:
    for _ in range(3):
        frame = camera.capture_frame()
        extractor.extract_entropy(frame)

    seed = extractor.reseed()
    csprng.reseed(seed)

    encryptor = Encryptor(csprng)
    ciphertext = encryptor.encrypt(b"secret message")
    plaintext = encryptor.decrypt(ciphertext)
    assert plaintext == b"secret message"

Key Features

  • Hardware-based entropy -- harvests true randomness from any camera's sensor noise and scene variation
  • Works with anything -- no special hardware needed; any webcam, phone camera, or built-in camera works
  • Multi-stage hashing pipeline -- SHA-3-512 + BLAKE2b with frame chaining and OS entropy mixing
  • ChaCha20 CSPRNG -- auto-rekeys every 100KB of output to limit key exposure
  • AES-256-GCM encryption -- authenticated encryption with integrity verification
  • Entropy quality testing -- 4 NIST-inspired statistical tests validate randomness before use
  • Thread-safe -- locking on all shared mutable state; concurrent generation supported
  • Zero disk footprint -- camera frames are processed in memory and immediately discarded
  • CLI and library -- use from the command line or import as a Python package
  • Web dashboard -- interactive browser-based UI for all operations (Flask)

Project Architecture

src/
├── __init__.py            Package init (version 0.1.0)
├── camera_capture.py      Camera frame acquisition (OpenCV, configurable interval, background thread)
├── entropy_extractor.py   SHA-3-512 + BLAKE2b entropy pipeline with 1KB XOR pool
├── csprng.py              ChaCha20-based CSPRNG with auto-rekey and reseed
├── encryption.py          AES-256-GCM encrypt/decrypt with versioned binary header
├── entropy_test.py        NIST-inspired statistical tests (frequency, runs, block frequency, serial)
└── cli.py                 Command-line interface (encrypt, decrypt, entropy, test-entropy)
server.py                  Flask web server with REST API for the dashboard
web/
└── index.html             Interactive dashboard (single-file HTML/CSS/JS)
tests/
├── test_entropy_extractor.py   12 tests -- extraction, pool, reseed, grayscale support
├── test_csprng.py               18 tests -- generation, reseed, validation, thread safety
├── test_encryption.py           12 tests -- roundtrip, file I/O, AEAD, header format
├── test_entropy_test.py         12 tests -- statistical tests, internal math helpers
└── test_cli.py                  11 tests -- argument parser for all subcommands and flags

Binary format

Encrypted files use a 48-byte header:

┌──────────┬──────────────┬──────────────────┬────────────────────┐
│ Version  │  Nonce (12B)  │  Key (32B)        │  AES-GCM Ciphertext │
│ 4 bytes  │              │                  │  + 16B auth tag     │
└──────────┴──────────────┴──────────────────┴────────────────────┘

Module dependency graph

cli.py
├── camera_capture.py
├── entropy_extractor.py
├── csprng.py
├── entropy_test.py
└── encryption.py ──▶ csprng.py

server.py
├── camera_capture.py
├── entropy_extractor.py
├── csprng.py
├── entropy_test.py
└── encryption.py ──▶ csprng.py

Security

Important

This project is an educational exploration of hardware-based entropy, inspired by Cloudflare's LavaRand. While it uses production-grade primitives (AES-256-GCM, ChaCha20, SHA-3), it has not undergone formal security auditing. Use at your own risk.

What the project does well:

  • AES-256-GCM provides authenticated encryption -- both confidentiality and integrity
  • ChaCha20 CSPRNG with automatic rekeying every 100KB of output limits key exposure window
  • Defense in depth -- camera entropy is mixed with OS entropy (os.urandom), so even if the camera is compromised, the OS source remains
  • Frame chaining -- each frame's hash depends on the previous one, preventing state rollback attacks
  • No frame storage -- camera data is processed in memory and immediately discarded; nothing is written to disk

Things to be aware of:

  • The encryption key is embedded alongside the ciphertext in the output file (versioned binary header). This is by design for convenience, but means anyone with the .enc file can decrypt it. The security comes from the unpredictability of the key, not from keeping it secret.
  • The 5-second interval between frames is a default; shorter intervals capture less real-world variation, longer intervals are slower.
  • Without a physical camera, the system falls back to OS-only entropy.

Development

Running tests

pip install -e ".[dev]"
pytest -v

All 65 tests pass with no camera required (camera tests use synthetic numpy arrays).

Run a single test file

pytest tests/test_csprng.py -v

Run a single test by name

pytest tests/test_csprng.py::TestCSPRNG::test_generate_returns_bytes -v

Run tests by substring match

pytest tests/ -k "test_reseed" -v

Run with coverage

pytest -v --cov=src

Coding standards

  • No inline comments in source code
  • All files start with from __future__ import annotations
  • Import order: stdlib, blank line, third-party, blank line, local src.*
  • All function signatures have type annotations and return types
  • npt.NDArray[np.uint8] for numpy arrays via numpy.typing
  • Classes: PascalCase, functions: snake_case, constants: UPPER_SNAKE_CASE
  • ValueError for invalid arguments, RuntimeError for hardware failures
  • Always chain exceptions with from e
  • threading.Lock for shared mutable state; daemon threads for background work
  • Printf-style formatting for logger calls, f-strings for error messages

Cryptographic conventions

  • Hash functions: hashlib.sha3_512, hashlib.sha3_256, hashlib.blake2b, hashlib.shake_256
  • Symmetric encryption: AES-256-GCM via cryptography.hazmat.primitives.ciphers.aead.AESGCM
  • Stream cipher: ChaCha20 via cryptography.hazmat.primitives.ciphers (16-byte nonce)
  • Key/nonce sizes: AES keys 32 bytes, GCM nonces 12 bytes, ChaCha20 nonces 16 bytes

Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/my-feature)
  3. Write code following the conventions in AGENTS.md
  4. Add tests for new functionality
  5. Run pytest -v and ensure all tests pass
  6. Commit and open a pull request

License

This project is licensed under the MIT License. See LICENSE for details.

About

Camera-based true entropy encryption inspired by Cloudflare LavaRand

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors