Skip to main content

happy_cracking/crypto/
base64.rs

1use anyhow::{Context, Result};
2use base64::{Engine, engine::general_purpose::STANDARD};
3use clap::Subcommand;
4
5#[derive(Subcommand)]
6pub enum Base64Action {
7    #[command(about = "Encode to Base64")]
8    Encode {
9        #[arg(help = "Input text")]
10        input: String,
11    },
12    #[command(about = "Decode from Base64")]
13    Decode {
14        #[arg(help = "Base64 encoded string")]
15        input: String,
16    },
17}
18
19pub fn run(action: Base64Action) -> Result<()> {
20    match action {
21        Base64Action::Encode { input } => {
22            println!("{}", encode(&input));
23        }
24        Base64Action::Decode { input } => {
25            println!("{}", decode(&input)?);
26        }
27    }
28    Ok(())
29}
30
31pub fn encode(input: &str) -> String {
32    STANDARD.encode(input.as_bytes())
33}
34
35pub fn decode(input: &str) -> Result<String> {
36    let decoded = STANDARD
37        .decode(input.trim())
38        .context("Failed to decode Base64")?;
39    String::from_utf8(decoded).context("Decoded data is not valid UTF-8")
40}