include plaintext nonce to sent packets

This commit is contained in:
17ms 2023-03-23 03:22:30 +02:00
parent f7a15623c7
commit e5b038dc91
2 changed files with 13 additions and 7 deletions

View File

@ -1,4 +1,4 @@
use super::crypto; use crate::crypto;
use aes_gcm::{aead::consts::U12, aes::Aes256, AesGcm}; use aes_gcm::{aead::consts::U12, aes::Aes256, AesGcm};
use rand::rngs::OsRng; use rand::rngs::OsRng;
use std::error::Error; use std::error::Error;
@ -12,10 +12,10 @@ pub async fn send_bytes(
enc: Option<(&mut AesGcm<Aes256, U12>, &mut OsRng)>, enc: Option<(&mut AesGcm<Aes256, U12>, &mut OsRng)>,
data: &Vec<u8>, data: &Vec<u8>,
) -> Result<(), Box<dyn Error + Send + Sync>> { ) -> Result<(), Box<dyn Error + Send + Sync>> {
let processed = enc.map_or(Ok(data.clone()), |enc| { let data = enc.map_or(Ok(data.clone()), |enc| {
crypto::aes_encrypt(data, enc.0, enc.1) crypto::aes_encrypt(data, enc.0, enc.1)
})?; })?;
writer.write_all(&processed).await?; writer.write_all(&data).await?;
writer.flush().await?; writer.flush().await?;
Ok(()) Ok(())

View File

@ -1,4 +1,4 @@
use super::comms; use crate::comms;
use aes_gcm::{ use aes_gcm::{
aead::{consts::U12, AeadMut}, aead::{consts::U12, AeadMut},
aes::Aes256, aes::Aes256,
@ -34,6 +34,7 @@ pub async fn edh(
let sliced_buf: [u8; 32] = buf[..32].try_into()?; let sliced_buf: [u8; 32] = buf[..32].try_into()?;
let recv_pbk = PublicKey::from(sliced_buf); let recv_pbk = PublicKey::from(sliced_buf);
buf.clear(); buf.clear();
Ok(own_sec.diffie_hellman(&recv_pbk)) Ok(own_sec.diffie_hellman(&recv_pbk))
} }
@ -46,6 +47,7 @@ pub fn aes_cipher(
fn generate_nonce(rng: &mut impl RngCore) -> Nonce<U12> { fn generate_nonce(rng: &mut impl RngCore) -> Nonce<U12> {
let mut nonce = Nonce::default(); let mut nonce = Nonce::default();
rng.fill_bytes(&mut nonce); rng.fill_bytes(&mut nonce);
nonce nonce
} }
@ -55,8 +57,11 @@ pub fn aes_encrypt(
rng: &mut OsRng, rng: &mut OsRng,
) -> Result<Vec<u8>, Box<dyn Error + Send + Sync>> { ) -> Result<Vec<u8>, Box<dyn Error + Send + Sync>> {
let nonce = generate_nonce(rng); let nonce = generate_nonce(rng);
let encrypted = cipher.encrypt(&nonce, data.as_ref()).unwrap(); // TODO: handle error types let encrypted = cipher.encrypt(&nonce, data.as_ref()).unwrap(); // TODO: handle errors
Ok(encrypted) let mut data = nonce.to_vec();
data.extend_from_slice(&encrypted);
Ok(data)
} }
pub fn aes_decrypt( pub fn aes_decrypt(
@ -66,6 +71,7 @@ pub fn aes_decrypt(
let (nonce_bytes, data) = data.split_at(AES_NONCE_SIZE); let (nonce_bytes, data) = data.split_at(AES_NONCE_SIZE);
let decrypted = cipher let decrypted = cipher
.decrypt(Nonce::from_slice(nonce_bytes), data.as_ref()) .decrypt(Nonce::from_slice(nonce_bytes), data.as_ref())
.unwrap(); // TODO: handle error types .unwrap(); // TODO: handle errors
Ok(decrypted) Ok(decrypted)
} }