Skip to content

Commit

Permalink
Try to clean up nonce work
Browse files Browse the repository at this point in the history
  • Loading branch information
nyonson committed Apr 18, 2024
1 parent b96d816 commit afb7fe5
Showing 1 changed file with 9 additions and 12 deletions.
21 changes: 9 additions & 12 deletions protocol/src/fschacha20poly1305.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,20 +65,17 @@ impl FSChaCha20Poly1305 {
/// Increment the message counter and rekey if necessary.
fn rekey(&mut self, aad: &[u8]) -> Result<(), Error> {
if (self.message_counter + 1) % REKEY_INTERVAL == 0 {
let mut rekey_nonce = REKEY_INITIAL_NONCE.to_vec();
let mut counter_div = (self.message_counter / REKEY_INTERVAL)
.to_le_bytes()
.to_vec();
counter_div.extend([0u8; 4]);
let mut rekey_nonce = [0u8; 12];
rekey_nonce[0..4].copy_from_slice(&REKEY_INITIAL_NONCE);

let counter_div = (self.message_counter / REKEY_INTERVAL).to_le_bytes();
rekey_nonce[4..8].copy_from_slice(&counter_div);

let counter_mod = (self.message_counter % REKEY_INTERVAL).to_le_bytes();
let mut nonce = counter_mod.to_vec();
nonce.extend(counter_div);
rekey_nonce.extend(nonce[4..].to_vec());
rekey_nonce[8..12].copy_from_slice(&counter_mod);

let mut plaintext = [0u8; 32];
let cipher = ChaCha20Poly1305::new(
self.key,
rekey_nonce.try_into().expect("Nonce is malformed."),
);
let cipher = ChaCha20Poly1305::new(self.key, rekey_nonce);
cipher
.encrypt(&mut plaintext, Some(aad))
.map_err(|_| Error::Encryption)?;
Expand Down

0 comments on commit afb7fe5

Please sign in to comment.