simple_hider/lib.rs
1//! This is the documentation for the simple_hider library.
2//!
3//! # Examples
4//!
5//! ```
6//! use simple_hider::{hide, unhide};
7//!
8//! let text = "Hello";
9//! let salt = "salt";
10//! let encrypted = hide(salt, text);
11//! let decrypted = unhide(salt, encrypted);
12//!
13//! assert_eq!(text, decrypted);
14//! ```
15
16// The text_to_chars() function takes a string as an argument and returns an array of the Unicode character codes of each character in the string.
17fn text_to_chars(text: &str) -> Vec<u32> {
18 text.chars().map(|c| c as u32).collect()
19}
20
21// The apply_salt_to_char() function takes a character code as an argument and returns the result of applying the bitwise XOR operator to the character code and the salt.
22fn apply_salt_to_char(code: u32, salt: &str) -> u32 {
23 let salt_chars = text_to_chars(salt);
24 salt_chars.iter().fold(code, |acc, &b| acc ^ b)
25}
26
27// The hide() function takes a salt and a text as arguments and returns the encoded text.
28pub fn hide(salt: &str, text: &str) -> String {
29 // The byte_hex() function takes a number as an argument and returns the hexadecimal representation of that number as a string.
30 fn byte_hex(n: u32) -> String {
31 format!("{:02x}", n)
32 }
33
34 let mut encoded = String::new();
35
36 for c in text.chars() {
37 let code = c as u32;
38 let code = apply_salt_to_char(code, salt);
39 encoded += &byte_hex(code);
40 }
41
42 return encoded
43}
44
45// The unhide() function takes a salt and an encoded text as arguments and returns the decoded text.
46pub fn unhide(salt: &str, encoded: &str) -> String {
47 let mut decoded = "".to_string();
48
49 for hex in encoded.as_bytes().chunks(2) {
50 let code = u32::from_str_radix(std::str::from_utf8(hex).unwrap(), 16).unwrap();
51 let code = apply_salt_to_char(code, salt);
52 decoded += &std::char::from_u32(code).unwrap().to_string();
53 }
54
55 return decoded
56}