Skip to content
Snippets Groups Projects
Unverified Commit ca0b5ed8 authored by Cheuk Pui Lam's avatar Cheuk Pui Lam
Browse files

added encryption with validity for dummy copies

parent be814d3c
No related branches found
No related tags found
1 merge request!4feat(crypto-utils): using base64 encoding for strings from now on, saving much...
......@@ -12,5 +12,6 @@ hmac = "0.12.1"
log = "0.4.25"
rand = "0.9.0"
rand_chacha = "0.9.0"
regex = "1.11.1"
sha2 = "0.10.8"
tiger = "0.2.1"
......@@ -12,7 +12,6 @@ pub mod chacha {
pub use rand_chacha::ChaCha20Rng;
use base64::prelude::*;
use log::debug;
pub fn encrypt(key: &[u8], plaintext: String) -> Result<String> {
let cipher = XChaCha20Poly1305::new_from_slice(key)?;
......@@ -24,11 +23,51 @@ pub mod chacha {
Ok(BASE64_STANDARD.encode(nonce) + &BASE64_STANDARD.encode(ciphertext))
}
pub fn encrypt_with_action_and_validity(
key: &[u8],
plaintext: String,
action: bool,
validity: bool,
) -> Result<String> {
let encrypt_string = format!("({}:{}:{})", plaintext, action as i64, validity as i64);
encrypt(key, encrypt_string)
}
pub fn decrypt_with_action_and_validity(
key: &[u8],
ciphertext: String,
) -> Result<(String, bool, bool)> {
let plaintext_with_action = decrypt(key, ciphertext)?;
let re = regex::Regex::new(r"\((.+):(\d):(\d)\)").unwrap();
let (plaintext, action, validity) = match re.captures(&plaintext_with_action) {
Some(caps) => Ok((
caps.get(1).map_or("", |m| m.as_str()).to_string(),
caps.get(2).map_or("", |m| m.as_str()).parse::<i64>()? != 0,
caps.get(3).map_or("", |m| m.as_str()).parse::<i64>()? != 0,
)),
None => Err(anyhow!("No match found")),
}?;
Ok((plaintext, action, validity))
}
#[test]
fn test_encrypt_decrypt_with_action_and_validity() {
let plaintext = "hello".to_string();
let action = false;
let validity = true;
let key = XChaCha20Poly1305::generate_key(&mut OsRng).to_vec();
let ciphertext =
encrypt_with_action_and_validity(&key, plaintext.clone(), action, validity).unwrap();
let (decrypted, decrypted_action, decrypted_validity) =
decrypt_with_action_and_validity(&key, ciphertext).unwrap();
assert_eq!(plaintext, decrypted, "Plaintexts do not match");
assert_eq!(action, decrypted_action, "Actions do not match");
assert_eq!(validity, decrypted_validity, "Validities do not match");
}
pub fn decrypt(key: &[u8], ciphertext: String) -> Result<String> {
let cipher = XChaCha20Poly1305::new_from_slice(key)?;
let cipher_bytes = BASE64_STANDARD.decode(ciphertext.clone())?;
let nonce_string = &cipher_bytes[0..24];
debug!("{}, {:?}", nonce_string.len(), nonce_string);
let nonce = XNonce::from_iter(cipher_bytes[0..24].iter().cloned());
let remaining = &cipher_bytes[24..];
let plaintext = match cipher.decrypt(&nonce, remaining) {
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment