l6kyu/
algorithms.rs

1//!
2//! Modules categorized by Codewars labels - 6kyu *** Algorithms ***
3//!
4
5use md5::{Digest, Md5};
6use shared::kata::*;
7
8/// Given is a md5 hash of a five digits long PIN. It is given as string.
9/// Your task is to return the cracked PIN as string.
10/// # Example
11/// ``` crack("827ccb0eea8a706c4c34a16891f84e7b"); ``` <br>
12/// returns Ok(12345)
13pub fn crack(string: String) -> Result<i32, ()> {
14    let kata = Kata {
15        level: Level::L6kyu,
16        tags: vec![Tag::Algorithms, Tag::Cryptography],
17        description: String::from("Crack the PIN"),
18    };
19
20    println!(
21        "Level: {:?}, Tags: {:?}, Description: {}",
22        kata.level, kata.tags, kata.description
23    );
24
25    let mut pin = String::new();
26
27    for i in 0..100000 {
28        pin = format!("{:05}", i);
29
30        let mut hasher = Md5::new();
31        hasher.update(pin.as_bytes());
32        let result = hasher.finalize();
33        let pin_hash = hex::encode(result);
34
35        if pin_hash == string {
36            break;
37        }
38    }
39
40    Ok(pin.parse().expect("not a number"))
41}