From 7e1cbab6fec0274431ca9f15db7a3ae6531928a4 Mon Sep 17 00:00:00 2001 From: Tony Arcieri Date: Sat, 24 Jan 2026 16:07:38 -0700 Subject: [PATCH] kem: make `Encapsulate` fully infallible Switches from `TryCryptoRng` back to `CryptoRng` for `encapsulate_with_rng`. We originally switched to #2049 with the rationale that the whole trait was fallible anyway, so we might as well handle the RNG errors. But then in #2216 we made the rest of the trait infallible, only using fallibility for the RNG. `Decapsulate` is also now fully infallible, but for cases where we need to handle errors there's a `TryDecapsulate` trait. Prospectively we could do the same thing here, and have a fallible `TryEncapsulate` trait that uses `TryCryptoRng` and handles RNG errors. This PR doesn't attempt to add one because it has some trait design issues around how we convert RNG errors into KEM-specific error types. Closes #2214 --- kem/src/lib.rs | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/kem/src/lib.rs b/kem/src/lib.rs index cd471186b..cbb57226b 100644 --- a/kem/src/lib.rs +++ b/kem/src/lib.rs @@ -14,7 +14,7 @@ pub use common::{ use common::array::{self, ArraySize}; use core::{array::TryFromSliceError, convert::Infallible}; -use rand_core::TryCryptoRng; +use rand_core::CryptoRng; #[cfg(feature = "getrandom")] use common::getrandom::{SysRng, rand_core::UnwrapErr}; @@ -50,17 +50,14 @@ pub trait KemParams { pub trait Encapsulate: KemParams + TryKeyInit + KeyExport { /// Encapsulates a fresh [`SharedSecret`] generated using the supplied random number /// generator `R`. - fn encapsulate_with_rng( - &self, - rng: &mut R, - ) -> Result<(Ciphertext, SharedSecret), R::Error>; + fn encapsulate_with_rng(&self, rng: &mut R) -> (Ciphertext, SharedSecret) + where + R: CryptoRng + ?Sized; /// Encapsulate a fresh shared secret generated using the system's secure RNG. #[cfg(feature = "getrandom")] fn encapsulate(&self) -> (Ciphertext, SharedSecret) { - match self.encapsulate_with_rng(&mut UnwrapErr(SysRng)) { - Ok(ret) => ret, - } + self.encapsulate_with_rng(&mut UnwrapErr(SysRng)) } }