elliptic_curve/scalar/
bytes.rs1use crate::{
4 bigint::{ArrayEncoding as _, Encoding as _},
5 Curve, Error, FieldBytes, Result,
6};
7use core::convert::TryFrom;
8use generic_array::GenericArray;
9use subtle::{Choice, ConditionallySelectable, ConstantTimeEq, ConstantTimeLess, CtOption};
10
11#[cfg(feature = "arithmetic")]
12use crate::{group::ff::PrimeField, NonZeroScalar, ProjectiveArithmetic, Scalar};
13
14#[cfg(feature = "zeroize")]
15use zeroize::Zeroize;
16
17#[derive(Clone, Debug, Eq)]
22pub struct ScalarBytes<C: Curve> {
23 inner: FieldBytes<C>,
25}
26
27impl<C> ScalarBytes<C>
28where
29 C: Curve,
30{
31 pub fn new(bytes: FieldBytes<C>) -> CtOption<Self> {
34 Self::from_uint(&C::UInt::from_be_byte_array(bytes))
35 }
36
37 pub fn from_uint(uint: &C::UInt) -> CtOption<Self> {
39 let inner = uint.to_be_byte_array();
40 let in_range = uint.ct_lt(&C::ORDER);
41 CtOption::new(Self { inner }, in_range)
42 }
43
44 #[cfg(feature = "arithmetic")]
46 #[cfg_attr(docsrs, doc(cfg(feature = "arithmetic")))]
47 pub fn from_scalar(scalar: &Scalar<C>) -> Self
48 where
49 C: ProjectiveArithmetic,
50 {
51 Self {
52 inner: scalar.to_repr(),
53 }
54 }
55
56 #[cfg(feature = "arithmetic")]
58 #[cfg_attr(docsrs, doc(cfg(feature = "arithmetic")))]
59 pub fn to_scalar(&self) -> Scalar<C>
60 where
61 C: ProjectiveArithmetic,
62 {
63 self.clone().into_scalar()
64 }
65
66 #[cfg(feature = "arithmetic")]
68 #[cfg_attr(docsrs, doc(cfg(feature = "arithmetic")))]
69 pub fn into_scalar(self) -> Scalar<C>
70 where
71 C: ProjectiveArithmetic,
72 {
73 Scalar::<C>::from_repr(self.inner).expect("ScalarBytes order invariant violated")
74 }
75
76 pub fn as_bytes(&self) -> &FieldBytes<C> {
78 &self.inner
79 }
80
81 pub fn into_bytes(self) -> FieldBytes<C> {
83 self.inner
84 }
85
86 pub fn zero() -> Self {
88 Self {
89 inner: Default::default(),
90 }
91 }
92
93 pub fn is_zero(&self) -> Choice {
95 self.ct_eq(&Self::zero())
96 }
97}
98
99impl<C> AsRef<FieldBytes<C>> for ScalarBytes<C>
100where
101 C: Curve,
102{
103 fn as_ref(&self) -> &FieldBytes<C> {
104 &self.inner
105 }
106}
107
108impl<C> AsRef<[u8]> for ScalarBytes<C>
109where
110 C: Curve,
111{
112 fn as_ref(&self) -> &[u8] {
113 self.inner.as_slice()
114 }
115}
116
117impl<C> ConditionallySelectable for ScalarBytes<C>
118where
119 Self: Copy,
120 C: Curve,
121{
122 fn conditional_select(a: &Self, b: &Self, choice: Choice) -> Self {
123 let mut inner = FieldBytes::<C>::default();
124
125 for (i, (byte_a, byte_b)) in a.inner.iter().zip(b.inner.iter()).enumerate() {
126 inner[i] = u8::conditional_select(byte_a, byte_b, choice)
127 }
128
129 Self { inner }
130 }
131}
132
133impl<C> ConstantTimeEq for ScalarBytes<C>
134where
135 C: Curve,
136{
137 fn ct_eq(&self, other: &Self) -> Choice {
138 self.inner
139 .iter()
140 .zip(other.inner.iter())
141 .fold(Choice::from(0u8), |acc, (a, b)| acc & a.ct_eq(b))
142 }
143}
144
145impl<C> Copy for ScalarBytes<C>
146where
147 C: Curve,
148 FieldBytes<C>: Copy,
149{
150}
151
152impl<C> Default for ScalarBytes<C>
153where
154 C: Curve,
155{
156 fn default() -> Self {
157 Self::zero()
158 }
159}
160
161impl<C> From<ScalarBytes<C>> for FieldBytes<C>
162where
163 C: Curve,
164{
165 fn from(scalar_bytes: ScalarBytes<C>) -> FieldBytes<C> {
166 scalar_bytes.inner
167 }
168}
169
170impl<C> From<&ScalarBytes<C>> for FieldBytes<C>
171where
172 C: Curve,
173{
174 fn from(scalar_bytes: &ScalarBytes<C>) -> FieldBytes<C> {
175 scalar_bytes.inner.clone()
176 }
177}
178
179#[cfg(feature = "arithmetic")]
180impl<C> From<NonZeroScalar<C>> for ScalarBytes<C>
181where
182 C: Curve + ProjectiveArithmetic,
183{
184 fn from(scalar: NonZeroScalar<C>) -> ScalarBytes<C> {
185 Self::from(&scalar)
186 }
187}
188
189#[cfg(feature = "arithmetic")]
190impl<C> From<&NonZeroScalar<C>> for ScalarBytes<C>
191where
192 C: Curve + ProjectiveArithmetic,
193{
194 fn from(scalar: &NonZeroScalar<C>) -> ScalarBytes<C> {
195 ScalarBytes {
196 inner: scalar.into(),
197 }
198 }
199}
200
201#[cfg(feature = "arithmetic")]
202impl<C> TryFrom<ScalarBytes<C>> for NonZeroScalar<C>
203where
204 C: Curve + ProjectiveArithmetic,
205{
206 type Error = Error;
207
208 fn try_from(bytes: ScalarBytes<C>) -> Result<NonZeroScalar<C>> {
209 NonZeroScalar::<C>::from_repr(bytes.inner).ok_or(Error)
210 }
211}
212
213impl<C> PartialEq for ScalarBytes<C>
214where
215 C: Curve,
216{
217 fn eq(&self, other: &Self) -> bool {
218 self.ct_eq(other).into()
219 }
220}
221
222impl<C> TryFrom<&[u8]> for ScalarBytes<C>
223where
224 C: Curve,
225{
226 type Error = Error;
227
228 fn try_from(bytes: &[u8]) -> Result<Self> {
229 if bytes.len() == C::UInt::BYTE_SIZE {
230 Option::from(ScalarBytes::new(GenericArray::clone_from_slice(bytes))).ok_or(Error)
231 } else {
232 Err(Error)
233 }
234 }
235}
236
237#[cfg(feature = "zeroize")]
238impl<C> Zeroize for ScalarBytes<C>
239where
240 C: Curve,
241{
242 fn zeroize(&mut self) {
243 self.inner.zeroize();
244 }
245}
246
247#[cfg(all(test, feature = "dev"))]
248mod tests {
249 use crate::dev::MockCurve;
250 use core::convert::TryFrom;
251 use hex_literal::hex;
252
253 type ScalarBytes = super::ScalarBytes<MockCurve>;
254
255 const SCALAR_REPR_ZERO: [u8; 32] = [0u8; 32];
256
257 const SCALAR_REPR_IN_RANGE: [u8; 32] =
258 hex!("FFFFFFFF 00000000 FFFFFFFF FFFFFFFF BCE6FAAD A7179E84 F3B9CAC2 FC632550");
259
260 const SCALAR_REPR_ORDER: [u8; 32] =
261 hex!("FFFFFFFF 00000000 FFFFFFFF FFFFFFFF BCE6FAAD A7179E84 F3B9CAC2 FC632551");
262
263 const SCALAR_REPR_MAX: [u8; 32] =
264 hex!("FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF");
265
266 #[test]
267 fn scalar_in_range() {
268 assert!(ScalarBytes::try_from(SCALAR_REPR_ZERO.as_ref()).is_ok());
269 assert!(ScalarBytes::try_from(SCALAR_REPR_IN_RANGE.as_ref()).is_ok());
270 }
271
272 #[test]
273 fn scalar_with_overflow() {
274 assert!(ScalarBytes::try_from(SCALAR_REPR_ORDER.as_ref()).is_err());
275 assert!(ScalarBytes::try_from(SCALAR_REPR_MAX.as_ref()).is_err());
276 }
277}