Skip to main content

p256/arithmetic/scalar/
blinding.rs

1//! Random blinding support for [`Scalar`]
2
3// TODO(tarcieri): make this generic (along with `Scalar::invert_vartime`)
4// and extract it into the `elliptic-curve` crate so it can be reused across curves
5
6use super::Scalar;
7use core::borrow::Borrow;
8use elliptic_curve::{
9    group::ff::Field,
10    ops::Invert,
11    rand_core::{CryptoRng, RngCore},
12    subtle::CtOption,
13};
14
15#[cfg(feature = "zeroize")]
16use elliptic_curve::zeroize::Zeroize;
17
18/// Scalar blinded with a randomly generated masking value.
19///
20/// This provides a randomly blinded impl of [`Invert`] which is useful for
21/// ECDSA ephemeral (`k`) scalars.
22#[cfg_attr(docsrs, doc(cfg(feature = "arithmetic")))]
23pub struct BlindedScalar {
24    /// Actual scalar value
25    scalar: Scalar,
26
27    /// Mask value
28    mask: Scalar,
29}
30
31impl BlindedScalar {
32    /// Create a new [`BlindedScalar`] from a scalar and a [`CryptoRng`]
33    pub fn new(scalar: Scalar, rng: impl CryptoRng + RngCore) -> Self {
34        Self {
35            scalar,
36            mask: Scalar::random(rng),
37        }
38    }
39}
40
41impl Borrow<Scalar> for BlindedScalar {
42    fn borrow(&self) -> &Scalar {
43        &self.scalar
44    }
45}
46
47impl Invert for BlindedScalar {
48    type Output = Scalar;
49
50    fn invert(&self) -> CtOption<Scalar> {
51        // prevent side channel analysis of scalar inversion by pre-and-post-multiplying
52        // with the random masking scalar
53        (self.scalar * self.mask)
54            .invert_vartime()
55            .map(|s| s * self.mask)
56    }
57}
58
59#[cfg(feature = "zeroize")]
60impl Zeroize for BlindedScalar {
61    fn zeroize(&mut self) {
62        self.scalar.zeroize();
63        self.mask.zeroize();
64    }
65}
66
67#[cfg(feature = "zeroize")]
68impl Drop for BlindedScalar {
69    fn drop(&mut self) {
70        self.zeroize();
71    }
72}