This commit is contained in:
2016-12-05 10:20:55 +01:00
parent 082c97fed9
commit a93c2ec7f8
3 changed files with 197 additions and 0 deletions

109
2016/05/src/main.rs Normal file
View File

@@ -0,0 +1,109 @@
extern crate crypto;
use std::u64;
use crypto::md5::Md5;
use crypto::digest::Digest;
struct Hasher {
md5: Md5,
index: u64,
secret: String
}
impl Hasher {
pub fn new(secret: &str) -> Self {
Hasher {
md5: Md5::new(),
index: 0,
secret: String::from(secret)
}
}
}
impl Iterator for Hasher {
type Item = String;
fn next(&mut self) -> Option<String> {
let input = format!("{}{}", self.secret, self.index);
self.md5.reset();
self.md5.input(input.as_bytes());
self.index += 1;
Some(self.md5.result_str())
}
}
fn main() {
let password = generate_week_password("ojvtpuvg");
println!("week_password={}", password);
let password = generate_strong_password("ojvtpuvg");
println!("strong_password={}", password);
}
pub fn generate_week_password(sector_id: &str) -> String {
Hasher::new(sector_id)
.filter(|x| x.starts_with("00000"))
.map(|x| x.as_bytes()[5] as char)
.take(8)
.collect::<String>()
}
pub fn generate_strong_password(sector_id: &str) -> String {
let iter = Hasher::new(sector_id)
.filter(|x| x.starts_with("00000"))
.filter_map(|x| {
let bytes = x.as_bytes();
if (bytes[5] as char) < '8' {
Some(((bytes[5] - 48) as usize, bytes[6] as char))
} else {
None
}
});
let mut password: Vec<Option<char>> = vec![None; 8];
let mut i = 0;
for (pos, ch) in iter {
if password[pos].is_some() {
continue;
}
password[pos] = Some(ch);
i += 1;
if i >= 8 {
break;
}
}
password.iter()
.filter_map(|x| *x)
.collect::<String>()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn example_01() {
assert_eq!(String::from("18f47a30"), generate_week_password("abc"));
}
#[test]
fn example_02() {
assert_eq!(String::from("05ace8e3"), generate_strong_password("abc"));
}
}