Skip to content

Commit 10ee0ee

Browse files
committed
CRT modulus blinding
Blinds `p` and `q` independently with factors containing 128-bits of randomness, then reduce residues before CRT recombination. Also adds regression tests and checkct coverage.
1 parent 28ae504 commit 10ee0ee

4 files changed

Lines changed: 154 additions & 17 deletions

File tree

‎checkct/driver/src/main.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ mod allocator;
1010
mod blinding;
1111
mod driver;
1212
mod exponent_blinding;
13+
mod modulus_blinding;
1314
mod pkcs1v15;
1415
#[allow(dead_code)]
1516
#[path = "../../../src/algorithms/pkcs1v15/selection.rs"]
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
//! CRT modulus blinding with secret primes and random factors.
2+
3+
use crate::rng::{PrivateRng, PublicRng};
4+
use checkct_macros::checkct;
5+
use core::hint::black_box;
6+
use crypto_bigint::{BoxedUint, Odd, U64};
7+
8+
#[checkct]
9+
pub fn blind_modulus_64() {
10+
// SAFETY: This independent, single-threaded analysis has no live allocations.
11+
unsafe { crate::allocator::reset() };
12+
black_box(PublicRng.next_u32());
13+
14+
let prime = Odd::new(BoxedUint::from(secret_modulus())).unwrap();
15+
let blinded = crate::blinding::blind_modulus(&mut PrivateRng, &prime).unwrap();
16+
black_box(blinded.as_limbs());
17+
drop(blinded);
18+
}
19+
20+
fn secret_modulus() -> U64 {
21+
let mut bytes = [0u8; 8];
22+
PrivateRng.fill_bytes(&mut bytes);
23+
bytes[0] |= 1;
24+
U64::from_le_slice(&bytes)
25+
}

‎src/algorithms/blinding.rs‎

Lines changed: 109 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
1-
//! Exponent blinding for RSA private operations.
1+
//! Exponent and CRT modulus blinding for RSA private operations.
22
3-
use crypto_bigint::{BoxedUint, ConcatenatingMul, Odd, Resize};
3+
use super::reduction::to_monty;
4+
use crypto_bigint::{
5+
BoxedUint, ConcatenatingMul, Odd, Resize,
6+
modular::{BoxedMontyForm, BoxedMontyParams},
7+
};
48
use rand_core::TryCryptoRng;
59
use zeroize::Zeroizing;
610

@@ -29,6 +33,44 @@ pub(crate) fn blind_exponent<R: TryCryptoRng + ?Sized>(
2933
Ok(blinded)
3034
}
3135

36+
/// Multiply a CRT prime by a fresh random odd factor, using public storage widths.
37+
///
38+
/// With `r` uniform over 128 bits, `g = 2*r + 1` is positive and odd and retains all
39+
/// 128 bits of randomness. Odd factors permit Montgomery arithmetic without rejection sampling.
40+
/// <https://www.ietf.org/archive/id/draft-irtf-cfrg-rsa-guidance-10.html#section-6.5>
41+
pub(crate) fn blind_modulus<R: TryCryptoRng + ?Sized>(
42+
rng: &mut R,
43+
prime: &Odd<BoxedUint>,
44+
) -> Result<Odd<BoxedUint>> {
45+
let mut bytes = Zeroizing::new([0u8; 16]);
46+
rng.try_fill_bytes(bytes.as_mut()).map_err(|_| Error::Rng)?;
47+
// Reserve the extra bit before doubling, including when every random byte is 0xff.
48+
let mut g =
49+
Zeroizing::new(BoxedUint::from_le_slice(bytes.as_ref(), 129).map_err(|_| Error::Internal)?);
50+
g.shl_assign(1);
51+
g.wrapping_add_assign(BoxedUint::one());
52+
Odd::new(prime.concatenating_mul(&*g))
53+
.into_option()
54+
.ok_or(Error::Internal)
55+
}
56+
57+
/// Exponentiate modulo a fresh multiple of `p`, then return the residue modulo `p`.
58+
///
59+
/// `exponent` may already be blinded using a multiple of `p - 1`. Reduce back to `p`
60+
/// before CRT recombination, whose precomputed coefficient uses the original primes.
61+
pub(crate) fn pow_mod_blinded<R: TryCryptoRng + ?Sized>(
62+
rng: &mut R,
63+
base: &BoxedUint,
64+
exponent: &BoxedUint,
65+
p: &BoxedMontyParams,
66+
) -> Result<BoxedMontyForm> {
67+
let params = BoxedMontyParams::new(blind_modulus(rng, p.modulus())?);
68+
let base = Zeroizing::new(to_monty(base, &params));
69+
let powered = Zeroizing::new(base.pow(exponent));
70+
let residue = Zeroizing::new(powered.retrieve());
71+
Ok(to_monty(&residue, p))
72+
}
73+
3274
/// Compute φ(n) = ∏(p_i - 1) at the public modulus precision for non-CRT operations.
3375
///
3476
/// The factors must belong to a valid RSA key; then every partial product is below n.
@@ -122,7 +164,60 @@ mod tests {
122164
}
123165

