Skip to content

Commit

Permalink
chacha20: Do not copy plaintext into dst_out before we know next keys…
Browse files Browse the repository at this point in the history
…tream can be reliably produced (see #308)
  • Loading branch information
brycx committed Dec 3, 2022
1 parent ff43f5f commit c35b97c
Showing 1 changed file with 23 additions and 7 deletions.
30 changes: 23 additions & 7 deletions src/hazardous/stream/chacha20.rs
Original file line number Diff line number Diff line change
Expand Up @@ -355,13 +355,29 @@ pub fn encrypt(
return Err(UnknownCryptoError);
}

dst_out[..plaintext.len()].copy_from_slice(plaintext);
encrypt_in_place(
secret_key,
nonce,
initial_counter,
&mut dst_out[..plaintext.len()],
)
let mut ctx = ChaCha20::new(secret_key.unprotected_as_bytes(), nonce.as_ref(), true)?;
let mut keystream_block = Zeroizing::new([0u8; CHACHA_BLOCKSIZE]);

for (ctr, (p_block, c_block)) in plaintext
.chunks(CHACHA_BLOCKSIZE)
.zip(dst_out.chunks_mut(CHACHA_BLOCKSIZE))
.enumerate()
{
match initial_counter.checked_add(ctr as u32) {
Some(counter) => {
// See https://github.com/orion-rs/orion/issues/308
ctx.next_produceable()?;

ctx.keystream_block(counter, keystream_block.as_mut());
xor_slices!(p_block, keystream_block.as_mut());
c_block[..p_block.len()]
.copy_from_slice(&keystream_block.as_ref()[..p_block.len()]);
}
None => return Err(UnknownCryptoError),
}
}

Ok(())
}

#[must_use = "SECURITY WARNING: Ignoring a Result can have real security implications."]
Expand Down

0 comments on commit c35b97c

Please sign in to comment.