Skip to main content

elliptic_curve/scalar/
non_zero.rs

1//! Non-zero scalar type.
2// TODO(tarcieri): change bounds to `ScalarArithmetic` instead of `ProjectiveArithmetic`
3
4use crate::{
5    bigint::Encoding as _,
6    ops::Invert,
7    rand_core::{CryptoRng, RngCore},
8    Curve, Error, FieldBytes, ProjectiveArithmetic, Result, Scalar,
9};
10use core::{convert::TryFrom, ops::Deref};
11use ff::{Field, PrimeField};
12use generic_array::GenericArray;
13use subtle::{Choice, ConditionallySelectable, ConstantTimeEq, CtOption};
14
15#[cfg(feature = "zeroize")]
16use {crate::SecretKey, zeroize::Zeroize};
17
18/// Non-zero scalar type.
19///
20/// This type ensures that its value is not zero, ala `core::num::NonZero*`.
21/// To do this, the generic `S` type must impl both `Default` and
22/// `ConstantTimeEq`, with the requirement that `S::default()` returns 0.
23///
24/// In the context of ECC, it's useful for ensuring that scalar multiplication
25/// cannot result in the point at infinity.
26#[cfg_attr(docsrs, doc(cfg(feature = "arithmetic")))]
27#[derive(Clone)]
28pub struct NonZeroScalar<C>
29where
30    C: Curve + ProjectiveArithmetic,
31{
32    scalar: Scalar<C>,
33}
34
35impl<C> NonZeroScalar<C>
36where
37    C: Curve + ProjectiveArithmetic,
38{
39    /// Generate a random `NonZeroScalar`
40    pub fn random(mut rng: impl CryptoRng + RngCore) -> Self {
41        // Use rejection sampling to eliminate zero values
42        loop {
43            if let Some(result) = Self::new(Field::random(&mut rng)) {
44                break result;
45            }
46        }
47    }
48
49    /// Decode a [`NonZeroScalar`] from a serialized field element
50    pub fn from_repr(repr: FieldBytes<C>) -> Option<Self> {
51        Scalar::<C>::from_repr(repr).and_then(Self::new)
52    }
53
54    /// Create a [`NonZeroScalar`] from a scalar.
55    // TODO(tarcieri): make this constant time?
56    pub fn new(scalar: Scalar<C>) -> Option<Self> {
57        if scalar.is_zero() {
58            None
59        } else {
60            Some(Self { scalar })
61        }
62    }
63}
64
65impl<C> AsRef<Scalar<C>> for NonZeroScalar<C>
66where
67    C: Curve + ProjectiveArithmetic,
68{
69    fn as_ref(&self) -> &Scalar<C> {
70        &self.scalar
71    }
72}
73
74impl<C> ConditionallySelectable for NonZeroScalar<C>
75where
76    C: Curve + ProjectiveArithmetic,
77{
78    fn conditional_select(a: &Self, b: &Self, choice: Choice) -> Self {
79        Self {
80            scalar: Scalar::<C>::conditional_select(&a.scalar, &b.scalar, choice),
81        }
82    }
83}
84
85impl<C> ConstantTimeEq for NonZeroScalar<C>
86where
87    C: Curve + ProjectiveArithmetic,
88{
89    fn ct_eq(&self, other: &Self) -> Choice {
90        self.scalar.ct_eq(&other.scalar)
91    }
92}
93
94impl<C> Copy for NonZeroScalar<C> where C: Curve + ProjectiveArithmetic {}
95
96impl<C> Deref for NonZeroScalar<C>
97where
98    C: Curve + ProjectiveArithmetic,
99{
100    type Target = Scalar<C>;
101
102    fn deref(&self) -> &Scalar<C> {
103        &self.scalar
104    }
105}
106
107impl<C> From<NonZeroScalar<C>> for FieldBytes<C>
108where
109    C: Curve + ProjectiveArithmetic,
110{
111    fn from(scalar: NonZeroScalar<C>) -> FieldBytes<C> {
112        Self::from(&scalar)
113    }
114}
115
116impl<C> From<&NonZeroScalar<C>> for FieldBytes<C>
117where
118    C: Curve + ProjectiveArithmetic,
119{
120    fn from(scalar: &NonZeroScalar<C>) -> FieldBytes<C> {
121        scalar.scalar.to_repr()
122    }
123}
124
125#[cfg(feature = "zeroize")]
126#[cfg_attr(docsrs, doc(cfg(feature = "zeroize")))]
127impl<C> From<SecretKey<C>> for NonZeroScalar<C>
128where
129    C: Curve + ProjectiveArithmetic,
130{
131    fn from(sk: SecretKey<C>) -> NonZeroScalar<C> {
132        Self::from(&sk)
133    }
134}
135
136#[cfg(feature = "zeroize")]
137#[cfg_attr(docsrs, doc(cfg(feature = "zeroize")))]
138impl<C> From<&SecretKey<C>> for NonZeroScalar<C>
139where
140    C: Curve + ProjectiveArithmetic,
141{
142    fn from(sk: &SecretKey<C>) -> NonZeroScalar<C> {
143        let scalar = sk.as_scalar_bytes().to_scalar();
144        debug_assert!(!scalar.is_zero());
145        Self { scalar }
146    }
147}
148
149impl<C> Invert for NonZeroScalar<C>
150where
151    C: Curve + ProjectiveArithmetic,
152{
153    type Output = Scalar<C>;
154
155    /// Perform a scalar inversion
156    fn invert(&self) -> CtOption<Self::Output> {
157        ff::Field::invert(&self.scalar)
158    }
159}
160
161impl<C> TryFrom<&[u8]> for NonZeroScalar<C>
162where
163    C: Curve + ProjectiveArithmetic,
164{
165    type Error = Error;
166
167    fn try_from(bytes: &[u8]) -> Result<Self> {
168        if bytes.len() == C::UInt::BYTE_SIZE {
169            NonZeroScalar::from_repr(GenericArray::clone_from_slice(bytes)).ok_or(Error)
170        } else {
171            Err(Error)
172        }
173    }
174}
175
176#[cfg(feature = "zeroize")]
177impl<C> Zeroize for NonZeroScalar<C>
178where
179    C: Curve + ProjectiveArithmetic,
180    Scalar<C>: Zeroize,
181{
182    fn zeroize(&mut self) {
183        self.scalar.zeroize();
184    }
185}