Skip to content

Commit

Permalink
Make ChaCha20::get_single_block return a full, single block
Browse files Browse the repository at this point in the history
While the current uses for `ChaCha20::get_single_block` only
actually want 32 bytes, a ChaCha20 block is 64 bytes, and future
uses may want another 32 bytes, so we can go ahead and return the
whole block when asked for one.
  • Loading branch information
TheBlueMatt committed Jan 16, 2024
1 parent 6777783 commit 224008d
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 7 deletions.
9 changes: 4 additions & 5 deletions lightning/src/crypto/chacha20.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,11 +150,10 @@ mod real_chacha {
}

/// Get one block from a ChaCha stream.
pub fn get_single_block(key: &[u8; 32], nonce: &[u8; 16]) -> [u8; 32] {
pub fn get_single_block(key: &[u8; 32], nonce: &[u8; 16]) -> [u8; 64] {
let mut chacha = ChaCha20 { state: ChaCha20::expand(key, nonce), output: [0u8; BLOCK_SIZE], offset: 64 };
let mut chacha_bytes = [0; 32];
chacha.process_in_place(&mut chacha_bytes);
chacha_bytes
chacha.update();
chacha.output
}

/// Encrypts `src` into `dest` using a single block from a ChaCha stream. Passing `dest` as
Expand Down Expand Up @@ -633,7 +632,7 @@ mod test {
let mut chacha20 = ChaCha20::new(&key, nonce_12bytes);
// Seek its counter to the block at counter_pos.
chacha20.seek_to_block(u32::from_le_bytes(counter_pos.try_into().unwrap()));
let mut block_bytes = [0; 32];
let mut block_bytes = [0; 64];
chacha20.process_in_place(&mut block_bytes);

assert_eq!(ChaCha20::get_single_block(&key, &nonce_16bytes), block_bytes);
Expand Down
10 changes: 8 additions & 2 deletions lightning/src/sign/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1072,7 +1072,10 @@ impl EntropySource for InMemorySigner {
let index = self.rand_bytes_index.get_increment();
let mut nonce = [0u8; 16];
nonce[..8].copy_from_slice(&index.to_be_bytes());
ChaCha20::get_single_block(&self.rand_bytes_unique_start, &nonce)
let block = ChaCha20::get_single_block(&self.rand_bytes_unique_start, &nonce);
let mut half_block = [0; 32];
half_block.copy_from_slice(&block[..32]);
half_block
}
}

Expand Down Expand Up @@ -1634,7 +1637,10 @@ impl EntropySource for KeysManager {
let index = self.rand_bytes_index.get_increment();
let mut nonce = [0u8; 16];
nonce[..8].copy_from_slice(&index.to_be_bytes());
ChaCha20::get_single_block(&self.rand_bytes_unique_start, &nonce)
let block = ChaCha20::get_single_block(&self.rand_bytes_unique_start, &nonce);
let mut half_block = [0; 32];
half_block.copy_from_slice(&block[..32]);
half_block
}
}

Expand Down

0 comments on commit 224008d

Please sign in to comment.