Skip to main content

happy_cracking/crypto/
hex.rs

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