Skip to content

Commit 35f1ab1

Browse files
committed
convert internals to TryCryptoRng
1 parent 33089e9 commit 35f1ab1

File tree

15 files changed

+108
-136
lines changed

15 files changed

+108
-136
lines changed

Cargo.lock

Lines changed: 1 addition & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,3 +79,7 @@ crypto-bigint = { git = "https://github.com/RustCrypto/crypto-bigint.git" }
7979

8080
# https://github.com/entropyxyz/crypto-primes/pull/74
8181
crypto-primes = { git = "https://github.com/entropyxyz/crypto-primes.git" }
82+
83+
# https://github.com/RustCrypto/traits/pull/1765
84+
# https://github.com/RustCrypto/traits/pull/1766
85+
signature = { git = "https://github.com/RustCrypto/traits.git" }

src/algorithms/generate.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ pub struct RsaPrivateKeyComponents {
3131
///
3232
/// [1]: https://patents.google.com/patent/US4405829A/en
3333
/// [2]: http://www.cacr.math.uwaterloo.ca/techreports/2006/cacr2006-16.pdf
34-
pub(crate) fn generate_multi_prime_key_with_exp<R: CryptoRng>(
34+
pub(crate) fn generate_multi_prime_key_with_exp<R: CryptoRng + ?Sized>(
3535
rng: &mut R,
3636
nprimes: usize,
3737
bit_size: usize,
@@ -120,7 +120,7 @@ pub(crate) fn generate_multi_prime_key_with_exp<R: CryptoRng>(
120120
})
121121
}
122122

123-
fn generate_prime_with_rng<R: CryptoRng>(rng: &mut R, bit_length: u32) -> BoxedUint {
123+
fn generate_prime_with_rng<R: CryptoRng + ?Sized>(rng: &mut R, bit_length: u32) -> BoxedUint {
124124
sieve_and_find(
125125
rng,
126126
SmallPrimesSieveFactory::new(bit_length, SetBits::TwoMsb),

src/algorithms/oaep.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use alloc::boxed::Box;
44
use alloc::vec::Vec;
55

66
use digest::{Digest, DynDigest, FixedOutputReset};
7-
use rand_core::CryptoRng;
7+
use rand_core::TryCryptoRng;
88
use subtle::{Choice, ConditionallySelectable, ConstantTimeEq, CtOption};
99
use zeroize::Zeroizing;
1010

@@ -19,7 +19,7 @@ use crate::errors::{Error, Result};
1919
const MAX_LABEL_LEN: u64 = 1 << 61;
2020

2121
#[inline]
22-
fn encrypt_internal<R: CryptoRng + ?Sized, MGF: FnMut(&mut [u8], &mut [u8])>(
22+
fn encrypt_internal<R: TryCryptoRng + ?Sized, MGF: FnMut(&mut [u8], &mut [u8])>(
2323
rng: &mut R,
2424
msg: &[u8],
2525
p_hash: &[u8],
@@ -35,7 +35,7 @@ fn encrypt_internal<R: CryptoRng + ?Sized, MGF: FnMut(&mut [u8], &mut [u8])>(
3535

3636
let (_, payload) = em.split_at_mut(1);
3737
let (seed, db) = payload.split_at_mut(h_size);
38-
rng.fill_bytes(seed);
38+
rng.try_fill_bytes(seed).map_err(|_| Error::Rng)?;
3939

4040
// Data block DB = pHash || PS || 01 || M
4141
let db_len = k - h_size - 1;
@@ -57,7 +57,7 @@ fn encrypt_internal<R: CryptoRng + ?Sized, MGF: FnMut(&mut [u8], &mut [u8])>(
5757
///
5858
/// [PKCS#1 OAEP]: https://datatracker.ietf.org/doc/html/rfc8017#section-7.1
5959
#[inline]
60-
pub(crate) fn oaep_encrypt<R: CryptoRng + ?Sized>(
60+
pub(crate) fn oaep_encrypt<R: TryCryptoRng + ?Sized>(
6161
rng: &mut R,
6262
msg: &[u8],
6363
digest: &mut dyn DynDigest,
@@ -90,7 +90,7 @@ pub(crate) fn oaep_encrypt<R: CryptoRng + ?Sized>(
9090
/// [PKCS#1 OAEP]: https://datatracker.ietf.org/doc/html/rfc8017#section-7.1
9191
#[inline]
9292
pub(crate) fn oaep_encrypt_digest<
93-
R: CryptoRng + ?Sized,
93+
R: TryCryptoRng + ?Sized,
9494
D: Digest,
9595
MGD: Digest + FixedOutputReset,
9696
>(

src/algorithms/pkcs1v15.rs

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
use alloc::vec::Vec;
1010
use digest::Digest;
1111
use pkcs8::AssociatedOid;
12-
use rand_core::CryptoRng;
12+
use rand_core::TryCryptoRng;
1313
use subtle::{Choice, ConditionallySelectable, ConstantTimeEq};
1414
use zeroize::Zeroizing;
1515

@@ -18,17 +18,22 @@ use crate::errors::{Error, Result};
1818
/// Fills the provided slice with random values, which are guaranteed
1919
/// to not be zero.
2020
#[inline]
21-
fn non_zero_random_bytes<R: CryptoRng + ?Sized>(rng: &mut R, data: &mut [u8]) {
22-
rng.fill_bytes(data);
21+
fn non_zero_random_bytes<R: TryCryptoRng + ?Sized>(
22+
rng: &mut R,
23+
data: &mut [u8],
24+
) -> core::result::Result<(), R::Error> {
25+
rng.try_fill_bytes(data)?;
2326

2427
for el in data {
2528
if *el == 0u8 {
2629
// TODO: break after a certain amount of time
2730
while *el == 0u8 {
28-
rng.fill_bytes(core::slice::from_mut(el));
31+
rng.try_fill_bytes(core::slice::from_mut(el))?;
2932
}
3033
}
3134
}
35+
36+
Ok(())
3237
}
3338

3439
/// Applied the padding scheme from PKCS#1 v1.5 for encryption. The message must be no longer than
@@ -39,7 +44,7 @@ pub(crate) fn pkcs1v15_encrypt_pad<R>(
3944
k: usize,
4045
) -> Result<Zeroizing<Vec<u8>>>
4146
where
42-
R: CryptoRng + ?Sized,
47+
R: TryCryptoRng + ?Sized,
4348
{
4449
if msg.len() + 11 > k {
4550
return Err(Error::MessageTooLong);
@@ -48,7 +53,7 @@ where
4853
// EM = 0x00 || 0x02 || PS || 0x00 || M
4954
let mut em = Zeroizing::new(vec![0u8; k]);
5055
em[1] = 2;
51-
non_zero_random_bytes(rng, &mut em[2..k - msg.len() - 1]);
56+
non_zero_random_bytes(rng, &mut em[2..k - msg.len() - 1]).map_err(|_: R::Error| Error::Rng)?;
5257
em[k - msg.len() - 1] = 0;
5358
em[k - msg.len()..].copy_from_slice(msg);
5459
Ok(em)
@@ -189,7 +194,7 @@ mod tests {
189194
for _ in 0..10 {
190195
let mut rng = ChaCha8Rng::from_seed([42; 32]);
191196
let mut b = vec![0u8; 512];
192-
non_zero_random_bytes(&mut rng, &mut b);
197+
non_zero_random_bytes(&mut rng, &mut b).unwrap();
193198
for el in &b {
194199
assert_ne!(*el, 0u8);
195200
}

src/algorithms/rsa.rs

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use core::cmp::Ordering;
44

55
use crypto_bigint::modular::{BoxedMontyForm, BoxedMontyParams};
66
use crypto_bigint::{BoxedUint, Gcd, NonZero, Odd, RandomMod, Wrapping};
7-
use rand_core::CryptoRng;
7+
use rand_core::TryCryptoRng;
88
use zeroize::Zeroize;
99

1010
use crate::errors::{Error, Result};
@@ -31,8 +31,8 @@ pub fn rsa_encrypt<K: PublicKeyParts>(key: &K, m: &BoxedUint) -> Result<BoxedUin
3131
/// Use this function with great care! Raw RSA should never be used without an appropriate padding
3232
/// or signature scheme. See the [module-level documentation][crate::hazmat] for more information.
3333
#[inline]
34-
pub fn rsa_decrypt<R: CryptoRng + ?Sized>(
35-
mut rng: Option<&mut R>,
34+
pub fn rsa_decrypt<R: TryCryptoRng + ?Sized>(
35+
rng: Option<&mut R>,
3636
priv_key: &impl PrivateKeyParts,
3737
c: &BoxedUint,
3838
) -> Result<BoxedUint> {
@@ -48,8 +48,8 @@ pub fn rsa_decrypt<R: CryptoRng + ?Sized>(
4848
let n_params = priv_key.n_params();
4949
let bits = d.bits_precision();
5050

51-
let c = if let Some(ref mut rng) = rng {
52-
let (blinded, unblinder) = blind(rng, priv_key, c, n_params);
51+
let c = if let Some(rng) = rng {
52+
let (blinded, unblinder) = blind(rng, priv_key, c, n_params)?;
5353
ir = Some(unblinder);
5454
blinded.widen(bits)
5555
} else {
@@ -123,7 +123,7 @@ pub fn rsa_decrypt<R: CryptoRng + ?Sized>(
123123
/// Use this function with great care! Raw RSA should never be used without an appropriate padding
124124
/// or signature scheme. See the [module-level documentation][crate::hazmat] for more information.
125125
#[inline]
126-
pub fn rsa_decrypt_and_check<R: CryptoRng + ?Sized>(
126+
pub fn rsa_decrypt_and_check<R: TryCryptoRng + ?Sized>(
127127
priv_key: &impl PrivateKeyParts,
128128
rng: Option<&mut R>,
129129
c: &BoxedUint,
@@ -142,12 +142,12 @@ pub fn rsa_decrypt_and_check<R: CryptoRng + ?Sized>(
142142
}
143143

144144
/// Returns the blinded c, along with the unblinding factor.
145-
fn blind<R: CryptoRng, K: PublicKeyParts>(
145+
fn blind<R: TryCryptoRng + ?Sized, K: PublicKeyParts>(
146146
rng: &mut R,
147147
key: &K,
148148
c: &BoxedUint,
149149
n_params: &BoxedMontyParams,
150-
) -> (BoxedUint, BoxedUint) {
150+
) -> Result<(BoxedUint, BoxedUint)> {
151151
// Blinding involves multiplying c by r^e.
152152
// Then the decryption operation performs (m^e * r^e)^d mod n
153153
// which equals mr mod n. The factor of r can then be removed
@@ -158,7 +158,7 @@ fn blind<R: CryptoRng, K: PublicKeyParts>(
158158
let mut r: BoxedUint = BoxedUint::one_with_precision(bits);
159159
let mut ir: Option<BoxedUint> = None;
160160
while ir.is_none() {
161-
r = BoxedUint::random_mod(rng, key.n());
161+
r = BoxedUint::try_random_mod(rng, key.n()).map_err(|_| Error::Rng)?;
162162
if r.is_zero().into() {
163163
r = BoxedUint::one_with_precision(bits);
164164
}
@@ -181,7 +181,7 @@ fn blind<R: CryptoRng, K: PublicKeyParts>(
181181
debug_assert_eq!(blinded.bits_precision(), bits);
182182
debug_assert_eq!(ir.bits_precision(), bits);
183183

184-
(blinded, ir)
184+
Ok((blinded, ir))
185185
}
186186

187187
/// Given an m and and unblinding factor, unblind the m.

src/errors.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,9 @@ pub enum Error {
6969

7070
/// Decoding error.
7171
Decode(crypto_bigint::DecodeError),
72+
73+
/// Random number generator error.
74+
Rng,
7275
}
7376

7477
#[cfg(feature = "std")]
@@ -99,6 +102,7 @@ impl core::fmt::Display for Error {
99102
Error::InvalidPadLen => write!(f, "invalid padding length"),
100103
Error::InvalidArguments => write!(f, "invalid arguments"),
101104
Error::Decode(err) => write!(f, "{:?}", err),
105+
Error::Rng => write!(f, "rng error"),
102106
}
103107
}
104108
}

src/key.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -169,7 +169,7 @@ impl PublicKeyParts for RsaPublicKey {
169169

170170
impl RsaPublicKey {
171171
/// Encrypt the given message.
172-
pub fn encrypt<R: CryptoRng, P: PaddingScheme>(
172+
pub fn encrypt<R: CryptoRng + ?Sized, P: PaddingScheme>(
173173
&self,
174174
rng: &mut R,
175175
padding: P,
@@ -254,15 +254,15 @@ impl RsaPrivateKey {
254254
const EXP: u64 = 65537;
255255

256256
/// Generate a new Rsa key pair of the given bit size using the passed in `rng`.
257-
pub fn new<R: CryptoRng>(rng: &mut R, bit_size: usize) -> Result<RsaPrivateKey> {
257+
pub fn new<R: CryptoRng + ?Sized>(rng: &mut R, bit_size: usize) -> Result<RsaPrivateKey> {
258258
Self::new_with_exp(rng, bit_size, BoxedUint::from(Self::EXP))
259259
}
260260

261261
/// Generate a new RSA key pair of the given bit size and the public exponent
262262
/// using the passed in `rng`.
263263
///
264264
/// Unless you have specific needs, you should use `RsaPrivateKey::new` instead.
265-
pub fn new_with_exp<R: CryptoRng>(
265+
pub fn new_with_exp<R: CryptoRng + ?Sized>(
266266
rng: &mut R,
267267
bit_size: usize,
268268
exp: BoxedUint,
@@ -493,7 +493,7 @@ impl RsaPrivateKey {
493493
/// Decrypt the given message.
494494
///
495495
/// Uses `rng` to blind the decryption process.
496-
pub fn decrypt_blinded<R: CryptoRng, P: PaddingScheme>(
496+
pub fn decrypt_blinded<R: CryptoRng + ?Sized, P: PaddingScheme>(
497497
&self,
498498
rng: &mut R,
499499
padding: P,
@@ -517,7 +517,7 @@ impl RsaPrivateKey {
517517
/// [`Pss::new`][`crate::Pss::new`] for a standard RSASSA-PSS signature, or
518518
/// [`Pss::new_blinded`][`crate::Pss::new_blinded`] for RSA-BSSA blind
519519
/// signatures.
520-
pub fn sign_with_rng<R: CryptoRng, S: SignatureScheme>(
520+
pub fn sign_with_rng<R: CryptoRng + ?Sized, S: SignatureScheme>(
521521
&self,
522522
rng: &mut R,
523523
padding: S,

src/oaep.rs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ use core::fmt;
1515
use crypto_bigint::BoxedUint;
1616

1717
use digest::{Digest, DynDigest, FixedOutputReset};
18-
use rand_core::CryptoRng;
18+
use rand_core::TryCryptoRng;
1919

2020
use crate::algorithms::oaep::*;
2121
use crate::algorithms::pad::{uint_to_be_pad, uint_to_zeroizing_be_pad};
@@ -135,7 +135,7 @@ impl Oaep {
135135
}
136136

137137
impl PaddingScheme for Oaep {
138-
fn decrypt<Rng: CryptoRng>(
138+
fn decrypt<Rng: TryCryptoRng + ?Sized>(
139139
mut self,
140140
rng: Option<&mut Rng>,
141141
priv_key: &RsaPrivateKey,
@@ -151,7 +151,7 @@ impl PaddingScheme for Oaep {
151151
)
152152
}
153153

154-
fn encrypt<Rng: CryptoRng>(
154+
fn encrypt<Rng: TryCryptoRng + ?Sized>(
155155
mut self,
156156
rng: &mut Rng,
157157
pub_key: &RsaPublicKey,
@@ -186,7 +186,7 @@ impl fmt::Debug for Oaep {
186186
///
187187
/// [PKCS#1 OAEP]: https://datatracker.ietf.org/doc/html/rfc8017#section-7.1
188188
#[inline]
189-
fn encrypt<R: CryptoRng + ?Sized>(
189+
fn encrypt<R: TryCryptoRng + ?Sized>(
190190
rng: &mut R,
191191
pub_key: &RsaPublicKey,
192192
msg: &[u8],
@@ -209,7 +209,7 @@ fn encrypt<R: CryptoRng + ?Sized>(
209209
/// `2 + (2 * hash.size())`.
210210
///
211211
/// [PKCS#1 OAEP]: https://datatracker.ietf.org/doc/html/rfc8017#section-7.1
212-
fn encrypt_digest<R: CryptoRng + ?Sized, D: Digest, MGD: Digest + FixedOutputReset>(
212+
fn encrypt_digest<R: TryCryptoRng + ?Sized, D: Digest, MGD: Digest + FixedOutputReset>(
213213
rng: &mut R,
214214
pub_key: &RsaPublicKey,
215215
msg: &[u8],
@@ -236,7 +236,7 @@ fn encrypt_digest<R: CryptoRng + ?Sized, D: Digest, MGD: Digest + FixedOutputRes
236236
///
237237
/// [PKCS#1 OAEP]: https://datatracker.ietf.org/doc/html/rfc8017#section-7.1
238238
#[inline]
239-
fn decrypt<R: CryptoRng + ?Sized>(
239+
fn decrypt<R: TryCryptoRng + ?Sized>(
240240
rng: Option<&mut R>,
241241
priv_key: &RsaPrivateKey,
242242
ciphertext: &[u8],
@@ -269,7 +269,7 @@ fn decrypt<R: CryptoRng + ?Sized>(
269269
///
270270
/// [PKCS#1 OAEP]: https://datatracker.ietf.org/doc/html/rfc8017#section-7.1
271271
#[inline]
272-
fn decrypt_digest<R: CryptoRng + ?Sized, D: Digest, MGD: Digest + FixedOutputReset>(
272+
fn decrypt_digest<R: TryCryptoRng + ?Sized, D: Digest, MGD: Digest + FixedOutputReset>(
273273
rng: Option<&mut R>,
274274
priv_key: &RsaPrivateKey,
275275
ciphertext: &[u8],

0 commit comments

Comments
 (0)