use crate::cryptography::des::encrypt::Des;
use crate::cryptography::des::f::f;
use crate::cryptography::des::key::{
inverse_key_shift, key_shift, permutated_choice_1, permutated_choice_2,
};
use crate::cryptography::des::permutation::{final_permutation, initial_permutation};
pub fn round(
n: u8,
left_key: &mut u32,
right_key: &mut u32,
left_x: &mut u32,
right_x: &mut u32,
) -> (u32, u32) {
(*left_key, *right_key) = inverse_key_shift(*left_key, *right_key, n);
let key = permutated_choice_2(*left_key, *right_key);
let temp = *right_x;
*right_x = *left_x ^ f(*right_x, key);
*left_x = temp;
(*left_x, *right_x)
}
impl Des {
pub fn decrypt(y: u64, key: u64) -> u64 {
let permuted = initial_permutation(y);
let mut left_x = (permuted >> 32) as u32;
let mut right_x = permuted as u32;
let pc = permutated_choice_1(key);
let mut left_key = (pc >> 28) as u32;
let mut right_key = (pc & 0x0FFFFFFF) as u32;
let mut round_keys = [0u64; 16];
for round in 1..=16 {
(left_key, right_key) = key_shift(left_key, right_key, round);
round_keys[(round - 1) as usize] = permutated_choice_2(left_key, right_key);
}
for &round_key in round_keys.iter().rev() {
let temp = right_x;
right_x = left_x ^ f(right_x, round_key);
left_x = temp;
}
let mut decrypted: u64 = 0;
decrypted |= left_x as u64;
decrypted |= (right_x as u64) << 32;
final_permutation(decrypted)
}
}