Skip to main content

devops_armory/crypt/
decipher.rs

1use libsodium_rs::{self, ensure_init};
2use libsodium_rs::crypto_box;
3use std::fs;
4use std::path::Path;
5
6/// Decrypt function
7/// Server secret key, client pub key and nonce key paths need to be provided 
8/// Message is formatted as u8
9pub fn decipher(
10    server_secret_key: &Path,
11    client_pub_key: &Path,
12    nonce_secret_key: &Path,
13    msg: &[u8]
14) -> Result<String, std::io::Error> {
15    // Initialize libsodium
16    ensure_init().expect("Failed to initialize libsodium");
17
18    // Read Server Keypair from files
19    let server_sk_bytes: Vec<u8> = fs::read(server_secret_key).unwrap();
20
21    // Convert Server Keypair bytes into CryptoBox
22    let ssk_box = crypto_box::SecretKey::from_bytes(&server_sk_bytes).unwrap();
23
24    // Read Client Keypair from files 
25    let client_pk_bytes: Vec<u8> = fs::read(client_pub_key).unwrap();
26
27    // Convert Client Keypair bytes into CryptoBox
28    let cpk_box = crypto_box::PublicKey::from_bytes(&client_pk_bytes).unwrap();
29
30    let nonce_from_file= fs::read(nonce_secret_key).unwrap();
31    let s: [u8; 24] = nonce_from_file.try_into().unwrap();
32    let nonce_original = crypto_box::Nonce::from_bytes_exact(s);
33
34    let decrypted = crypto_box::open(&msg, &nonce_original, &cpk_box, &ssk_box).unwrap();
35    let x = String::from_utf8(decrypted);
36    //assert_eq!(message, &decrypted[..]);
37    //println!("{:?}", x.unwrap());
38
39    Ok(x.unwrap())
40
41}