use pyo3::prelude::*;
use serde::{Deserialize, Serialize};
fn rotor_spec(name: &str) -> Option<(&'static str, &'static [u8])> {
match name {
"I" => Some(("EKMFLGDQVZNTOWYHXUSPAIBRCJ", b"Q")),
"II" => Some(("AJDKSIRUXBLHWTMCQGZNPYFVOE", b"E")),
"III" => Some(("BDFHJLCPRTXVZNYEIWGAKMUSQO", b"V")),
"IV" => Some(("ESOVPZJAYQUIRHXLNFTGKDCMWB", b"J")),
"V" => Some(("VZBRGITYUPSDNHLXAWMJQOFECK", b"Z")),
"VI" => Some(("JPGVOUMFYQBENHZRDKASXLICTW", b"ZM")),
"VII" => Some(("NZJHGRCXMYSWBOUFAIVLPEKQDT", b"ZM")),
"VIII" => Some(("FKQHTLXOCBJSPDZRAMEWNIUYGV", b"ZM")),
_ => None,
}
}
fn reflector_spec(name: &str) -> Option<&'static str> {
match name {
"B" => Some("YRUHQSLDPXNGOKMIEBFZCWVJAT"),
"C" => Some("FVPJIAOYEDRZXWGCTKUQSBNMHL"),
"B-thin" => Some("ENKQAUYWJICOPBLMDXZVFTHRGS"),
"C-thin" => Some("RDOBJNTKVEHMLFCWZAXGYIPSUQ"),
_ => None,
}
}
fn wiring_from_str(s: &str) -> [u8; 26] {
let mut table = [0u8; 26];
for (i, c) in s.bytes().enumerate() {
table[i] = c - b'A';
}
table
}
fn invert_wiring(fwd: &[u8; 26]) -> [u8; 26] {
let mut rev = [0u8; 26];
for (i, &v) in fwd.iter().enumerate() {
rev[v as usize] = i as u8;
}
rev
}
#[pyclass]
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Plugboard {
mapping: [u8; 26],
}
#[pymethods]
impl Plugboard {
#[new]
#[pyo3(signature = (pairs=""))]
pub fn new(pairs: &str) -> PyResult<Self> {
Self::from_pairs(pairs).map_err(pyo3::exceptions::PyValueError::new_err)
}
}
impl Plugboard {
pub fn from_pairs(pairs: &str) -> Result<Self, String> {
let mut mapping: [u8; 26] = std::array::from_fn(|i| i as u8);
let mut used = [false; 26];
if pairs.trim().is_empty() {
return Ok(Self { mapping });
}
let tokens: Vec<&str> = pairs.split_whitespace().collect();
if tokens.len() > 13 {
return Err("Plugboard supports at most 13 pairs".into());
}
for token in &tokens {
let bytes: Vec<u8> = token.bytes().collect();
if bytes.len() != 2 {
return Err(format!(
"Invalid pair '{}': must be exactly 2 letters",
token
));
}
let a = bytes[0].to_ascii_uppercase();
let b = bytes[1].to_ascii_uppercase();
if !a.is_ascii_uppercase() || !b.is_ascii_uppercase() {
return Err(format!("Invalid pair '{}': must be ASCII letters", token));
}
let ai = (a - b'A') as usize;
let bi = (b - b'A') as usize;
if ai == bi {
return Err(format!(
"Invalid pair '{}': cannot pair a letter with itself",
token
));
}
if used[ai] || used[bi] {
return Err(format!(
"Invalid pair '{}': letter already used in another pair",
token
));
}
used[ai] = true;
used[bi] = true;
mapping[ai] = bi as u8;
mapping[bi] = ai as u8;
}
Ok(Self { mapping })
}
#[inline]
pub fn swap(&self, c: u8) -> u8 {
self.mapping[c as usize]
}
}
#[pyclass]
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Rotor {
wiring_fwd: [u8; 26],
wiring_rev: [u8; 26],
notch: Vec<u8>,
position: u8,
ring: u8,
rotor_id: String,
initial_position: u8,
}
#[pymethods]
impl Rotor {
#[new]
pub fn new(rotor_type: &str, position: u8, ring: u8) -> PyResult<Self> {
Self::from_spec(rotor_type, position, ring).map_err(pyo3::exceptions::PyValueError::new_err)
}
}
impl Rotor {
pub fn from_spec(rotor_type: &str, position: u8, ring: u8) -> Result<Self, String> {
let (wiring_str, notch_chars) =
rotor_spec(rotor_type).ok_or_else(|| format!("Unknown rotor type '{}'", rotor_type))?;
let wiring_fwd = wiring_from_str(wiring_str);
let wiring_rev = invert_wiring(&wiring_fwd);
let notch: Vec<u8> = notch_chars.iter().map(|&c| c - b'A').collect();
Ok(Self {
wiring_fwd,
wiring_rev,
notch,
position: position % 26,
ring: ring % 26,
rotor_id: rotor_type.to_string(),
initial_position: position % 26,
})
}
#[inline]
pub fn forward(&self, c: u8) -> u8 {
let shift = (26 + self.position - self.ring) % 26;
let input = (c + shift) % 26;
let output = self.wiring_fwd[input as usize];
(output + 26 - shift) % 26
}
#[inline]
pub fn backward(&self, c: u8) -> u8 {
let shift = (26 + self.position - self.ring) % 26;
let input = (c + shift) % 26;
let output = self.wiring_rev[input as usize];
(output + 26 - shift) % 26
}
#[inline]
pub fn step(&mut self) {
self.position = (self.position + 1) % 26;
}
#[inline]
pub fn is_at_notch(&self) -> bool {
self.notch.contains(&self.position)
}
pub fn reset(&mut self) {
self.position = self.initial_position;
}
}
#[pyclass]
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Reflector {
wiring: [u8; 26],
reflector_id: String,
}
#[pymethods]
impl Reflector {
#[new]
pub fn new(reflector_type: &str) -> PyResult<Self> {
Self::from_spec(reflector_type).map_err(pyo3::exceptions::PyValueError::new_err)
}
}
impl Reflector {
pub fn from_spec(reflector_type: &str) -> Result<Self, String> {
let wiring_str = reflector_spec(reflector_type)
.ok_or_else(|| format!("Unknown reflector type '{}'", reflector_type))?;
Ok(Self {
wiring: wiring_from_str(wiring_str),
reflector_id: reflector_type.to_string(),
})
}
#[inline]
pub fn reflect(&self, c: u8) -> u8 {
self.wiring[c as usize]
}
}
#[pyclass]
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct EnigmaMachine {
rotors: Vec<Rotor>,
reflector: Reflector,
plugboard: Plugboard,
}
#[pymethods]
impl EnigmaMachine {
pub fn process_string(&mut self, input: &str) -> String {
let mut output = String::with_capacity(input.len());
for c in input.bytes() {
if c.is_ascii_alphabetic() {
let idx = c.to_ascii_uppercase() - b'A';
let encrypted = self.encrypt_char(idx);
output.push((encrypted + b'A') as char);
}
}
output
}
pub fn export_key(&self) -> String {
serde_json::to_string_pretty(self).expect("Serialization should not fail")
}
pub fn import_key(&mut self, key: &str) -> PyResult<()> {
let state: EnigmaMachine = serde_json::from_str(key)
.map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("Invalid key: {}", e)))?;
*self = state;
Ok(())
}
pub fn reset(&mut self) {
for rotor in &mut self.rotors {
rotor.reset();
}
}
}
impl EnigmaMachine {
fn step_rotors(&mut self) {
let n = self.rotors.len();
if n >= 3 {
let right = n - 1;
let middle = n - 2;
let left = n - 3;
if self.rotors[middle].is_at_notch() {
self.rotors[middle].step();
self.rotors[left].step();
}
else if self.rotors[right].is_at_notch() {
self.rotors[middle].step();
}
self.rotors[right].step();
} else if n == 2 {
if self.rotors[1].is_at_notch() {
self.rotors[0].step();
}
self.rotors[1].step();
} else if n == 1 {
self.rotors[0].step();
}
}
fn encrypt_char(&mut self, c: u8) -> u8 {
self.step_rotors();
let mut signal = self.plugboard.swap(c);
for rotor in self.rotors.iter().rev() {
signal = rotor.forward(signal);
}
signal = self.reflector.reflect(signal);
for rotor in &self.rotors {
signal = rotor.backward(signal);
}
self.plugboard.swap(signal)
}
}
#[pyclass]
#[derive(Clone, Debug)]
pub struct EnigmaBuilder {
rotors: Vec<Rotor>,
reflector: Option<Reflector>,
plugboard: Option<Plugboard>,
}
#[pymethods]
impl EnigmaBuilder {
#[new]
pub fn new() -> Self {
Self {
rotors: Vec::new(),
reflector: None,
plugboard: None,
}
}
#[pyo3(name = "rotor", signature = (rotor_type, position=0, ring=0))]
pub fn py_rotor(&mut self, rotor_type: &str, position: u8, ring: u8) -> PyResult<()> {
let r = Rotor::from_spec(rotor_type, position, ring)
.map_err(pyo3::exceptions::PyValueError::new_err)?;
self.rotors.push(r);
Ok(())
}
#[pyo3(name = "reflector")]
pub fn py_reflector(&mut self, reflector_type: &str) -> PyResult<()> {
let r = Reflector::from_spec(reflector_type)
.map_err(pyo3::exceptions::PyValueError::new_err)?;
self.reflector = Some(r);
Ok(())
}
#[pyo3(name = "plugboard", signature = (pairs=""))]
pub fn py_plugboard(&mut self, pairs: &str) -> PyResult<()> {
let pb = Plugboard::from_pairs(pairs).map_err(pyo3::exceptions::PyValueError::new_err)?;
self.plugboard = Some(pb);
Ok(())
}
#[pyo3(name = "build")]
pub fn py_build(&self) -> PyResult<EnigmaMachine> {
self.clone()
.build()
.map_err(pyo3::exceptions::PyValueError::new_err)
}
}
impl EnigmaBuilder {
pub fn rotor(mut self, rotor_type: &str, position: u8, ring: u8) -> Self {
let r = Rotor::from_spec(rotor_type, position, ring).expect("Invalid rotor type");
self.rotors.push(r);
self
}
pub fn reflector(mut self, reflector_type: &str) -> Self {
let r = Reflector::from_spec(reflector_type).expect("Invalid reflector type");
self.reflector = Some(r);
self
}
pub fn plugboard(mut self, pairs: &str) -> Self {
let pb = Plugboard::from_pairs(pairs).expect("Invalid plugboard pairs");
self.plugboard = Some(pb);
self
}
pub fn build(self) -> Result<EnigmaMachine, String> {
if self.rotors.is_empty() {
return Err("At least one rotor must be configured".into());
}
let reflector = self
.reflector
.ok_or_else(|| "A reflector must be configured".to_string())?;
let plugboard = self
.plugboard
.unwrap_or_else(|| Plugboard::from_pairs("").unwrap());
Ok(EnigmaMachine {
rotors: self.rotors,
reflector,
plugboard,
})
}
}
impl Default for EnigmaBuilder {
fn default() -> Self {
Self::new()
}
}
#[pymodule]
fn enigmar(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<Plugboard>()?;
m.add_class::<Rotor>()?;
m.add_class::<Reflector>()?;
m.add_class::<EnigmaMachine>()?;
m.add_class::<EnigmaBuilder>()?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn build_default(pos: [u8; 3], ring: [u8; 3], plugboard: &str) -> EnigmaMachine {
EnigmaBuilder::new()
.rotor("I", pos[0], ring[0])
.rotor("II", pos[1], ring[1])
.rotor("III", pos[2], ring[2])
.reflector("B")
.plugboard(plugboard)
.build()
.unwrap()
}
#[test]
fn test_reciprocal_encryption() {
let mut encoder = build_default([0, 0, 0], [0, 0, 0], "");
let mut decoder = build_default([0, 0, 0], [0, 0, 0], "");
let plaintext = "THEQUICKBROWNFOXJUMPSOVERTHELAZYDOG";
let ciphertext = encoder.process_string(plaintext);
assert_ne!(ciphertext, plaintext);
let decrypted = decoder.process_string(&ciphertext);
assert_eq!(decrypted, plaintext);
}
#[test]
fn test_reciprocal_with_plugboard() {
let pairs = "AV BS CG DL FU HZ IN KM OW RX";
let mut encoder = build_default([0, 0, 0], [0, 0, 0], pairs);
let mut decoder = build_default([0, 0, 0], [0, 0, 0], pairs);
let plaintext = "ATTACKATDAWN";
let ciphertext = encoder.process_string(plaintext);
let decrypted = decoder.process_string(&ciphertext);
assert_eq!(decrypted, plaintext);
}
#[test]
fn test_no_letter_encrypts_to_itself() {
let mut machine = build_default([0, 0, 0], [0, 0, 0], "");
for c in 0u8..26 {
let mut m = build_default([0, 0, 0], [0, 0, 0], "");
let input = String::from((c + b'A') as char);
let output = m.process_string(&input);
assert_ne!(input, output, "Letter {} encrypted to itself!", input);
}
let all_a = "AAAAAAAAAAAAAAAAAAAAAAAAAA";
let result = machine.process_string(all_a);
assert!(
!result.contains('A'),
"Found 'A' in output — Enigma should never encrypt a letter to itself"
);
}
#[test]
fn test_double_stepping() {
let mut machine = EnigmaBuilder::new()
.rotor("I", 0, 0)
.rotor("II", 3, 0) .rotor("III", 20, 0) .reflector("B")
.plugboard("")
.build()
.unwrap();
machine.process_string("A");
assert_eq!(machine.rotors[2].position, 21); assert_eq!(machine.rotors[1].position, 3); assert_eq!(machine.rotors[0].position, 0);
machine.process_string("A");
assert_eq!(machine.rotors[2].position, 22); assert_eq!(machine.rotors[1].position, 4); assert_eq!(machine.rotors[0].position, 0);
machine.process_string("A");
assert_eq!(machine.rotors[2].position, 23); assert_eq!(machine.rotors[1].position, 5); assert_eq!(machine.rotors[0].position, 1);
machine.process_string("A");
assert_eq!(machine.rotors[2].position, 24); assert_eq!(machine.rotors[1].position, 5); assert_eq!(machine.rotors[0].position, 1); }
#[test]
fn test_plugboard_validation() {
assert!(Plugboard::from_pairs("AB CD").is_ok());
assert!(Plugboard::from_pairs("").is_ok());
assert!(Plugboard::from_pairs("AB AC").is_err());
assert!(Plugboard::from_pairs("AA").is_err());
let too_many = "AB CD EF GH IJ KL MN OP QR ST UV WX YZ ZA";
assert!(Plugboard::from_pairs(too_many).is_err());
assert!(Plugboard::from_pairs("A1").is_err());
}
#[test]
fn test_plugboard_swap() {
let pb = Plugboard::from_pairs("AB CD").unwrap();
assert_eq!(pb.swap(0), 1); assert_eq!(pb.swap(1), 0); assert_eq!(pb.swap(2), 3); assert_eq!(pb.swap(3), 2); assert_eq!(pb.swap(4), 4); }
#[test]
fn test_key_export_import() {
let mut machine = build_default([5, 10, 15], [1, 2, 3], "AB CD");
let key = machine.export_key();
machine.process_string("TESTING");
machine.import_key(&key).expect("import_key should succeed");
assert_eq!(machine.rotors[0].position, 5);
assert_eq!(machine.rotors[1].position, 10);
assert_eq!(machine.rotors[2].position, 15);
}
#[test]
fn test_non_alpha_input_handling() {
let mut machine = build_default([0, 0, 0], [0, 0, 0], "");
let mut machine2 = build_default([0, 0, 0], [0, 0, 0], "");
let result1 = machine.process_string("HELLO WORLD 123!");
let result2 = machine2.process_string("HELLOWORLD");
assert_eq!(result1, result2);
assert_eq!(result1.len(), 10);
}
#[test]
fn test_lowercase_input() {
let mut m1 = build_default([0, 0, 0], [0, 0, 0], "");
let mut m2 = build_default([0, 0, 0], [0, 0, 0], "");
let upper = m1.process_string("HELLO");
let lower = m2.process_string("hello");
assert_eq!(upper, lower);
}
#[test]
fn test_ring_settings() {
let mut m1 = build_default([0, 0, 0], [0, 0, 0], "");
let mut m2 = build_default([0, 0, 0], [1, 1, 1], "");
let r1 = m1.process_string("AAAA");
let r2 = m2.process_string("AAAA");
assert_ne!(r1, r2);
}
#[test]
fn test_different_rotor_positions() {
let mut m1 = build_default([0, 0, 0], [0, 0, 0], "");
let mut m2 = build_default([1, 2, 3], [0, 0, 0], "");
let r1 = m1.process_string("AAAA");
let r2 = m2.process_string("AAAA");
assert_ne!(r1, r2);
}
#[test]
fn test_builder_missing_reflector() {
let result = EnigmaBuilder::new().rotor("I", 0, 0).build();
assert!(result.is_err());
}
#[test]
fn test_builder_missing_rotors() {
let result = EnigmaBuilder::new().reflector("B").build();
assert!(result.is_err());
}
#[test]
#[should_panic(expected = "Invalid rotor type")]
fn test_builder_invalid_rotor() {
let _ = EnigmaBuilder::new().rotor("INVALID", 0, 0);
}
#[test]
#[should_panic(expected = "Invalid reflector type")]
fn test_builder_invalid_reflector() {
let _ = EnigmaBuilder::new().reflector("INVALID");
}
#[test]
fn test_reset() {
let mut machine = build_default([5, 10, 15], [0, 0, 0], "");
machine.process_string("AAAAAAAAAA");
assert_ne!(machine.rotors[2].position, 15);
machine.reset();
assert_eq!(machine.rotors[0].position, 5);
assert_eq!(machine.rotors[1].position, 10);
assert_eq!(machine.rotors[2].position, 15);
}
#[test]
fn test_known_vector() {
let mut machine = build_default([0, 0, 0], [0, 0, 0], "");
let result = machine.process_string("AAAAAAAAAA");
assert!(!result.contains('A'));
assert_eq!(result.len(), 10);
assert_eq!(result, "BDZGOWCXLT");
}
#[test]
fn test_long_message_reciprocal() {
let msg = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".repeat(10); let pairs = "AV BS CG DL FU HZ IN KM OW RX";
let mut encoder = build_default([7, 13, 22], [3, 5, 11], pairs);
let mut decoder = build_default([7, 13, 22], [3, 5, 11], pairs);
let cipher = encoder.process_string(&msg);
let plain = decoder.process_string(&cipher);
assert_eq!(plain, msg);
}
}