Skip to main content

devops_armory/crypt/
cipher.rs

1use libsodium_rs::{self, ensure_init};
2use libsodium_rs::crypto_box;
3use std::fs;
4use std::path::Path;
5
6/// Encrypt function
7/// Server pub key, client secret key and nonce key paths need to be provided 
8/// Message is formatted as u8
9pub fn cipher(
10    server_pub_key: &Path,
11    client_secret_key: &Path,
12    nonce_secret_key: &Path,
13    msg: &[u8]
14) -> Result <Vec<u8>, std::io::Error> {
15    // Initialize libsodium
16    ensure_init().expect("Failed to initialize libsodium");
17
18    // Read Server publickey from files
19    let server_pk_bytes: Vec<u8> = fs::read(server_pub_key).unwrap_or_default();
20
21    // Convert Server publickey bytes into CryptoBox
22    let spk_box = crypto_box::PublicKey::from_bytes(&server_pk_bytes).unwrap();
23
24    // Read Client secret key from files 
25    let client_sk_bytes: Vec<u8> = fs::read(client_secret_key).unwrap_or_default();
26
27    // Convert Client secret key bytes into CryptoBox
28    let csk_box = crypto_box::SecretKey::from_bytes(&client_sk_bytes).unwrap();
29
30    // Read nonce data from file and convert it to Nonce struct
31    let nonce_from_file= fs::read(nonce_secret_key).unwrap_or_default();
32    let s: [u8; 24] = nonce_from_file.try_into().unwrap_or_default();
33    let nonce_original = crypto_box::Nonce::from_bytes_exact(s);
34
35    // Encrypt message
36    let message = msg;
37    let ciphertext = crypto_box::seal(message, &nonce_original, &spk_box, &csk_box).unwrap_or_default();
38    
39    Ok(ciphertext)
40
41}