diff --git a/sachy-crypto/src/lib.rs b/sachy-crypto/src/lib.rs index 4eae355..309ba67 100644 --- a/sachy-crypto/src/lib.rs +++ b/sachy-crypto/src/lib.rs @@ -143,6 +143,10 @@ impl SendingState<'_> { msg: &mut alloc::vec::Vec, associated_data: &[u8], ) -> Result<(), ProtoError> { + if self.counter.ct_eq(&TransportState::COUNTER_MAX).into() { + return Err(ProtoError); + } + let counter = self.counter.to_be_bytes(); self.transport.aead.encrypt_in_place( @@ -153,11 +157,7 @@ impl SendingState<'_> { self.counter = self.counter.wrapping_add(TransportState::COUNTER_INCR); - if self.counter.ct_eq(&TransportState::COUNTER_MAX).into() { - Err(ProtoError) - } else { - Ok(()) - } + Ok(()) } } @@ -172,6 +172,10 @@ impl ReceivingState<'_> { msg: &mut alloc::vec::Vec, associated_data: &[u8], ) -> Result<(), ProtoError> { + if self.counter.ct_eq(&TransportState::COUNTER_MAX).into() { + return Err(ProtoError); + } + let counter = self.counter.to_be_bytes(); self.transport.aead.decrypt_in_place( @@ -182,11 +186,7 @@ impl ReceivingState<'_> { self.counter = self.counter.wrapping_add(TransportState::COUNTER_INCR); - if self.counter.ct_eq(&TransportState::COUNTER_MAX).into() { - Err(ProtoError) - } else { - Ok(()) - } + Ok(()) } } @@ -272,17 +272,16 @@ impl TransportState { let epstein = self.select_nonce_context(send); - let (head, tail) = trump.split_at_mut(position.len()); - let (first, second) = epstein.split_at(position.len()); + let trump_len = trump.len(); - // XOR the base nonce with position bytes, copying them to the derived nonce - head.iter_mut() - .zip(first) - .zip(position) - .for_each(|((head, ep), pos)| *head = ep ^ pos); + // Copy position bytes into BE format onto derived nonce + trump[trump_len - position.len()..].copy_from_slice(position); - // Copy rest of base nonce into derived nonce - tail.copy_from_slice(second); + // XOR the base nonce onto the derived nonce bytes + trump + .iter_mut() + .zip(epstein) + .for_each(|(trump, epstein)| *trump ^= epstein); trump }