hutton_rust/
lib.rs

1use std::collections::HashSet; // for removing dupe chars from string
2
3pub fn encrypt(input: &str, password: &str, key: &str, decrypt: bool) -> String {
4    let abc = String::from("abcdefghijklmnopqrstuvwxyz");
5    let mut alphabet_key = create_key(&key, &abc);
6    let mut output = String::new();
7
8    let mut password = String::from(password);
9
10    for (_, input_char) in input.char_indices() {
11        let password_char = password.chars().nth(0).unwrap();
12        let password_number = abc.find(password_char).unwrap();
13        let alphabet_key_char = alphabet_key.chars().nth(0).unwrap();
14        let alphabet_key_number = abc.find(alphabet_key_char).unwrap();
15        let mut shift: i64 = (password_number + alphabet_key_number + 2) as i64;
16
17        if decrypt {
18            shift = -shift;
19        }
20
21        let input_char_number = alphabet_key.find(input_char).unwrap();
22        let output_char_number = (shift + (input_char_number as i64)).rem_euclid(26);
23        let output_char = alphabet_key
24            .chars()
25            .nth(output_char_number as usize)
26            .unwrap();
27        let input_char_number_b = alphabet_key.find(input_char).unwrap();
28
29        password = rotate_string(&password);
30        output += &output_char.to_string();
31        alphabet_key = swap_chars(
32            &alphabet_key,
33            input_char_number_b,
34            output_char_number as usize,
35        );
36    }
37    output
38}
39
40fn rotate_string(input: &str) -> String {
41    let first = input.chars().nth(0).unwrap();
42    let rest = remove_first(&input);
43    rest + &first.to_string()
44}
45
46fn remove_first(input: &str) -> String {
47    let mut output = input.chars();
48    output.next();
49    String::from(output.as_str())
50}
51
52fn swap_chars(input: &str, i: usize, j: usize) -> String {
53    let a = input.chars().nth(i).unwrap();
54    let b = input.chars().nth(j).unwrap();
55    input
56        .chars()
57        .enumerate()
58        .map(|(idx, c)| match idx {
59            idx if idx == i => b,
60            idx if idx == j => a,
61            _ => c,
62        })
63        .collect()
64}
65
66fn create_key(input: &str, abc: &str) -> String {
67    let mut a = input.chars().collect::<Vec<char>>();
68    let mut b = abc.chars().collect::<Vec<char>>();
69    a.append(&mut b);
70
71    let mut uniques = HashSet::new();
72    a.retain(|e| uniques.insert(e.clone()));
73
74    a.into_iter().collect()
75}