Skip to main content

happy_cracking/crypto/
hash.rs

1use anyhow::Result;
2use clap::Subcommand;
3use md5::Md5;
4use sha1::Sha1;
5use sha2::{Digest, Sha256, Sha512};
6
7#[derive(Subcommand)]
8pub enum HashAction {
9    #[command(about = "Generate MD5 hash")]
10    Md5 {
11        #[arg(help = "Input text")]
12        input: String,
13    },
14    #[command(about = "Generate SHA1 hash")]
15    Sha1 {
16        #[arg(help = "Input text")]
17        input: String,
18    },
19    #[command(about = "Generate SHA256 hash")]
20    Sha256 {
21        #[arg(help = "Input text")]
22        input: String,
23    },
24    #[command(about = "Generate SHA512 hash")]
25    Sha512 {
26        #[arg(help = "Input text")]
27        input: String,
28    },
29    #[command(about = "Generate all hashes")]
30    All {
31        #[arg(help = "Input text")]
32        input: String,
33    },
34}
35
36pub fn run(action: HashAction) -> Result<()> {
37    match action {
38        HashAction::Md5 { input } => {
39            println!("{}", md5_hash(&input));
40        }
41        HashAction::Sha1 { input } => {
42            println!("{}", sha1_hash(&input));
43        }
44        HashAction::Sha256 { input } => {
45            println!("{}", sha256_hash(&input));
46        }
47        HashAction::Sha512 { input } => {
48            println!("{}", sha512_hash(&input));
49        }
50        HashAction::All { input } => {
51            println!("MD5:    {}", md5_hash(&input));
52            println!("SHA1:   {}", sha1_hash(&input));
53            println!("SHA256: {}", sha256_hash(&input));
54            println!("SHA512: {}", sha512_hash(&input));
55        }
56    }
57    Ok(())
58}
59
60pub fn md5_hash(input: &str) -> String {
61    let mut hasher = Md5::new();
62    hasher.update(input.as_bytes());
63    format!("{:x}", hasher.finalize())
64}
65
66pub fn sha1_hash(input: &str) -> String {
67    let mut hasher = Sha1::new();
68    hasher.update(input.as_bytes());
69    format!("{:x}", hasher.finalize())
70}
71
72pub fn sha256_hash(input: &str) -> String {
73    let mut hasher = Sha256::new();
74    hasher.update(input.as_bytes());
75    format!("{:x}", hasher.finalize())
76}
77
78pub fn sha512_hash(input: &str) -> String {
79    let mut hasher = Sha512::new();
80    hasher.update(input.as_bytes());
81    format!("{:x}", hasher.finalize())
82}