Skip to content

Commit

Permalink
Convert write to no std (WIP)
Browse files Browse the repository at this point in the history
  • Loading branch information
nyonson committed Apr 19, 2024
1 parent dc8439f commit ec51524
Showing 1 changed file with 34 additions and 22 deletions.
56 changes: 34 additions & 22 deletions protocol/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -218,45 +218,57 @@ pub struct PacketWriter {
}

impl PacketWriter {
/// Encrypt plaintext bytes to be sent over the wire.
/// Encrypt plaintext bytes and serialize into a packet to be sent over the wire.
///
/// # Arguments
///
/// - `plaintext` - Plaintext to be encrypted.
/// - `plaintext` - Plaintext content to be encrypted.
/// - `aad` - Optional authentication for the peer, currently only used for the first round of messages.
/// - `packet` - Buffer.
/// - `decoy` - Should the peer ignore this message.
///
/// # Returns
///
/// An encrypted packet to send over the wire.
///
/// # Errors
///
/// Fails if the packet was not encrypted properly.
pub fn prepare_v2_packet(
&mut self,
plaintext: Vec<u8>,
aad: Option<Vec<u8>>,
plaintext: &[u8],
aad: Option<&[u8]>,
packet: &mut [u8],
decoy: bool,
) -> Result<Vec<u8>, Error> {
let mut packet: Vec<u8> = Vec::new();
let mut header: u8 = 0;
if decoy {
header = DECOY;
) -> Result<(), Error> {
// Validate buffer capacity.
if packet.len() < plaintext.len() + LENGTH_BYTES + DECOY_BYTES + TAG_BYTES {
return Err(Error::MessageLengthTooSmall);
}
let mut content_len = [0u8; 3];
content_len.copy_from_slice(&(plaintext.len() as u32).to_le_bytes()[0..LENGTH_BYTES]);
let mut content = vec![header];
content.extend(plaintext);

let plaintext_length = plaintext.len();
let decoy_index = LENGTH_BYTES + DECOY_BYTES - 1;
let plaintext_start_index = decoy_index + 1;
let plaintext_end_index = plaintext_start_index + plaintext_length;

// Set decoy byte.
packet[decoy_index] = if decoy { DECOY } else { 0 };
packet[plaintext_start_index..plaintext_end_index].copy_from_slice(plaintext);

// Encrypt decoy byte and plaintext in place and produce tag.
let auth = aad.unwrap_or_default();
let tag = self
.packet_encoding_cipher
.encrypt(&auth, &mut packet[decoy_index..plaintext_end_index])?;

// Encrypt plaintext length.
let mut content_len = [0u8; 3];
content_len.copy_from_slice(&(plaintext_length as u32).to_le_bytes()[0..LENGTH_BYTES]);
self.length_encoding_cipher
.crypt(&mut content_len)
.expect("encrypt length");
let tag = self.packet_encoding_cipher.encrypt(&auth, &mut content)?;
packet.extend(&content_len);
packet.extend(content);
packet.extend(tag);
Ok(packet)

// Copy over encrypted length and the tag to the final packet (plaintext already encrypted).
packet[0..LENGTH_BYTES].copy_from_slice(&content_len);
packet[plaintext_end_index..(plaintext_end_index + TAG_BYTES)].copy_from_slice(&tag);

Ok(())
}
}

Expand Down

0 comments on commit ec51524

Please sign in to comment.