Skip to content

Commit

Permalink
update (encpt): create the cypher body
Browse files Browse the repository at this point in the history
  • Loading branch information
lumbrjx committed Jan 21, 2024
1 parent 4128d29 commit 7c52558
Show file tree
Hide file tree
Showing 5 changed files with 150 additions and 36 deletions.
112 changes: 112 additions & 0 deletions src/encpt/encrypt.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
use std::error::Error;
use std::fmt;

use crate::encpt::mapping::switcher::switch_chars;
use crate::encpt::math::matrix::{calc_n, char_to_mtrx, fill_mtrx_gaps, mtrx_to_vecs};
use crate::encpt::math::process::add_to_vec;
use crate::shared::parse::{
flatten_vec, split_by_n, split_string, str2_string_vec, string_vec2_str,
};
use crate::{chr_to_mp, chr_to_mxas, salt_extender, MpType};

#[derive(Debug)]
struct ValueError {
message: String,
}
impl fmt::Display for ValueError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "EncrytionError: {}", self.message)
}
}

impl Error for ValueError {}

struct EncptInfo {
original_length: usize,
salt_short: i8, // 0 : buffer, 1 : salt
mtrx_n: usize,
rd_len: usize,
}
pub fn is_salt_short<'a>(buffer: &'a str, salt: &'a str) -> bool {
if buffer.len() > salt.len() {
return true;
}
return false;
}

pub fn df1t_encrypt(buffer: String, salt: String) -> Result<String, Box<dyn Error>> {
if salt.len() > 16 {
return Err(Box::new(ValueError {
message: "Salt can't be more than 16 char".to_string(),
}));
};

// add original length
//
// .....
//

// Extend the shotest string
let extended: String;
match salt_extender(&salt, &buffer) {
Ok(res) => extended = res,
Err(err) => panic!("{}", err),
}
println!("im extended {}", extended);

// split the buffer and salt into vectors and parse them to mapped version
let mut binding1: Vec<String> = split_string(&buffer);
let mut binding2: Vec<String> = split_string(&salt);

match is_salt_short(&buffer, &salt) {
true => binding2 = split_string(&extended), // + add the shortest in struct
false => binding1 = split_string(&extended),
}

let buffer_vec = chr_to_mp(string_vec2_str(&binding1), MpType::CharMap);
let salt_vec = chr_to_mp(string_vec2_str(&binding2), MpType::SaltMap);
println!("im buffer {:?}", &buffer_vec);
println!("im salt {:?}", &salt_vec);

// Salt and buffer mixing
let mixed: Vec<String>;
match switch_chars(salt_vec, buffer_vec) {
Ok(t) => mixed = t,
Err(e) => panic!("{}", e),
}
println!("im mixed {:?}", &mixed);

// map the mixed vec into mx_as vec version
let binding3 = flatten_vec(mixed);
let mx_version: Vec<&str>;
match chr_to_mxas(string_vec2_str(&binding3)) {
Ok(t) => mx_version = t,
Err(e) => panic!("{}", e),
}
let mtrx_n = calc_n(mx_version.len());
// add mtrx_n to struct

// split the chunk into unstructered matrix
let splitted_empty = split_by_n(mtrx_n, str2_string_vec(mx_version));
// structure the matrix by filling the gaps with 0's
let splitted_filled = fill_mtrx_gaps(mtrx_n, char_to_mtrx(splitted_empty));
// get the green, red, blue vecs from the matrix
let vecs_from_mtrx = mtrx_to_vecs(splitted_filled);
let grn = &vecs_from_mtrx[0];
let rd = &vecs_from_mtrx[1];
let ble = &vecs_from_mtrx[2];
// add mtrx_n to green and blue and the red length to red
let grn_a = add_to_vec(mtrx_n as i32, grn.to_vec());
let rd_a = add_to_vec(rd.len() as i32, rd.to_vec());
let ble_a = add_to_vec(mtrx_n as i32, ble.to_vec());
// create a new matrix of the new values
let parsed_mtrx: Vec<Vec<String>> = vec![grn_a, rd_a, ble_a]
.iter()
.map(|c| flatten_vec(c.iter().map(|&c| c.to_string()).collect()))
.collect();
// faltten the matrix
let flat_mtrx: Vec<String> = parsed_mtrx.into_iter().flatten().collect();
println!("to string {:?}", flat_mtrx);
// println!("blue {:?}", ble_a);
Ok("done".to_string())
}
31 changes: 14 additions & 17 deletions src/encpt/mapping/mapper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ pub enum MpType {
}

// map strings to vectors
pub fn chr_to_mp(vc: Vec<&str>, mpt: MpType) -> Result<Vec<&str>, &str> {
pub fn chr_to_mp(vc: Vec<&str>, mpt: MpType) -> Vec<&str> {
let mut result: Vec<&str> = vec![];
let mpp: [[&str; 3]; 85];
match mpt {
Expand All @@ -25,11 +25,8 @@ pub fn chr_to_mp(vc: Vec<&str>, mpt: MpType) -> Result<Vec<&str>, &str> {
}
}
}
if result.len() != vc.len() {
Err("No matching characters found")
} else {
Ok(result)
}

result
}

pub fn chr_to_mxas(vc: Vec<&str>) -> Result<Vec<&str>, &str> {
Expand Down Expand Up @@ -77,28 +74,28 @@ impl ExtValue {
}
}

