DevelopmentNodeEnvironment_MicrosoftVSCodeDependency_22NodeVersion_Bundle_Clean_Debug_ElectronProfile_EsbuildCompiler_Mountain/IPC/WindServiceHandlers/Encryption/
Encrypt.rs1use base64::{Engine, engine::general_purpose::STANDARD as B64};
9use ring::{
10 aead::{AES_256_GCM, Aad, LessSafeKey, Nonce, UnboundKey},
11 rand::{SecureRandom, SystemRandom},
12};
13use serde_json::{Value, json};
14
15use crate::{IPC::WindServiceHandlers::Utilities::JsonValueHelpers::arg_string, dev_log};
16use super::Key::Fn as DeriveKey;
17
18pub async fn Fn(Arguments:Vec<Value>) -> Result<Value, String> {
19 let Plaintext = arg_string(&Arguments, 0);
20
21 if Plaintext.is_empty() {
22 return Ok(json!(""));
23 }
24
25 let KeyBytes = DeriveKey().map_err(|E| format!("encryption:encrypt unavailable - {E}"))?;
26
27 let UnboundK = UnboundKey::new(&AES_256_GCM, &KeyBytes).map_err(|E| format!("encrypt key: {E:?}"))?;
28
29 let Key = LessSafeKey::new(UnboundK);
30
31 let Rng = SystemRandom::new();
32
33 let mut NonceBytes = [0u8; 12];
34
35 Rng.fill(&mut NonceBytes).map_err(|E| format!("encrypt rng: {E:?}"))?;
36
37 let NonceVal = Nonce::assume_unique_for_key(NonceBytes);
38
39 let mut Data = Plaintext.into_bytes();
40
41 Key.seal_in_place_append_tag(NonceVal, Aad::empty(), &mut Data)
42 .map_err(|E| format!("encrypt seal: {E:?}"))?;
43
44 let mut Out = NonceBytes.to_vec();
45
46 Out.extend_from_slice(&Data);
47
48 dev_log!(
49 "encryption",
50 "encryption:encrypt {} bytes → {} bytes",
51 Out.len() - 12 - 16,
52 Out.len()
53 );
54
55 Ok(json!(B64.encode(&Out)))
56}