๐ Enigmar
High-performance Enigma Machine simulator in Rust with Python bindings.
Enigmar is an educational library that accurately simulates the Wehrmacht Enigma M3/M4 cipher machines, including the famous double-stepping anomaly that made the real machine's behavior notoriously complex. Built with PyO3 for seamless Python interoperability.
โจ Features
- Historically accurate โ Rotors IโVIII, Reflectors B/C/B-thin/C-thin, with correct double-stepping
- Reciprocal encryption โ encrypting and decrypting are the same operation, just like the real Enigma
- No letter self-encryption โ faithfully reproduces the Enigma's critical weakness
- Python bindings โ use from Python via PyO3 with
pip install-ready architecture - Key management โ export/import full machine state as JSON for reproducibility
- Zero-allocation core โ
[u8; 26]lookup tables for O(1) character mapping - Comprehensive validation โ graceful error handling for invalid configurations
๐ฆ Installation
Rust
Add to your Cargo.toml:
[]
= { = "." }
Python
๐ Quick Start
Rust
use EnigmaBuilder;
Python
# Configure
=
=
# Encrypt
=
# Save & restore state
= # JSON snapshot
# restore state
# reset rotor positions
๐ ๏ธ API Reference
EnigmaBuilder
| Method | Description |
|---|---|
new() |
Create an empty builder |
.rotor(type, position, ring) |
Add a rotor (left โ right). Types: "I" โ "VIII" |
.reflector(type) |
Set reflector. Types: "B", "C", "B-thin", "C-thin" |
.plugboard(pairs) |
Set plugboard pairs, e.g. "AB CD EF" (up to 13 pairs) |
.build() |
Build the EnigmaMachine |
EnigmaMachine
| Method | Description |
|---|---|
process_string(input) |
Encrypt/decrypt a message (non-alpha chars silently dropped) |
export_key() |
Serialize machine state to JSON string |
import_key(key) |
Restore machine state from JSON string |
reset() |
Reset rotors to initial positions |
โ๏ธ How It Works
Input โ Plugboard โ Rotor III โ Rotor II โ Rotor I โ Reflector
โ
Output โ Plugboard โ Rotor III โ Rotor II โ Rotor I โโโโ
Double-stepping: Before each character, the right rotor always steps. If the right rotor is at its notch, the middle rotor steps. If the middle rotor is at its notch, both the middle and left rotors step โ this is the "double-stepping" anomaly of the mechanical Enigma.
๐งช Testing
Runs 18 unit tests and 8 doc-tests covering:
- Reciprocal encryption (encrypt โ decrypt = original)
- Double-stepping behavior verification
- Known test vector:
AAAAAAAAAAโBDZGOWCXLT - No letter self-encryption guarantee
- Plugboard validation (duplicates, self-pairs, max 13 pairs)
- Key export/import round-trip
- Long message (260 chars) with plugboard
๐ Project Structure
enigmar/
โโโ Cargo.toml # Dependencies: pyo3, serde, serde_json
โโโ src/
โ โโโ lib.rs # Core library (all components + tests)
โโโ example.py # Python usage example
โโโ README.md
๐ License
MIT