1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
//! Random blinding support for [`Scalar`]

use super::Scalar;
use crate::{ops::Invert, CurveArithmetic};
use group::ff::Field;
use rand_core::CryptoRngCore;
use subtle::CtOption;
use zeroize::Zeroize;

/// Scalar blinded with a randomly generated masking value.
///
/// This provides a randomly blinded impl of [`Invert`] which is useful for
/// e.g. ECDSA ephemeral (`k`) scalars.
///
/// It implements masked variable-time inversions using Stein's algorithm, which
/// may be helpful for performance on embedded platforms.
#[derive(Clone)]
pub struct BlindedScalar<C>
where
    C: CurveArithmetic,
{
    /// Actual scalar value.
    scalar: Scalar<C>,

    /// Mask value.
    mask: Scalar<C>,
}

impl<C> BlindedScalar<C>
where
    C: CurveArithmetic,
{
    /// Create a new [`BlindedScalar`] from a scalar and a [`CryptoRngCore`].
    pub fn new(scalar: Scalar<C>, rng: &mut impl CryptoRngCore) -> Self {
        Self {
            scalar,
            mask: Scalar::<C>::random(rng),
        }
    }
}

impl<C> AsRef<Scalar<C>> for BlindedScalar<C>
where
    C: CurveArithmetic,
{
    fn as_ref(&self) -> &Scalar<C> {
        &self.scalar
    }
}

impl<C> Invert for BlindedScalar<C>
where
    C: CurveArithmetic,
{
    type Output = CtOption<Scalar<C>>;

    fn invert(&self) -> CtOption<Scalar<C>> {
        // prevent side channel analysis of scalar inversion by pre-and-post-multiplying
        // with the random masking scalar
        (self.scalar * self.mask)
            .invert_vartime()
            .map(|s| s * self.mask)
    }
}

impl<C> Drop for BlindedScalar<C>
where
    C: CurveArithmetic,
{
    fn drop(&mut self) {
        self.scalar.zeroize();
        self.mask.zeroize();
    }
}