61 lines
2.1 KiB
Rust
61 lines
2.1 KiB
Rust
use crate::utils::{trim_newline};
|
|
/// encrypt & decrypt content with `enc_file` using `XChaCha20Poly1305` and random nonce
|
|
///```rust
|
|
/// let texto = String::from("Esto es una prueba");
|
|
/// println!("{}",&texto);
|
|
/// let ky = String::from("an example very very secret key.");
|
|
/// let key= ky.as_str(); //Plaintext to encrypt
|
|
/// let res_enc = encrypt(&texto,key);
|
|
/// println!("encripty: {}",&res_enc);
|
|
/// let res_dec = decrypt(&res_enc,key);
|
|
/// println!("decrypt: {}",&res_dec);
|
|
///```
|
|
#[must_use]
|
|
pub fn encrypt(text: &str, key: &str) -> String {
|
|
if key.is_empty() {
|
|
return text.to_string();
|
|
}
|
|
//let txt = format!(r#"{}"#, text); //Plaintext to encrypt
|
|
let text_vec = text.as_bytes().to_vec();
|
|
//let key: &str = "an example very very secret key."; //Key will normally be chosen from keymap and provided to the encrypt_chacha() function
|
|
//let text_vec: Vec<u8> = txt_char.to_vec(); //Convert text to Vec<u8>
|
|
//Ciphertext stores the len() of encrypted content, the nonce and the actual ciphertext using bincode
|
|
match enc_file::encrypt_chacha(text_vec, key) {
|
|
//encrypt vec<u8>, returns result(Vec<u8>)
|
|
Ok(ciphertext) => base64::encode(&ciphertext),
|
|
Err(e) => {
|
|
println!("Error encrypt: {}", e);
|
|
String::from("")
|
|
}
|
|
}
|
|
}
|
|
/// decrypt content with `enc_file` using `XChaCha20Poly1305` and random nonce
|
|
#[must_use]
|
|
pub fn decrypt(text: &str, key: &str) -> String {
|
|
if key.is_empty() {
|
|
return text.to_string();
|
|
}
|
|
let mut input = text.to_owned();
|
|
trim_newline(&mut input);
|
|
match base64::decode(&input) {
|
|
Ok(inpt_text) => match enc_file::decrypt_chacha(inpt_text, key) {
|
|
Ok(res) => match String::from_utf8(res) {
|
|
Ok(result) => result,
|
|
Err(e) => {
|
|
println!("Error utf8 decode: {}", e);
|
|
String::from("")
|
|
}
|
|
},
|
|
Err(e) => {
|
|
println!("Error decrypt: {}", e);
|
|
String::from("")
|
|
}
|
|
},
|
|
Err(e) => {
|
|
println!("Error base64 decode: {}", e);
|
|
String::from("")
|
|
}
|
|
}
|
|
// println!("text: {} plain: {}",format!("{:?}", &text), format!("{:?}", plaintext)); //Check that text == plaintext
|
|
}
|