1// Copyright 2015-2019 Brian Smith.
2//
3// Permission to use, copy, modify, and/or distribute this software for any
4// purpose with or without fee is hereby granted, provided that the above
5// copyright notice and this permission notice appear in all copies.
6//
7// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
8// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
10// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
1415use crate::{arithmetic::limbs_from_hex, digest, error, limb};
1617#[repr(transparent)]
18pub struct Scalar([u8; SCALAR_LEN]);
1920pub const SCALAR_LEN: usize = 32;
2122impl Scalar {
23// Constructs a `Scalar` from `bytes`, failing if `bytes` encodes a scalar
24 // that not in the range [0, n).
25pub fn from_bytes_checked(bytes: [u8; SCALAR_LEN]) -> Result<Self, error::Unspecified> {
26const ORDER: [limb::Limb; SCALAR_LEN / limb::LIMB_BYTES] =
27 limbs_from_hex("1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed");
2829// `bytes` is in little-endian order.
30let mut reversed = bytes;
31 reversed.reverse();
3233let mut limbs = [0; SCALAR_LEN / limb::LIMB_BYTES];
34 limb::parse_big_endian_in_range_and_pad_consttime(
35 untrusted::Input::from(&reversed),
36 limb::AllowZero::Yes,
37&ORDER,
38&mut limbs,
39 )?;
4041Ok(Self(bytes))
42 }
4344// Constructs a `Scalar` from `digest` reduced modulo n.
45pub fn from_sha512_digest_reduced(digest: digest::Digest) -> Self {
46prefixed_extern! {
47fn x25519_sc_reduce(s: &mut UnreducedScalar);
48 }
49let mut unreduced = [0u8; digest::SHA512_OUTPUT_LEN];
50 unreduced.copy_from_slice(digest.as_ref());
51unsafe { x25519_sc_reduce(&mut unreduced) };
52Self((&unreduced[..SCALAR_LEN]).try_into().unwrap())
53 }
54}
5556#[repr(transparent)]
57pub struct MaskedScalar([u8; SCALAR_LEN]);
5859impl MaskedScalar {
60pub fn from_bytes_masked(bytes: [u8; SCALAR_LEN]) -> Self {
61prefixed_extern! {
62fn x25519_sc_mask(a: &mut [u8; SCALAR_LEN]);
63 }
64let mut r = Self(bytes);
65unsafe { x25519_sc_mask(&mut r.0) };
66 r
67 }
68}
6970impl From<MaskedScalar> for Scalar {
71fn from(MaskedScalar(scalar): MaskedScalar) -> Self {
72Self(scalar)
73 }
74}
7576type UnreducedScalar = [u8; UNREDUCED_SCALAR_LEN];
77const UNREDUCED_SCALAR_LEN: usize = SCALAR_LEN * 2;