Skip to main content

happy_cracking/crypto/
caesar.rs

1use crate::crypto::rot;
2use anyhow::Result;
3use clap::Subcommand;
4
5#[derive(Subcommand)]
6pub enum CaesarAction {
7    #[command(about = "Encrypt with Caesar cipher")]
8    Encrypt {
9        #[arg(help = "Input text")]
10        input: String,
11        #[arg(short, long, help = "Shift amount (0-25)")]
12        shift: u8,
13    },
14    #[command(about = "Decrypt with Caesar cipher")]
15    Decrypt {
16        #[arg(help = "Encrypted text")]
17        input: String,
18        #[arg(short, long, help = "Shift amount (0-25)")]
19        shift: u8,
20    },
21    #[command(about = "Brute force all 26 shifts")]
22    Bruteforce {
23        #[arg(help = "Encrypted text")]
24        input: String,
25    },
26}
27
28pub fn run(action: CaesarAction) -> Result<()> {
29    match action {
30        CaesarAction::Encrypt { input, shift } => {
31            println!("{}", rot::rotate(&input, shift % 26));
32        }
33        CaesarAction::Decrypt { input, shift } => {
34            println!("{}", rot::rotate(&input, (26 - (shift % 26)) % 26));
35        }
36        CaesarAction::Bruteforce { input } => {
37            for shift in 0..26 {
38                println!("Shift {:2}: {}", shift, rot::rotate(&input, shift));
39            }
40        }
41    }
42    Ok(())
43}