124166
#[test]
125-
fn exponent_blinding_private_operations() {
167+
fn modulus_blinding_arithmetic() {
168+
for bits in [64, 128, 192] {
169+
let prime = Odd::new(BoxedUint::max(bits)).expect("odd modulus");
170+
let blinded_bits = bits + BoxedUint::zero_with_precision(129).bits_precision();
171+
let p = prime.as_ref().resize_unchecked(blinded_bits);
172+
let mut rng = MockRng(
173+
[0u128, 1, u128::MAX]
174+
.map(|r| r.to_le_bytes().to_vec())
175+
.into(),
176+
);
177+
for expected in [
178+
p.clone(),
179+
p.shl(1).wrapping_add(&p),
180+
p.shl(129).wrapping_sub(&p),
181+
] {
182+
let blinded = blind_modulus(&mut rng, &prime).expect("blinded modulus");
183+
assert_eq!(blinded.as_ref(), &expected);
184+
assert_eq!(blinded.bits_precision(), blinded_bits);
185+
}
186+
assert!(rng.0.is_empty());
187+
}
188+
}
189+
190+
#[test]
191+
fn modulus_blinding_reduces_to_original_prime() {
192+
// Exercise inputs both narrower and wider than the blinded modulus, and primes whose
193+
// values are much smaller than their storage widths (as in unbalanced RSA keys).
194+
for bits in [64, 128, 192] {
195+
let p = Odd::new(BoxedUint::from(53u64).resize_unchecked(bits)).expect("prime");
196+
let params = BoxedMontyParams::new(p);
197+
for base_bits in [64, 512] {
198+
for base in [
199+
BoxedUint::max(base_bits),
200+
BoxedUint::zero_with_precision(base_bits),
201+
] {
202+
for exponent in [0u64, 17] {
203+
let exponent = BoxedUint::from(exponent);
204+
let expected = to_monty(&base, &params).pow(&exponent).retrieve();
205+
// r=26 makes g=p=53, so this also covers a factor sharing the prime.
206+
for r in [0u128, 26, u128::MAX] {
207+
let mut rng = MockRng([r.to_le_bytes().to_vec()].into());
208+
let actual = pow_mod_blinded(&mut rng, &base, &exponent, &params)
209+
.expect("blinded exponentiation");
210+
assert_eq!(actual.retrieve(), expected);
211+
assert_eq!(actual.bits_precision(), bits);
212+
}
213+
}
214+
}
215+
}
216+
}
217+
}
218+
219+
#[test]
220+
fn blinding_private_operations() {
126221
let two_prime = RsaPrivateKey::from_p_q(61u64.into(), 53u64.into(), 17u64.into())
127222
.expect("two-prime key");
128223
let multi_prime = RsaPrivateKey::from_primes(
@@ -145,24 +240,30 @@ mod tests {
145240
BoxedUint::one_with_precision(bits),
146241
BoxedUint::from(42u64).resize_unchecked(bits),
147242
key.primes()[0].as_ref().resize_unchecked(bits), // Not coprime to n.
243+
key.primes()[1].as_ref().resize_unchecked(bits),
148244
key.n().wrapping_sub(BoxedUint::one()),
149245
] {
150246
let expected = rsa_decrypt_and_check::<MockRng>(&key, None, &c)
151247
.expect("unblinded reference");
152248
let mut requests = VecDeque::new();
153249

154-
for factor in [0, 0xff] {
250+
// The last case makes both blinded CRT moduli equal to n (g_p=q, g_q=p).
251+
// The random factors need not be coprime to either prime or to one another.
252+
let blindings = [(0, [0u128; 2]), (0xff, [u128::MAX; 2]), (0xa5, [26, 30])];
253+
for (factor, [rp, rq]) in blindings {
155254
let mut base = vec![0; key.size()];
156255
base[0] = 1; // Invertible base factor, without rejection sampling.
157256
requests.push_back(base);
158257
requests.push_back(vec![factor; 16]);
159258
if crt {
160259
requests.push_back(vec![factor ^ 0xff; 16]);
260+
requests.push_back(rp.to_le_bytes().to_vec());
261+
requests.push_back(rq.to_le_bytes().to_vec());
161262
}
162263
}
163264
let mut rng = MockRng(requests.clone());
164-
// Reusing a key must request fresh factors for each operation and each exponent.
165-
for _ in 0..2 {
265+
// Reusing a key must request fresh factors for each exponent and modulus.
266+
for _ in 0..blindings.len() {
166267
assert_eq!(
167268
rsa_decrypt_and_check(&key, Some(&mut rng), &c)
168269
.expect("blinded result"),
@@ -171,8 +272,8 @@ mod tests {
171272
}
172273
assert!(rng.0.is_empty());
173274

174-
// Exhaust the RNG after base blinding, and between the two CRT exponents.
175-
for available in 1..=if crt { 2 } else { 1 } {
275+
// Fail at each exponent and modulus blinding request after base blinding.
276+
for available in 1..=if crt { 4 } else { 1 } {
176277
let mut rng = MockRng(requests.iter().take(available).cloned().collect());
177278
assert_eq!(
178279
rsa_decrypt_and_check(&key, Some(&mut rng), &c),

‎src/algorithms/rsa.rs‎

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
77
pub(crate) use super::reduction::to_monty;
88

9-
use super::blinding::{blind_exponent, totient};
9+
use super::blinding::{blind_exponent, pow_mod_blinded, totient};
1010
use crypto_bigint::{
1111
BoxedUint, ConcatenatingMul, ConcatenatingSquare, Gcd, NonZero, Odd, RandomMod, Resize,
1212
modular::BoxedMontyParams,
@@ -42,7 +42,8 @@ pub fn rsa_encrypt<K: PublicKeyParts>(key: &K, m: &BoxedUint) -> Result<BoxedUin
4242
/// Implements the integer arithmetic shared by RSADP (RFC8017 §5.1.2) and RSASP1 (§5.2.1).
4343
/// Checks that `c < n` and that `c` has the modulus's storage precision.
4444
///
45-
/// Returns a plaintext `BoxedUint`. Performs base and fresh exponent blinding if an `Rng` is passed.
45+
/// Returns a plaintext `BoxedUint`. Performs base, exponent, and CRT modulus blinding if an `Rng`
46+
/// is passed, using fresh factors for each private operation.
4647
/// Blinded non-CRT operations require the prime factors in [`PrivateKeyParts::primes`].
4748
///
4849
/// <div class="warning">
@@ -113,12 +114,19 @@ pub fn rsa_decrypt<R: TryCryptoRng + ?Sized>(
113114
.as_ref()
114115
.map_or((dp, dq), |(dp, dq)| (&**dp, &**dq));
115116

116-
// m1 = c^dP mod p
117-
let cp = to_monty(&c, &p_params);
118-
let mut m1 = cp.pow(dp);
119-
// m2 = c^dQ mod q
120-
let cq = to_monty(&c, &q_params);
121-
let m2 = cq.pow(dq).retrieve();
117+
// Exponentiate modulo independently blinded primes, then reduce both residues back
118+
// to the original primes before using the precomputed qInv for CRT recombination.
119+
let (mut m1, m2) = if let Some(rng) = rng {
120+
(
121+
pow_mod_blinded(rng, &c, dp, &p_params)?,
122+
pow_mod_blinded(rng, &c, dq, &q_params)?.retrieve(),
123+
)
124+
} else {
125+
(
126+
to_monty(&c, &p_params).pow(dp),
127+
to_monty(&c, &q_params).pow(dq).retrieve(),
128+
)
129+
};
122130

123131
// (m1 - m2) mod p, also supporting custom keys with unequal public widths.
124132
let m2r = to_monty(&m2, &p_params);
@@ -130,6 +138,7 @@ pub fn rsa_decrypt<R: TryCryptoRng + ?Sized>(
130138
let h = (qinv * m1).retrieve();
131139

132140
// m = m2 + h.q
141+
// With m2 < q and h < p, m < n even when the exponentiations used blinded moduli.
133142
let m2 = m2.try_resize(n.bits_precision()).ok_or(Error::Internal)?;
134143
let hq = h
135144
.concatenating_mul(priv_key.primes()[1].as_ref())
@@ -162,7 +171,8 @@ pub fn rsa_decrypt<R: TryCryptoRng + ?Sized>(
162171

163172
/// ⚠️ Performs raw RSA decryption with no padding.
164173
///
165-
/// Returns a plaintext `BoxedUint`. Performs base and fresh exponent blinding if an `Rng` is passed.
174+
/// Returns a plaintext `BoxedUint`. Performs base, exponent, and CRT modulus blinding if an `Rng`
175+
/// is passed, using fresh factors for each private operation.
166176
/// Blinded non-CRT operations require the prime factors in [`PrivateKeyParts::primes`].
167177
///
168178
/// `c` must have the same `bits_precision` as the RSA key modulus.

0 commit comments

Comments
 (0)