// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. use crate::errors::InternalPakeError; use curve25519_dalek::{ constants::RISTRETTO_BASEPOINT_POINT, ristretto::{CompressedRistretto, RistrettoPoint}, scalar::Scalar, traits::Identity, }; use generic_array::{ typenum::{U32, U64}, GenericArray, }; use std::convert::TryInto; use rand::{CryptoRng, RngCore}; use super::Group; /// The implementation of such a subgroup for Ristretto impl Group for RistrettoPoint { type Scalar = Scalar; type ScalarLen = U32; fn from_scalar_slice( scalar_bits: &GenericArray, ) -> Result { let mut bits = [0u8; 32]; bits.copy_from_slice(scalar_bits); Ok(Scalar::from_bytes_mod_order(bits)) } fn random_nonzero_scalar(rng: &mut R) -> Self::Scalar { loop { let scalar = { #[cfg(not(test))] { let mut scalar_bytes = [0u8; 64]; rng.fill_bytes(&mut scalar_bytes); Scalar::from_bytes_mod_order_wide(&scalar_bytes) } // Tests need an exact conversion from bytes to scalar, sampling only 32 bytes from rng #[cfg(test)] { let mut scalar_bytes = [0u8; 32]; rng.fill_bytes(&mut scalar_bytes); Scalar::from_bytes_mod_order(scalar_bytes) } }; if scalar != Scalar::zero() { break scalar; } } } fn scalar_as_bytes(scalar: Self::Scalar) -> GenericArray { scalar.to_bytes().into() } fn scalar_invert(scalar: &Self::Scalar) -> Self::Scalar { scalar.invert() } // The byte length necessary to represent group elements type ElemLen = U32; fn from_element_slice( element_bits: &GenericArray, ) -> Result { CompressedRistretto::from_slice(element_bits) .decompress() .ok_or(InternalPakeError::PointError) } // serialization of a group element fn to_arr(&self) -> GenericArray { let c = self.compress(); *GenericArray::from_slice(c.as_bytes()) } type UniformBytesLen = U64; fn hash_to_curve( uniform_bytes: &GenericArray, ) -> Result { // https://caniuse.rs/features/array_gt_32_impls let bits: [u8; 64] = { let mut bytes = [0u8; 64]; bytes.copy_from_slice(uniform_bytes); bytes }; Ok(RistrettoPoint::from_uniform_bytes(&bits)) } fn base_point() -> Self { RISTRETTO_BASEPOINT_POINT } fn mult_by_slice(&self, scalar: &GenericArray) -> Self { let arr: [u8; 32] = scalar.as_slice().try_into().expect("Wrong length"); self * Scalar::from_bits(arr) } /// Returns if the group element is equal to the identity (1) fn is_identity(&self) -> bool { self == &Self::identity() } fn ct_equal(&self, other: &Self) -> bool { constant_time_eq::constant_time_eq(&self.to_arr(), &other.to_arr()) } }