Group trait overhaul (#52)
* Decouple element from `Group` * Change `SUITE_ID` to `u16` and rework `get_context_string()` * Rework scalar de-serialization * Rename `Group` methods - `random_nonzero_scalar` -> `random_scalar` - `scalar_as_bytes` -> `serialize_scalar` - `scalar_invert` -> `invert_scalar` * Rework element de-serialization * Rename and remove `Group` methods `to_arr` -> `serialize_elem` `base_point` -> `base_elem` `is_identity` -> removed `identity` -> `identity_elem` `zero_scalar` -> hidden behind `cfg(test)` * Sort `Group` methods * Rework `expand_message_xmd` and remove utility * Improve P256 `hash_to_scalar`
This commit is contained in:
+56
-54
@@ -5,74 +5,82 @@
|
||||
// License, Version 2.0 found in the LICENSE-APACHE file in the root directory
|
||||
// of this source tree.
|
||||
|
||||
use core::ops::Add;
|
||||
use core::convert::TryFrom;
|
||||
|
||||
use digest::core_api::BlockSizeUser;
|
||||
use digest::core_api::{Block, BlockSizeUser};
|
||||
use digest::{Digest, FixedOutputReset};
|
||||
use generic_array::sequence::Concat;
|
||||
use generic_array::typenum::{Unsigned, U1, U2};
|
||||
use generic_array::typenum::{IsLess, NonZero, Unsigned, U65536};
|
||||
use generic_array::{ArrayLength, GenericArray};
|
||||
|
||||
use crate::util::i2osp;
|
||||
use crate::{Error, Result};
|
||||
|
||||
// Computes ceil(x / y)
|
||||
fn div_ceil(x: usize, y: usize) -> usize {
|
||||
let additive = (x % y != 0) as usize;
|
||||
x / y + additive
|
||||
}
|
||||
|
||||
fn xor<L: ArrayLength<u8>>(x: GenericArray<u8, L>, y: GenericArray<u8, L>) -> GenericArray<u8, L> {
|
||||
x.into_iter().zip(y).map(|(x1, x2)| x1 ^ x2).collect()
|
||||
}
|
||||
|
||||
/// Corresponds to the expand_message_xmd() function defined in
|
||||
/// <https://www.ietf.org/archive/id/draft-irtf-cfrg-hash-to-curve-10.txt>
|
||||
pub fn expand_message_xmd<
|
||||
'a,
|
||||
H: BlockSizeUser + Digest + FixedOutputReset,
|
||||
L: ArrayLength<u8>,
|
||||
M: IntoIterator<Item = &'a [u8]>,
|
||||
D: ArrayLength<u8> + Add<U1>,
|
||||
>(
|
||||
msg: M,
|
||||
dst: GenericArray<u8, D>,
|
||||
pub fn expand_message_xmd<H: BlockSizeUser + Digest + FixedOutputReset, L: ArrayLength<u8>>(
|
||||
msg: &[&[u8]],
|
||||
dst: &[u8],
|
||||
) -> Result<GenericArray<u8, L>>
|
||||
where
|
||||
<D as Add<U1>>::Output: ArrayLength<u8>,
|
||||
// Constraint set by `expand_message_xmd`:
|
||||
// https://www.ietf.org/archive/id/draft-irtf-cfrg-hash-to-curve-13.html#section-5.4.1-6
|
||||
L: NonZero + IsLess<U65536>,
|
||||
{
|
||||
let digest_len = H::OutputSize::USIZE;
|
||||
let ell = div_ceil(L::USIZE, digest_len);
|
||||
if ell > 255 {
|
||||
// DST, a byte string of at most 255 bytes.
|
||||
let dst_len = u8::try_from(dst.len()).map_err(|_| Error::HashToCurveError)?;
|
||||
|
||||
// b_in_bytes, b / 8 for b the output size of H in bits.
|
||||
let b_in_bytes = H::OutputSize::to_usize();
|
||||
|
||||
// Constraint set by `expand_message_xmd`:
|
||||
// https://www.ietf.org/archive/id/draft-irtf-cfrg-hash-to-curve-13.html#section-5.4.1-4
|
||||
if b_in_bytes > H::BlockSize::USIZE {
|
||||
return Err(Error::HashToCurveError);
|
||||
}
|
||||
let dst_prime = dst.concat(i2osp::<U1>(D::USIZE)?);
|
||||
let z_pad = i2osp::<H::BlockSize>(0)?;
|
||||
let l_i_b_str = i2osp::<U2>(L::USIZE)?;
|
||||
|
||||
let mut h = H::new();
|
||||
// ell = ceil(len_in_bytes / b_in_bytes)
|
||||
// ABORT if ell > 255
|
||||
let ell = u8::try_from((L::USIZE + b_in_bytes - 1) / b_in_bytes)
|
||||
.map_err(|_| Error::HashToCurveError)?;
|
||||
|
||||
let mut hash = H::new();
|
||||
|
||||
// b_0 = H(msg_prime)
|
||||
// msg_prime = Z_pad || msg || l_i_b_str || I2OSP(0, 1) || DST_prime
|
||||
Digest::update(&mut h, z_pad);
|
||||
for bytes in msg {
|
||||
Digest::update(&mut h, bytes)
|
||||
// Z_pad = I2OSP(0, s_in_bytes)
|
||||
// s_in_bytes, the input block size of H, measured in bytes
|
||||
Digest::update(&mut hash, Block::<H>::default());
|
||||
for msg in msg {
|
||||
Digest::update(&mut hash, msg);
|
||||
}
|
||||
Digest::update(&mut h, l_i_b_str);
|
||||
Digest::update(&mut h, i2osp::<U1>(0)?);
|
||||
Digest::update(&mut h, &dst_prime);
|
||||
// l_i_b_str = I2OSP(len_in_bytes, 2)
|
||||
Digest::update(&mut hash, L::U16.to_be_bytes());
|
||||
Digest::update(&mut hash, [0]);
|
||||
// DST_prime = DST || I2OSP(len(DST), 1)
|
||||
Digest::update(&mut hash, dst);
|
||||
Digest::update(&mut hash, [dst_len]);
|
||||
let b_0 = hash.finalize_reset();
|
||||
|
||||
// b[0]
|
||||
let b_0 = h.finalize_reset();
|
||||
let mut b_i = GenericArray::default();
|
||||
|
||||
let mut uniform_bytes = GenericArray::default();
|
||||
|
||||
for (i, chunk) in (1..(ell + 1)).zip(uniform_bytes.chunks_mut(digest_len)) {
|
||||
Digest::update(&mut h, xor(b_0.clone(), b_i.clone()));
|
||||
Digest::update(&mut h, i2osp::<U1>(i)?);
|
||||
Digest::update(&mut h, &dst_prime);
|
||||
b_i = h.finalize_reset();
|
||||
chunk.copy_from_slice(&b_i[..digest_len.min(chunk.len())]);
|
||||
// b_1 = H(b_0 || I2OSP(1, 1) || DST_prime)
|
||||
// for i in (2, ..., ell):
|
||||
for (i, chunk) in (1..(ell + 1)).zip(uniform_bytes.chunks_mut(b_in_bytes)) {
|
||||
// b_i = H(strxor(b_0, b_(i - 1)) || I2OSP(i, 1) || DST_prime)
|
||||
Digest::update(&mut hash, xor(b_0.clone(), b_i.clone()));
|
||||
Digest::update(&mut hash, [i]);
|
||||
// DST_prime = DST || I2OSP(len(DST), 1)
|
||||
Digest::update(&mut hash, dst);
|
||||
Digest::update(&mut hash, [dst_len]);
|
||||
b_i = hash.finalize_reset();
|
||||
// uniform_bytes = b_1 || ... || b_ell
|
||||
// return substr(uniform_bytes, 0, len_in_bytes)
|
||||
chunk.copy_from_slice(&b_i[..b_in_bytes.min(chunk.len())]);
|
||||
}
|
||||
|
||||
Ok(uniform_bytes)
|
||||
@@ -81,7 +89,6 @@ where
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use generic_array::typenum::{U128, U32};
|
||||
use generic_array::GenericArray;
|
||||
|
||||
struct Params {
|
||||
msg: &'static str,
|
||||
@@ -91,6 +98,8 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_expand_message_xmd() {
|
||||
const DST: [u8; 27] = *b"QUUX-V01-CS02-with-expander";
|
||||
|
||||
// Test vectors taken from Section K.1 of https://www.ietf.org/archive/id/draft-irtf-cfrg-hash-to-curve-10.txt
|
||||
let test_vectors: alloc::vec::Vec<Params> = alloc::vec![
|
||||
Params {
|
||||
@@ -190,20 +199,13 @@ mod tests {
|
||||
378fba044a31f5cb44583a892f5969dcd73b3fa128816e",
|
||||
},
|
||||
];
|
||||
let dst = GenericArray::from(*b"QUUX-V01-CS02-with-expander");
|
||||
|
||||
for tv in test_vectors {
|
||||
let uniform_bytes = match tv.len_in_bytes {
|
||||
32 => super::expand_message_xmd::<sha2::Sha256, U32, _, _>(
|
||||
Some(tv.msg.as_bytes()),
|
||||
dst,
|
||||
)
|
||||
.map(|bytes| bytes.to_vec()),
|
||||
128 => super::expand_message_xmd::<sha2::Sha256, U128, _, _>(
|
||||
Some(tv.msg.as_bytes()),
|
||||
dst,
|
||||
)
|
||||
.map(|bytes| bytes.to_vec()),
|
||||
32 => super::expand_message_xmd::<sha2::Sha256, U32>(&[tv.msg.as_bytes()], &DST)
|
||||
.map(|bytes| bytes.to_vec()),
|
||||
128 => super::expand_message_xmd::<sha2::Sha256, U128>(&[tv.msg.as_bytes()], &DST)
|
||||
.map(|bytes| bytes.to_vec()),
|
||||
_ => unimplemented!(),
|
||||
}
|
||||
.unwrap();
|
||||
|
||||
+48
-87
@@ -18,47 +18,36 @@ use core::ops::{Add, Mul, Sub};
|
||||
|
||||
use digest::core_api::BlockSizeUser;
|
||||
use digest::{Digest, FixedOutputReset};
|
||||
use generic_array::typenum::U1;
|
||||
use generic_array::{ArrayLength, GenericArray};
|
||||
use rand_core::{CryptoRng, RngCore};
|
||||
#[cfg(feature = "ristretto255")]
|
||||
pub use ristretto::Ristretto255;
|
||||
use subtle::ConstantTimeEq;
|
||||
use zeroize::Zeroize;
|
||||
|
||||
use crate::{Error, Result};
|
||||
use crate::voprf::Mode;
|
||||
use crate::Result;
|
||||
|
||||
pub(crate) const STR_HASH_TO_SCALAR: [u8; 13] = *b"HashToScalar-";
|
||||
pub(crate) const STR_HASH_TO_GROUP: [u8; 12] = *b"HashToGroup-";
|
||||
|
||||
/// A prime-order subgroup of a base field (EC, prime-order field ...). This
|
||||
/// subgroup is noted additively — as in the draft RFC — in this trait.
|
||||
pub trait Group:
|
||||
Copy
|
||||
+ Sized
|
||||
+ ConstantTimeEq
|
||||
+ for<'a> Mul<&'a <Self as Group>::Scalar, Output = Self>
|
||||
+ for<'a> Add<&'a Self, Output = Self>
|
||||
{
|
||||
pub trait Group {
|
||||
/// The ciphersuite identifier as dictated by
|
||||
/// <https://www.ietf.org/archive/id/draft-irtf-cfrg-voprf-05.txt>
|
||||
const SUITE_ID: usize;
|
||||
const SUITE_ID: u16;
|
||||
|
||||
/// transforms a password and domain separation tag (DST) into a curve point
|
||||
fn hash_to_curve<H: BlockSizeUser + Digest + FixedOutputReset, D: ArrayLength<u8> + Add<U1>>(
|
||||
msg: &[u8],
|
||||
dst: GenericArray<u8, D>,
|
||||
) -> Result<Self>
|
||||
where
|
||||
<D as Add<U1>>::Output: ArrayLength<u8>;
|
||||
/// The type of group elements
|
||||
type Elem: Copy
|
||||
+ Sized
|
||||
+ ConstantTimeEq
|
||||
+ Zeroize
|
||||
+ for<'a> Mul<&'a Self::Scalar, Output = Self::Elem>
|
||||
+ for<'a> Add<&'a Self::Elem, Output = Self::Elem>;
|
||||
|
||||
/// Hashes a slice of pseudo-random bytes to a scalar
|
||||
fn hash_to_scalar<
|
||||
'a,
|
||||
H: BlockSizeUser + Digest + FixedOutputReset,
|
||||
D: ArrayLength<u8> + Add<U1>,
|
||||
I: IntoIterator<Item = &'a [u8]>,
|
||||
>(
|
||||
input: I,
|
||||
dst: GenericArray<u8, D>,
|
||||
) -> Result<Self::Scalar>
|
||||
where
|
||||
<D as Add<U1>>::Output: ArrayLength<u8>;
|
||||
/// The byte length necessary to represent group elements
|
||||
type ElemLen: ArrayLength<u8> + 'static;
|
||||
|
||||
/// The type of base field scalars
|
||||
type Scalar: Zeroize
|
||||
@@ -67,79 +56,51 @@ pub trait Group:
|
||||
+ for<'a> Add<&'a Self::Scalar, Output = Self::Scalar>
|
||||
+ for<'a> Sub<&'a Self::Scalar, Output = Self::Scalar>
|
||||
+ for<'a> Mul<&'a Self::Scalar, Output = Self::Scalar>;
|
||||
|
||||
/// The byte length necessary to represent scalars
|
||||
type ScalarLen: ArrayLength<u8> + 'static;
|
||||
|
||||
/// Return a scalar from its fixed-length bytes representation, without
|
||||
/// checking if the scalar is zero.
|
||||
fn from_scalar_slice_unchecked(
|
||||
scalar_bits: &GenericArray<u8, Self::ScalarLen>,
|
||||
/// transforms a password and domain separation tag (DST) into a curve point
|
||||
fn hash_to_curve<H: BlockSizeUser + Digest + FixedOutputReset>(
|
||||
msg: &[&[u8]],
|
||||
mode: Mode,
|
||||
) -> Result<Self::Elem>;
|
||||
|
||||
/// Hashes a slice of pseudo-random bytes to a scalar
|
||||
fn hash_to_scalar<H: BlockSizeUser + Digest + FixedOutputReset>(
|
||||
input: &[&[u8]],
|
||||
mode: Mode,
|
||||
) -> Result<Self::Scalar>;
|
||||
|
||||
/// Return a scalar from its fixed-length bytes representation. If the
|
||||
/// scalar is zero, then return an error.
|
||||
fn from_scalar_slice<'a>(
|
||||
scalar_bits: impl Into<&'a GenericArray<u8, Self::ScalarLen>>,
|
||||
) -> Result<Self::Scalar> {
|
||||
let scalar = Self::from_scalar_slice_unchecked(scalar_bits.into())?;
|
||||
if scalar.ct_eq(&Self::scalar_zero()).into() {
|
||||
return Err(Error::ZeroScalarError);
|
||||
}
|
||||
Ok(scalar)
|
||||
}
|
||||
/// Get the base point for the group
|
||||
fn base_elem() -> Self::Elem;
|
||||
|
||||
/// picks a scalar at random
|
||||
fn random_nonzero_scalar<R: RngCore + CryptoRng>(rng: &mut R) -> Self::Scalar;
|
||||
/// Serializes a scalar to bytes
|
||||
fn scalar_as_bytes(scalar: Self::Scalar) -> GenericArray<u8, Self::ScalarLen>;
|
||||
/// The multiplicative inverse of this scalar
|
||||
fn scalar_invert(scalar: &Self::Scalar) -> Self::Scalar;
|
||||
/// Returns the identity group element
|
||||
fn identity_elem() -> Self::Elem;
|
||||
|
||||
/// The byte length necessary to represent group elements
|
||||
type ElemLen: ArrayLength<u8> + 'static;
|
||||
|
||||
/// Return an element from its fixed-length bytes representation. This is
|
||||
/// the unchecked version, which does not check for deserializing the
|
||||
/// identity element
|
||||
fn from_element_slice_unchecked(element_bits: &GenericArray<u8, Self::ElemLen>)
|
||||
-> Result<Self>;
|
||||
/// Serializes the `self` group element
|
||||
fn serialize_elem(elem: Self::Elem) -> GenericArray<u8, Self::ElemLen>;
|
||||
|
||||
/// Return an element from its fixed-length bytes representation. If the
|
||||
/// element is the identity element, return an error.
|
||||
fn from_element_slice<'a>(
|
||||
element_bits: impl Into<&'a GenericArray<u8, Self::ElemLen>>,
|
||||
) -> Result<Self> {
|
||||
let elem = Self::from_element_slice_unchecked(element_bits.into())?;
|
||||
fn deserialize_elem(element_bits: &GenericArray<u8, Self::ElemLen>) -> Result<Self::Elem>;
|
||||
|
||||
if Self::ct_eq(&elem, &<Self as Group>::identity()).into() {
|
||||
// found the identity element
|
||||
return Err(Error::PointError);
|
||||
}
|
||||
/// picks a scalar at random
|
||||
fn random_scalar<R: RngCore + CryptoRng>(rng: &mut R) -> Self::Scalar;
|
||||
|
||||
Ok(elem)
|
||||
}
|
||||
|
||||
/// Serializes the `self` group element
|
||||
fn to_arr(&self) -> GenericArray<u8, Self::ElemLen>;
|
||||
|
||||
/// Get the base point for the group
|
||||
fn base_point() -> Self;
|
||||
|
||||
/// Returns if the group element is equal to the identity (1)
|
||||
fn is_identity(&self) -> bool {
|
||||
self.ct_eq(&<Self as Group>::identity()).into()
|
||||
}
|
||||
|
||||
/// Returns the identity group element
|
||||
fn identity() -> Self;
|
||||
/// The multiplicative inverse of this scalar
|
||||
fn invert_scalar(scalar: Self::Scalar) -> Self::Scalar;
|
||||
|
||||
/// Returns the scalar representing zero
|
||||
fn scalar_zero() -> Self::Scalar;
|
||||
#[cfg(test)]
|
||||
fn zero_scalar() -> Self::Scalar;
|
||||
|
||||
/// Set the contents of self to the identity value
|
||||
fn zeroize(&mut self) {
|
||||
*self = <Self as Group>::identity();
|
||||
}
|
||||
/// Serializes a scalar to bytes
|
||||
fn serialize_scalar(scalar: Self::Scalar) -> GenericArray<u8, Self::ScalarLen>;
|
||||
|
||||
/// Return a scalar from its fixed-length bytes representation. If the
|
||||
/// scalar is zero or invalid, then return an error.
|
||||
fn deserialize_scalar(scalar_bits: &GenericArray<u8, Self::ScalarLen>) -> Result<Self::Scalar>;
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
+77
-78
@@ -18,22 +18,26 @@ use core::str::FromStr;
|
||||
|
||||
use digest::core_api::BlockSizeUser;
|
||||
use digest::{Digest, FixedOutputReset};
|
||||
use generic_array::typenum::{Unsigned, U1, U2, U32, U33, U48};
|
||||
use generic_array::sequence::Concat;
|
||||
use generic_array::typenum::{Unsigned, U2, U32, U33, U48};
|
||||
use generic_array::{ArrayLength, GenericArray};
|
||||
use num_bigint::{BigInt, Sign};
|
||||
use num_integer::Integer;
|
||||
use num_traits::{One, ToPrimitive, Zero};
|
||||
use once_cell::unsync::Lazy;
|
||||
use p256_::elliptic_curve::bigint::{Encoding, U384};
|
||||
use p256_::elliptic_curve::group::prime::PrimeCurveAffine;
|
||||
use p256_::elliptic_curve::group::GroupEncoding;
|
||||
use p256_::elliptic_curve::ops::Reduce;
|
||||
use p256_::elliptic_curve::sec1::{FromEncodedPoint, ToEncodedPoint};
|
||||
#[cfg(test)]
|
||||
use p256_::elliptic_curve::Field;
|
||||
use p256_::{AffinePoint, EncodedPoint, ProjectivePoint};
|
||||
use p256_::{AffinePoint, EncodedPoint, NistP256, ProjectivePoint, PublicKey, Scalar, SecretKey};
|
||||
use rand_core::{CryptoRng, RngCore};
|
||||
use subtle::{Choice, ConditionallySelectable};
|
||||
|
||||
use super::Group;
|
||||
use crate::group::{STR_HASH_TO_GROUP, STR_HASH_TO_SCALAR};
|
||||
use crate::voprf::{self, Mode};
|
||||
use crate::{Error, Result};
|
||||
|
||||
// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-8.2
|
||||
@@ -41,18 +45,26 @@ use crate::{Error, Result};
|
||||
pub type L = U48;
|
||||
|
||||
#[cfg(feature = "p256")]
|
||||
impl Group for ProjectivePoint {
|
||||
const SUITE_ID: usize = 0x0003;
|
||||
impl Group for NistP256 {
|
||||
const SUITE_ID: u16 = 0x0003;
|
||||
|
||||
type Elem = ProjectivePoint;
|
||||
|
||||
type ElemLen = U33;
|
||||
|
||||
type Scalar = Scalar;
|
||||
|
||||
type ScalarLen = U32;
|
||||
|
||||
// Implements the `hash_to_curve()` function from
|
||||
// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-3
|
||||
fn hash_to_curve<H: BlockSizeUser + Digest + FixedOutputReset, D: ArrayLength<u8> + Add<U1>>(
|
||||
msg: &[u8],
|
||||
dst: GenericArray<u8, D>,
|
||||
) -> Result<Self>
|
||||
where
|
||||
<D as Add<U1>>::Output: ArrayLength<u8>,
|
||||
{
|
||||
fn hash_to_curve<H: BlockSizeUser + Digest + FixedOutputReset>(
|
||||
msg: &[&[u8]],
|
||||
mode: Mode,
|
||||
) -> Result<Self::Elem> {
|
||||
let dst =
|
||||
GenericArray::from(STR_HASH_TO_GROUP).concat(voprf::get_context_string::<Self>(mode));
|
||||
|
||||
// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-8.2
|
||||
// `p: 2^256 - 2^224 + 2^192 + 2^96 - 1`
|
||||
const P: Lazy<BigInt> = Lazy::new(|| {
|
||||
@@ -79,7 +91,7 @@ impl Group for ProjectivePoint {
|
||||
// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-5.3
|
||||
// `hash_to_field` calls `expand_message` with a `len_in_bytes` of `count * L`
|
||||
let uniform_bytes =
|
||||
super::expand::expand_message_xmd::<H, <L as Mul<U2>>::Output, _, _>(Some(msg), dst)?;
|
||||
super::expand::expand_message_xmd::<H, <L as Mul<U2>>::Output>(msg, &dst)?;
|
||||
|
||||
// hash to curve
|
||||
let (q0x, q0y) = hash_to_curve_simple_swu(&uniform_bytes[..L::USIZE], &A, &B, &P, &Z);
|
||||
@@ -100,88 +112,75 @@ impl Group for ProjectivePoint {
|
||||
}
|
||||
|
||||
// Implements the `HashToScalar()` function
|
||||
fn hash_to_scalar<
|
||||
'a,
|
||||
H: BlockSizeUser + Digest + FixedOutputReset,
|
||||
D: ArrayLength<u8> + Add<U1>,
|
||||
I: IntoIterator<Item = &'a [u8]>,
|
||||
>(
|
||||
input: I,
|
||||
dst: GenericArray<u8, D>,
|
||||
) -> Result<Self::Scalar>
|
||||
where
|
||||
<D as Add<U1>>::Output: ArrayLength<u8>,
|
||||
{
|
||||
fn hash_to_scalar<H: BlockSizeUser + Digest + FixedOutputReset>(
|
||||
input: &[&[u8]],
|
||||
mode: Mode,
|
||||
) -> Result<Self::Scalar> {
|
||||
let dst =
|
||||
GenericArray::from(STR_HASH_TO_SCALAR).concat(voprf::get_context_string::<Self>(mode));
|
||||
|
||||
// https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf#[{%22num%22:211,%22gen%22:0},{%22name%22:%22XYZ%22},70,700,0]
|
||||
// P-256 `n` is defined as
|
||||
// `115792089210356248762697446949407573529996955224135760342
|
||||
// 422259061068512044369`
|
||||
const N: Lazy<BigInt> = Lazy::new(|| {
|
||||
BigInt::from_str(
|
||||
"115792089210356248762697446949407573529996955224135760342422259061068512044369",
|
||||
)
|
||||
.unwrap()
|
||||
});
|
||||
const N: U384 =
|
||||
U384::from_be_hex("00000000000000000000000000000000FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551");
|
||||
|
||||
// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-5.3
|
||||
// `HashToScalar` is `hash_to_field`
|
||||
let uniform_bytes = super::expand::expand_message_xmd::<H, L, _, _>(input, dst)?;
|
||||
let bytes = BigInt::from_bytes_be(Sign::Plus, &uniform_bytes)
|
||||
.mod_floor(&N)
|
||||
.to_bytes_be()
|
||||
.1;
|
||||
let mut result = GenericArray::default();
|
||||
result[..bytes.len()].copy_from_slice(&bytes);
|
||||
let uniform_bytes = super::expand::expand_message_xmd::<H, L>(input, &dst)?;
|
||||
let bytes = Option::<U384>::from(U384::from_be_slice(&uniform_bytes).reduce(&N))
|
||||
.unwrap()
|
||||
.to_be_bytes();
|
||||
|
||||
Ok(p256_::Scalar::from_be_bytes_reduced(result))
|
||||
Ok(Scalar::from_be_bytes_reduced(
|
||||
GenericArray::clone_from_slice(&bytes[16..]),
|
||||
))
|
||||
}
|
||||
|
||||
type ElemLen = U33;
|
||||
type Scalar = p256_::Scalar;
|
||||
type ScalarLen = U32;
|
||||
|
||||
fn from_scalar_slice_unchecked(
|
||||
scalar_bits: &GenericArray<u8, Self::ScalarLen>,
|
||||
) -> Result<Self::Scalar> {
|
||||
Ok(Self::Scalar::from_be_bytes_reduced(*scalar_bits))
|
||||
fn base_elem() -> Self::Elem {
|
||||
ProjectivePoint::generator()
|
||||
}
|
||||
|
||||
fn random_nonzero_scalar<R: RngCore + CryptoRng>(rng: &mut R) -> Self::Scalar {
|
||||
Self::Scalar::random(rng)
|
||||
fn identity_elem() -> Self::Elem {
|
||||
ProjectivePoint::identity()
|
||||
}
|
||||
|
||||
fn scalar_as_bytes(scalar: Self::Scalar) -> GenericArray<u8, Self::ScalarLen> {
|
||||
scalar.into()
|
||||
}
|
||||
|
||||
fn scalar_invert(scalar: &Self::Scalar) -> Self::Scalar {
|
||||
scalar.invert().unwrap_or(Self::Scalar::zero())
|
||||
}
|
||||
|
||||
fn from_element_slice_unchecked(
|
||||
element_bits: &GenericArray<u8, Self::ElemLen>,
|
||||
) -> Result<Self> {
|
||||
Option::from(Self::from_bytes(element_bits)).ok_or(Error::PointError)
|
||||
}
|
||||
|
||||
fn to_arr(&self) -> GenericArray<u8, Self::ElemLen> {
|
||||
let bytes = self.to_affine().to_encoded_point(true);
|
||||
fn serialize_elem(elem: Self::Elem) -> GenericArray<u8, Self::ElemLen> {
|
||||
let bytes = elem.to_affine().to_encoded_point(true);
|
||||
let bytes = bytes.as_bytes();
|
||||
let mut result = GenericArray::default();
|
||||
result[..bytes.len()].copy_from_slice(bytes);
|
||||
result
|
||||
}
|
||||
|
||||
fn base_point() -> Self {
|
||||
Self::generator()
|
||||
fn deserialize_elem(element_bits: &GenericArray<u8, Self::ElemLen>) -> Result<Self::Elem> {
|
||||
PublicKey::from_sec1_bytes(element_bits)
|
||||
.map(|public_key| public_key.to_projective())
|
||||
.map_err(|_| Error::PointError)
|
||||
}
|
||||
|
||||
fn identity() -> Self {
|
||||
Self::identity()
|
||||
fn random_scalar<R: RngCore + CryptoRng>(rng: &mut R) -> Self::Scalar {
|
||||
*SecretKey::random(rng).to_nonzero_scalar()
|
||||
}
|
||||
|
||||
fn scalar_zero() -> Self::Scalar {
|
||||
Self::Scalar::zero()
|
||||
fn invert_scalar(scalar: Self::Scalar) -> Self::Scalar {
|
||||
Option::from(scalar.invert()).unwrap()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn zero_scalar() -> Self::Scalar {
|
||||
Scalar::zero()
|
||||
}
|
||||
|
||||
fn serialize_scalar(scalar: Self::Scalar) -> GenericArray<u8, Self::ScalarLen> {
|
||||
scalar.into()
|
||||
}
|
||||
|
||||
fn deserialize_scalar(scalar_bits: &GenericArray<u8, Self::ScalarLen>) -> Result<Self::Scalar> {
|
||||
SecretKey::from_be_bytes(scalar_bits)
|
||||
.map(|secret_key| *secret_key.to_nonzero_scalar())
|
||||
.map_err(|_| Error::ScalarError)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -459,6 +458,8 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn hash_to_curve_simple_swu() {
|
||||
const DST: [u8; 44] = *b"QUUX-V01-CS02-with-P256_XMD:SHA-256_SSWU_RO_";
|
||||
|
||||
const P: Lazy<BigInt> = Lazy::new(|| {
|
||||
BigInt::from_str(
|
||||
"115792089210356248762697446949407573530086143415290314195533631308867097853951",
|
||||
@@ -544,15 +545,13 @@ mod tests {
|
||||
q1y: "f6ed88a7aab56a488100e6f1174fa9810b47db13e86be999644922961206e184",
|
||||
},
|
||||
];
|
||||
let dst = GenericArray::from(*b"QUUX-V01-CS02-with-P256_XMD:SHA-256_SSWU_RO_");
|
||||
|
||||
for tv in test_vectors {
|
||||
let uniform_bytes =
|
||||
super::super::expand::expand_message_xmd::<sha2::Sha256, U96, _, _>(
|
||||
Some(tv.msg.as_bytes()),
|
||||
dst,
|
||||
)
|
||||
.unwrap();
|
||||
let uniform_bytes = super::super::expand::expand_message_xmd::<sha2::Sha256, U96>(
|
||||
&[tv.msg.as_bytes()],
|
||||
&DST,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let u0 = BigInt::from_bytes_be(Sign::Plus, &uniform_bytes[..48]).mod_floor(&P);
|
||||
let u1 = BigInt::from_bytes_be(Sign::Plus, &uniform_bytes[48..]).mod_floor(&P);
|
||||
|
||||
+64
-66
@@ -6,7 +6,6 @@
|
||||
// of this source tree.
|
||||
|
||||
use core::convert::TryInto;
|
||||
use core::ops::Add;
|
||||
|
||||
use curve25519_dalek::constants::RISTRETTO_BASEPOINT_POINT;
|
||||
use curve25519_dalek::ristretto::{CompressedRistretto, RistrettoPoint};
|
||||
@@ -14,53 +13,55 @@ use curve25519_dalek::scalar::Scalar;
|
||||
use curve25519_dalek::traits::Identity;
|
||||
use digest::core_api::BlockSizeUser;
|
||||
use digest::{Digest, FixedOutputReset};
|
||||
use generic_array::typenum::{U1, U32, U64};
|
||||
use generic_array::{ArrayLength, GenericArray};
|
||||
use generic_array::sequence::Concat;
|
||||
use generic_array::typenum::{U32, U64};
|
||||
use generic_array::GenericArray;
|
||||
use rand_core::{CryptoRng, RngCore};
|
||||
|
||||
use super::Group;
|
||||
use super::{expand, Group, STR_HASH_TO_GROUP, STR_HASH_TO_SCALAR};
|
||||
use crate::voprf::{self, Mode};
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// [`Group`] implementation for Ristretto255.
|
||||
pub struct Ristretto255;
|
||||
|
||||
// `cfg` here is only needed because of a bug in Rust's crate feature documentation. See: https://github.com/rust-lang/rust/issues/83428
|
||||
#[cfg(feature = "ristretto255")]
|
||||
/// The implementation of such a subgroup for Ristretto
|
||||
impl Group for RistrettoPoint {
|
||||
const SUITE_ID: usize = 0x0001;
|
||||
impl Group for Ristretto255 {
|
||||
const SUITE_ID: u16 = 0x0001;
|
||||
|
||||
type Elem = RistrettoPoint;
|
||||
|
||||
type ElemLen = U32;
|
||||
|
||||
type Scalar = Scalar;
|
||||
|
||||
type ScalarLen = U32;
|
||||
|
||||
// Implements the `hash_to_ristretto255()` function from
|
||||
// https://www.ietf.org/archive/id/draft-irtf-cfrg-hash-to-curve-10.txt
|
||||
fn hash_to_curve<H: BlockSizeUser + Digest + FixedOutputReset, D: ArrayLength<u8> + Add<U1>>(
|
||||
msg: &[u8],
|
||||
dst: GenericArray<u8, D>,
|
||||
) -> Result<Self>
|
||||
where
|
||||
<D as Add<U1>>::Output: ArrayLength<u8>,
|
||||
{
|
||||
let uniform_bytes = super::expand::expand_message_xmd::<H, U64, _, _>(Some(msg), dst)?;
|
||||
fn hash_to_curve<H: BlockSizeUser + Digest + FixedOutputReset>(
|
||||
msg: &[&[u8]],
|
||||
mode: Mode,
|
||||
) -> Result<Self::Elem> {
|
||||
let dst =
|
||||
GenericArray::from(STR_HASH_TO_GROUP).concat(voprf::get_context_string::<Self>(mode));
|
||||
|
||||
Ok(RistrettoPoint::from_uniform_bytes(
|
||||
uniform_bytes
|
||||
.as_slice()
|
||||
.try_into()
|
||||
.map_err(|_| Error::HashToCurveError)?,
|
||||
))
|
||||
let uniform_bytes = expand::expand_message_xmd::<H, U64>(msg, &dst)?;
|
||||
|
||||
Ok(RistrettoPoint::from_uniform_bytes(&uniform_bytes.into()))
|
||||
}
|
||||
|
||||
// Implements the `HashToScalar()` function from
|
||||
// https://www.ietf.org/archive/id/draft-irtf-cfrg-voprf-07.html#section-4.1
|
||||
fn hash_to_scalar<
|
||||
'a,
|
||||
H: BlockSizeUser + Digest + FixedOutputReset,
|
||||
D: ArrayLength<u8> + Add<U1>,
|
||||
I: IntoIterator<Item = &'a [u8]>,
|
||||
>(
|
||||
input: I,
|
||||
dst: GenericArray<u8, D>,
|
||||
) -> Result<Self::Scalar>
|
||||
where
|
||||
<D as Add<U1>>::Output: ArrayLength<u8>,
|
||||
{
|
||||
let uniform_bytes = super::expand::expand_message_xmd::<H, U64, _, _>(input, dst)?;
|
||||
fn hash_to_scalar<'a, H: BlockSizeUser + Digest + FixedOutputReset>(
|
||||
input: &[&[u8]],
|
||||
mode: Mode,
|
||||
) -> Result<Self::Scalar> {
|
||||
let dst =
|
||||
GenericArray::from(STR_HASH_TO_SCALAR).concat(voprf::get_context_string::<Self>(mode));
|
||||
|
||||
let uniform_bytes = expand::expand_message_xmd::<H, U64>(input, &dst)?;
|
||||
|
||||
Ok(Scalar::from_bytes_mod_order_wide(
|
||||
uniform_bytes
|
||||
@@ -70,15 +71,27 @@ impl Group for RistrettoPoint {
|
||||
))
|
||||
}
|
||||
|
||||
type Scalar = Scalar;
|
||||
type ScalarLen = U32;
|
||||
fn from_scalar_slice_unchecked(
|
||||
scalar_bits: &GenericArray<u8, Self::ScalarLen>,
|
||||
) -> Result<Self::Scalar> {
|
||||
Ok(Scalar::from_bytes_mod_order(*scalar_bits.as_ref()))
|
||||
fn base_elem() -> Self::Elem {
|
||||
RISTRETTO_BASEPOINT_POINT
|
||||
}
|
||||
|
||||
fn random_nonzero_scalar<R: RngCore + CryptoRng>(rng: &mut R) -> Self::Scalar {
|
||||
fn identity_elem() -> Self::Elem {
|
||||
RistrettoPoint::identity()
|
||||
}
|
||||
|
||||
// serialization of a group element
|
||||
fn serialize_elem(elem: Self::Elem) -> GenericArray<u8, Self::ElemLen> {
|
||||
elem.compress().to_bytes().into()
|
||||
}
|
||||
|
||||
fn deserialize_elem(element_bits: &GenericArray<u8, Self::ElemLen>) -> Result<Self::Elem> {
|
||||
CompressedRistretto::from_slice(element_bits)
|
||||
.decompress()
|
||||
.filter(|point| point != &RistrettoPoint::identity())
|
||||
.ok_or(Error::PointError)
|
||||
}
|
||||
|
||||
fn random_scalar<R: RngCore + CryptoRng>(rng: &mut R) -> Self::Scalar {
|
||||
loop {
|
||||
let scalar = {
|
||||
let mut scalar_bytes = [0u8; 64];
|
||||
@@ -92,37 +105,22 @@ impl Group for RistrettoPoint {
|
||||
}
|
||||
}
|
||||
|
||||
fn scalar_as_bytes(scalar: Self::Scalar) -> GenericArray<u8, Self::ScalarLen> {
|
||||
scalar.to_bytes().into()
|
||||
}
|
||||
|
||||
fn scalar_invert(scalar: &Self::Scalar) -> Self::Scalar {
|
||||
fn invert_scalar(scalar: Self::Scalar) -> Self::Scalar {
|
||||
scalar.invert()
|
||||
}
|
||||
|
||||
// The byte length necessary to represent group elements
|
||||
type ElemLen = U32;
|
||||
fn from_element_slice_unchecked(
|
||||
element_bits: &GenericArray<u8, Self::ElemLen>,
|
||||
) -> Result<Self> {
|
||||
CompressedRistretto::from_slice(element_bits)
|
||||
.decompress()
|
||||
.ok_or(Error::PointError)
|
||||
}
|
||||
// serialization of a group element
|
||||
fn to_arr(&self) -> GenericArray<u8, Self::ElemLen> {
|
||||
self.compress().to_bytes().into()
|
||||
#[cfg(test)]
|
||||
fn zero_scalar() -> Self::Scalar {
|
||||
Scalar::zero()
|
||||
}
|
||||
|
||||
fn base_point() -> Self {
|
||||
RISTRETTO_BASEPOINT_POINT
|
||||
fn serialize_scalar(scalar: Self::Scalar) -> GenericArray<u8, Self::ScalarLen> {
|
||||
scalar.to_bytes().into()
|
||||
}
|
||||
|
||||
fn identity() -> Self {
|
||||
<Self as Identity>::identity()
|
||||
}
|
||||
|
||||
fn scalar_zero() -> Self::Scalar {
|
||||
Self::Scalar::zero()
|
||||
fn deserialize_scalar(scalar_bits: &GenericArray<u8, Self::ScalarLen>) -> Result<Self::Scalar> {
|
||||
Scalar::from_canonical_bytes((*scalar_bits).into())
|
||||
.filter(|scalar| scalar != &Scalar::zero())
|
||||
.ok_or(Error::ScalarError)
|
||||
}
|
||||
}
|
||||
|
||||
+11
-11
@@ -16,18 +16,18 @@ use crate::{Error, Group, Result};
|
||||
fn test_group_properties() -> Result<()> {
|
||||
#[cfg(feature = "ristretto255")]
|
||||
{
|
||||
use curve25519_dalek::ristretto::RistrettoPoint;
|
||||
use crate::Ristretto255;
|
||||
|
||||
test_identity_element_error::<RistrettoPoint>()?;
|
||||
test_zero_scalar_error::<RistrettoPoint>()?;
|
||||
test_identity_element_error::<Ristretto255>()?;
|
||||
test_zero_scalar_error::<Ristretto255>()?;
|
||||
}
|
||||
|
||||
#[cfg(feature = "p256")]
|
||||
{
|
||||
use p256_::ProjectivePoint;
|
||||
use p256_::NistP256;
|
||||
|
||||
test_identity_element_error::<ProjectivePoint>()?;
|
||||
test_zero_scalar_error::<ProjectivePoint>()?;
|
||||
test_identity_element_error::<NistP256>()?;
|
||||
test_zero_scalar_error::<NistP256>()?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
@@ -35,8 +35,8 @@ fn test_group_properties() -> Result<()> {
|
||||
|
||||
// Checks that the identity element cannot be deserialized
|
||||
fn test_identity_element_error<G: Group>() -> Result<()> {
|
||||
let identity = G::identity();
|
||||
let result = G::from_element_slice(&identity.to_arr());
|
||||
let identity = G::identity_elem();
|
||||
let result = G::deserialize_elem(&G::serialize_elem(identity));
|
||||
assert!(matches!(result, Err(Error::PointError)));
|
||||
|
||||
Ok(())
|
||||
@@ -44,9 +44,9 @@ fn test_identity_element_error<G: Group>() -> Result<()> {
|
||||
|
||||
// Checks that the zero scalar cannot be deserialized
|
||||
fn test_zero_scalar_error<G: Group>() -> Result<()> {
|
||||
let zero_scalar = G::scalar_zero();
|
||||
let result = G::from_scalar_slice(&G::scalar_as_bytes(zero_scalar));
|
||||
assert!(matches!(result, Err(Error::ZeroScalarError)));
|
||||
let zero_scalar = G::zero_scalar();
|
||||
let result = G::deserialize_scalar(&G::serialize_scalar(zero_scalar));
|
||||
assert!(matches!(result, Err(Error::ScalarError)));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user