pub fn salt_extender(salt: String, password: String) -> Result<String, Box<dyn Error>> {
pub fn salt_extender(salt: &str, password: &str) -> Result<String, Box<dyn Error>> {
if salt.is_empty() || password.is_empty() {
return Err(Box::new(EmptyValueError));
}

if salt.len() > password.len() {
let res = ExtValue {
longer: salt,
shorter: password,
longer: salt.to_string(),
shorter: password.to_string(),
};
return Ok(res.ext_data());
}

if salt.len() < password.len() {
let res = ExtValue {
longer: password,
shorter: salt,
longer: password.to_string(),
shorter: salt.to_string(),
};
return Ok(res.ext_data());
}

Ok(salt)
Ok(salt.to_string())
}

#[cfg(test)]
Expand All @@ -108,13 +105,13 @@ mod tests {
#[test]
fn try_char() {
let res = chr_to_mp(vec!["A", "B", "C"], MpType::CharMap);
assert_eq!(res, Ok(vec!["Av", "bQ", "TG"]))
assert_eq!(res, vec!["Av", "bQ", "TG"])
}
#[test]
fn salt_extender_longer() {
let longer = String::from("abc");
let shorter = String::from("dsdfsqdfsqdff");
match salt_extender(longer.clone(), shorter.clone()) {
match salt_extender(&longer, &shorter) {
Ok(result) => {
let expected = String::from("abcabcabcabca");
assert_eq!(result, expected);
Expand All @@ -127,7 +124,7 @@ mod tests {
fn salt_extender_shorter() {
let longer = String::from("abc");
let shorter = String::from("dsdfsqdfsqdff");
match salt_extender(shorter.clone(), longer.clone()) {
match salt_extender(&shorter, &longer) {
Ok(result) => {
let expected = String::from("abcabcabcabca");
assert_eq!(result, expected);
Expand All @@ -139,7 +136,7 @@ mod tests {
fn salt_extender_even() {
let longer = String::from("dsdfsqdfsqdff");
let shorter = String::from("dsdfsqdfsqdff");
match salt_extender(shorter.clone(), longer.clone()) {
match salt_extender(&shorter, &longer) {
Ok(result) => {
let expected = String::from("dsdfsqdfsqdff");
assert_eq!(result, expected);
Expand All @@ -153,7 +150,7 @@ mod tests {
fn salt_extender_empty() {
let longer = String::from("");
let shorter = String::from("");
match salt_extender(shorter.clone(), longer.clone()) {
match salt_extender(&shorter, &longer) {
Ok(result) => {
let expected = String::from("dsdfsqdfsqdff");
assert_eq!(result, expected);
Expand Down
11 changes: 6 additions & 5 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::{
encpt::{
encrypt::df1t_encrypt,
mapping::{
construct::{self, construct_str},
mapper::*,
Expand All @@ -21,6 +22,7 @@ mod shared {
pub mod parse;
}
mod encpt {
pub mod encrypt;
pub mod math {
pub mod matrix;
pub mod process;
Expand Down Expand Up @@ -73,9 +75,8 @@ fn main() {
// println!("{:?}", d);
// }
// Example usage
let dxxy = vec!["abc".to_string(), "def".to_string(), "ghi".to_string()];
let info = vec!["12".to_string(), "34".to_string(), "56".to_string()];

let result = construct_str(dxxy.clone(), info.clone());
println!("Result: {}", result);
let salt = "ABCDER";
let password = "SUPER";
let res = df1t_encrypt(password.to_owned(), salt.to_owned());
println!("{}", res.unwrap())
}
20 changes: 10 additions & 10 deletions src/maps/nums.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
pub const NUM_MAP: [[&'static str; 2]; 10] = [
["0", "H*d"],
["1", "4(g"],
["2", "p:5"],
["3", "ddc"],
["4", "mmH"],
["5", "*d/"],
["6", "mkl"],
["7", "65d"],
["8", "II-"],
["9", "mp*"],
["0", "H"],
["1", "("],
["2", "2"],
["3", "c"],
["4", "8"],
["5", "*"],
["6", "/"],
["7", "6"],
["8", "I"],
["9", "m"],
];
12 changes: 8 additions & 4 deletions src/shared/parse.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
pub fn split_string(input: String) -> Vec<String> {
let result: Vec<String> = input.chars().map(|c| c.to_string()).collect();
pub fn split_string(input: &str) -> Vec<String> {
let result: Vec<String> = input.to_string().chars().map(|c| c.to_string()).collect();
result
}

Expand All @@ -21,6 +21,10 @@ pub fn str2_string_vec(nsrd: Vec<&str>) -> Vec<String> {
nsrd_as_strings
}

pub fn string_vec2_str(nsrd: &[String]) -> Vec<&str> {
nsrd.iter().map(|s| s.as_str()).collect()
}

pub fn split_by_n(n: usize, chunk: Vec<String>) -> Vec<Vec<String>> {
let mut split_vectors: Vec<Vec<String>> = chunk.chunks(n).map(|chunk| chunk.to_vec()).collect();
if split_vectors.len() < n {
Expand Down Expand Up @@ -55,15 +59,15 @@ mod tests {
fn parse_a_string() {
let string = "sqdf 45h df";
let result = vec!["s", "q", "d", "f", " ", "4", "5", "h", " ", "d", "f"];
let splitted = split_string(string.to_string());
let splitted = split_string(string);

assert_eq!(result, splitted);
}

#[test]
fn split_string_then_restor_it() {
let string = "super secret 8 t8 --y strin_g=";
let splitted = split_string(string.to_string());
let splitted = split_string(string);
let joined = join_string(splitted);
assert_eq!(joined, string);
}
Expand Down

0 comments on commit 7c52558

Please sign in to comment.