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:
+1
-1
@@ -24,7 +24,7 @@ p256 = [
|
||||
"once_cell",
|
||||
"p256_",
|
||||
]
|
||||
ristretto255 = []
|
||||
ristretto255 = ["generic-array/more_lengths"]
|
||||
ristretto255_fiat_u32 = ["curve25519-dalek/fiat_u32_backend", "ristretto255"]
|
||||
ristretto255_fiat_u64 = ["curve25519-dalek/fiat_u64_backend", "ristretto255"]
|
||||
ristretto255_simd = ["curve25519-dalek/simd_backend", "ristretto255"]
|
||||
|
||||
+2
-2
@@ -34,8 +34,8 @@ pub enum Error {
|
||||
ProofVerificationError,
|
||||
/// Encountered insufficient bytes when attempting to deserialize
|
||||
SizeError,
|
||||
/// Encountered a zero scalar
|
||||
ZeroScalarError,
|
||||
/// Encountered an invalid scalar
|
||||
ScalarError,
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
|
||||
+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(())
|
||||
}
|
||||
|
||||
+45
-38
@@ -24,7 +24,7 @@
|
||||
//! We will use the following choices in this example:
|
||||
//!
|
||||
//! ```ignore
|
||||
//! type Group = curve25519_dalek::ristretto::RistrettoPoint;
|
||||
//! type Group = voprf::Ristretto255;
|
||||
//! type Hash = sha2::Sha512;
|
||||
//! ```
|
||||
//!
|
||||
@@ -52,11 +52,11 @@
|
||||
//!
|
||||
//! ```
|
||||
//! # #[cfg(feature = "ristretto255")]
|
||||
//! # type Group = curve25519_dalek::ristretto::RistrettoPoint;
|
||||
//! # type Group = voprf::Ristretto255;
|
||||
//! # #[cfg(feature = "ristretto255")]
|
||||
//! # type Hash = sha2::Sha512;
|
||||
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
||||
//! # type Group = p256_::ProjectivePoint;
|
||||
//! # type Group = p256_::NistP256;
|
||||
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
||||
//! # type Hash = sha2::Sha256;
|
||||
//! use rand::rngs::OsRng;
|
||||
@@ -78,11 +78,11 @@
|
||||
//!
|
||||
//! ```
|
||||
//! # #[cfg(feature = "ristretto255")]
|
||||
//! # type Group = curve25519_dalek::ristretto::RistrettoPoint;
|
||||
//! # type Group = voprf::Ristretto255;
|
||||
//! # #[cfg(feature = "ristretto255")]
|
||||
//! # type Hash = sha2::Sha512;
|
||||
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
||||
//! # type Group = p256_::ProjectivePoint;
|
||||
//! # type Group = p256_::NistP256;
|
||||
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
||||
//! # type Hash = sha2::Sha256;
|
||||
//! use rand::rngs::OsRng;
|
||||
@@ -104,11 +104,11 @@
|
||||
//!
|
||||
//! ```
|
||||
//! # #[cfg(feature = "ristretto255")]
|
||||
//! # type Group = curve25519_dalek::ristretto::RistrettoPoint;
|
||||
//! # type Group = voprf::Ristretto255;
|
||||
//! # #[cfg(feature = "ristretto255")]
|
||||
//! # type Hash = sha2::Sha512;
|
||||
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
||||
//! # type Group = p256_::ProjectivePoint;
|
||||
//! # type Group = p256_::NistP256;
|
||||
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
||||
//! # type Hash = sha2::Sha256;
|
||||
//! # use voprf::NonVerifiableClient;
|
||||
@@ -136,11 +136,11 @@
|
||||
//!
|
||||
//! ```
|
||||
//! # #[cfg(feature = "ristretto255")]
|
||||
//! # type Group = curve25519_dalek::ristretto::RistrettoPoint;
|
||||
//! # type Group = voprf::Ristretto255;
|
||||
//! # #[cfg(feature = "ristretto255")]
|
||||
//! # type Hash = sha2::Sha512;
|
||||
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
||||
//! # type Group = p256_::ProjectivePoint;
|
||||
//! # type Group = p256_::NistP256;
|
||||
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
||||
//! # type Hash = sha2::Sha256;
|
||||
//! # use voprf::NonVerifiableClient;
|
||||
@@ -187,11 +187,11 @@
|
||||
//!
|
||||
//! ```
|
||||
//! # #[cfg(feature = "ristretto255")]
|
||||
//! # type Group = curve25519_dalek::ristretto::RistrettoPoint;
|
||||
//! # type Group = voprf::Ristretto255;
|
||||
//! # #[cfg(feature = "ristretto255")]
|
||||
//! # type Hash = sha2::Sha512;
|
||||
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
||||
//! # type Group = p256_::ProjectivePoint;
|
||||
//! # type Group = p256_::NistP256;
|
||||
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
||||
//! # type Hash = sha2::Sha256;
|
||||
//! use rand::rngs::OsRng;
|
||||
@@ -220,11 +220,11 @@
|
||||
//!
|
||||
//! ```
|
||||
//! # #[cfg(feature = "ristretto255")]
|
||||
//! # type Group = curve25519_dalek::ristretto::RistrettoPoint;
|
||||
//! # type Group = voprf::Ristretto255;
|
||||
//! # #[cfg(feature = "ristretto255")]
|
||||
//! # type Hash = sha2::Sha512;
|
||||
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
||||
//! # type Group = p256_::ProjectivePoint;
|
||||
//! # type Group = p256_::NistP256;
|
||||
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
||||
//! # type Hash = sha2::Sha256;
|
||||
//! use rand::rngs::OsRng;
|
||||
@@ -246,11 +246,11 @@
|
||||
//!
|
||||
//! ```
|
||||
//! # #[cfg(feature = "ristretto255")]
|
||||
//! # type Group = curve25519_dalek::ristretto::RistrettoPoint;
|
||||
//! # type Group = voprf::Ristretto255;
|
||||
//! # #[cfg(feature = "ristretto255")]
|
||||
//! # type Hash = sha2::Sha512;
|
||||
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
||||
//! # type Group = p256_::ProjectivePoint;
|
||||
//! # type Group = p256_::NistP256;
|
||||
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
||||
//! # type Hash = sha2::Sha256;
|
||||
//! # use voprf::VerifiableClient;
|
||||
@@ -279,11 +279,11 @@
|
||||
//!
|
||||
//! ```
|
||||
//! # #[cfg(feature = "ristretto255")]
|
||||
//! # type Group = curve25519_dalek::ristretto::RistrettoPoint;
|
||||
//! # type Group = voprf::Ristretto255;
|
||||
//! # #[cfg(feature = "ristretto255")]
|
||||
//! # type Hash = sha2::Sha512;
|
||||
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
||||
//! # type Group = p256_::ProjectivePoint;
|
||||
//! # type Group = p256_::NistP256;
|
||||
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
||||
//! # type Hash = sha2::Sha256;
|
||||
//! # use voprf::VerifiableClient;
|
||||
@@ -336,11 +336,11 @@
|
||||
//!
|
||||
//! ```
|
||||
//! # #[cfg(feature = "ristretto255")]
|
||||
//! # type Group = curve25519_dalek::ristretto::RistrettoPoint;
|
||||
//! # type Group = voprf::Ristretto255;
|
||||
//! # #[cfg(feature = "ristretto255")]
|
||||
//! # type Hash = sha2::Sha512;
|
||||
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
||||
//! # type Group = p256_::ProjectivePoint;
|
||||
//! # type Group = p256_::NistP256;
|
||||
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
||||
//! # type Hash = sha2::Sha256;
|
||||
//! # use voprf::VerifiableClient;
|
||||
@@ -364,11 +364,11 @@
|
||||
//!
|
||||
//! ```
|
||||
//! # #[cfg(feature = "ristretto255")]
|
||||
//! # type Group = curve25519_dalek::ristretto::RistrettoPoint;
|
||||
//! # type Group = voprf::Ristretto255;
|
||||
//! # #[cfg(feature = "ristretto255")]
|
||||
//! # type Hash = sha2::Sha512;
|
||||
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
||||
//! # type Group = p256_::ProjectivePoint;
|
||||
//! # type Group = p256_::NistP256;
|
||||
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
||||
//! # type Hash = sha2::Sha256;
|
||||
//! # use voprf::{VerifiableServerBatchEvaluatePrepareResult, VerifiableServerBatchEvaluateFinishResult, VerifiableClient};
|
||||
@@ -407,11 +407,11 @@
|
||||
//! ```
|
||||
//! # #[cfg(feature = "alloc")] {
|
||||
//! # #[cfg(feature = "ristretto255")]
|
||||
//! # type Group = curve25519_dalek::ristretto::RistrettoPoint;
|
||||
//! # type Group = voprf::Ristretto255;
|
||||
//! # #[cfg(feature = "ristretto255")]
|
||||
//! # type Hash = sha2::Sha512;
|
||||
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
||||
//! # type Group = p256_::ProjectivePoint;
|
||||
//! # type Group = p256_::NistP256;
|
||||
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
||||
//! # type Hash = sha2::Sha256;
|
||||
//! # use voprf::{VerifiableServerBatchEvaluateResult, VerifiableClient};
|
||||
@@ -446,11 +446,11 @@
|
||||
//! ```
|
||||
//! # #[cfg(feature = "alloc")] {
|
||||
//! # #[cfg(feature = "ristretto255")]
|
||||
//! # type Group = curve25519_dalek::ristretto::RistrettoPoint;
|
||||
//! # type Group = voprf::Ristretto255;
|
||||
//! # #[cfg(feature = "ristretto255")]
|
||||
//! # type Hash = sha2::Sha512;
|
||||
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
||||
//! # type Group = p256_::ProjectivePoint;
|
||||
//! # type Group = p256_::NistP256;
|
||||
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
||||
//! # type Hash = sha2::Sha256;
|
||||
//! # use voprf::{VerifiableServerBatchEvaluateResult, VerifiableClient};
|
||||
@@ -507,9 +507,10 @@
|
||||
//! - The `alloc` feature requires Rusts [`alloc`] crate and enables batching
|
||||
//! VOPRF evaluations.
|
||||
//!
|
||||
//! - The `p256` feature enables using p256 as the underlying group for the
|
||||
//! [Group] choice and increases the MSRV to 1.56. Note that this is currently
|
||||
//! an experimental feature ⚠️, and is not yet ready for production use.
|
||||
//! - The `p256` feature enables using [`NistP256`](p256_::NistP256) as the
|
||||
//! underlying group for the [Group] choice and increases the MSRV to 1.56.
|
||||
//! Note that this is currently an experimental feature ⚠️, and is not yet
|
||||
//! ready for production use.
|
||||
//!
|
||||
//! - The `serde` feature, enabled by default, provides convenience functions
|
||||
//! for serializing and deserializing with [serde](https://serde.rs/).
|
||||
@@ -520,18 +521,21 @@
|
||||
//! that need access to these raw values and are able to perform the necessary
|
||||
//! validations on them (such as being valid group elements).
|
||||
//!
|
||||
//! - The backend features are re-exported from [curve25519-dalek](https://doc.dalek.rs/curve25519_dalek/index.html#backends-and-features)
|
||||
//! and allow for selecting the corresponding backend for the curve arithmetic
|
||||
//! used. The `ristretto255_u64` feature is included as the default. Other
|
||||
//! features are mapped as `ristretto255_u32`, `ristretto255_fiat_u64` and
|
||||
//! `ristretto255_fiat_u32`. Any `ristretto255_*` backend feature will enable
|
||||
//! the `ristretto255` feature, which can be used too, but keep in mind that
|
||||
//! `curve25519-dalek` will fail to compile without a selected backend.
|
||||
//! - The `ristretto255` feature enables using [`Ristretto255`] as the
|
||||
//! underlying group for the [Group] choice. A backend feature, which are
|
||||
//! re-exported from [curve25519-dalek] and allow for selecting the
|
||||
//! corresponding backend for the curve arithmetic used, has to be selected,
|
||||
//! otherwise compilation will fail. The `ristretto255_u64` feature is
|
||||
//! included as the default. Other features are mapped as `ristretto255_u32`,
|
||||
//! `ristretto255_fiat_u64` and `ristretto255_fiat_u32`. Any `ristretto255_*`
|
||||
//! backend feature will enable the `ristretto255` feature.
|
||||
//!
|
||||
//! - The `ristretto255_simd` feature is re-exported from [curve25519-dalek](https://doc.dalek.rs/curve25519_dalek/index.html#backends-and-features)
|
||||
//! and enables parallel formulas, using either AVX2 or AVX512-IFMA. This will
|
||||
//! - The `ristretto255_simd` feature is re-exported from [curve25519-dalek] and
|
||||
//! enables parallel formulas, using either AVX2 or AVX512-IFMA. This will
|
||||
//! automatically enable the `ristretto255_u64` feature and requires Rust
|
||||
//! nightly.
|
||||
//!
|
||||
//! [curve25519-dalek]: (https://doc.dalek.rs/curve25519_dalek/index.html#backends-and-features)
|
||||
|
||||
#![deny(unsafe_code)]
|
||||
#![no_std]
|
||||
@@ -557,12 +561,15 @@ mod tests;
|
||||
|
||||
// Exports
|
||||
|
||||
#[cfg(feature = "ristretto255")]
|
||||
pub use group::Ristretto255;
|
||||
|
||||
pub use crate::error::{Error, Result};
|
||||
pub use crate::group::Group;
|
||||
#[cfg(feature = "alloc")]
|
||||
pub use crate::voprf::VerifiableServerBatchEvaluateResult;
|
||||
pub use crate::voprf::{
|
||||
BlindedElement, EvaluationElement, NonVerifiableClient, NonVerifiableClientBlindResult,
|
||||
BlindedElement, EvaluationElement, Mode, NonVerifiableClient, NonVerifiableClientBlindResult,
|
||||
NonVerifiableServer, NonVerifiableServerEvaluateResult, PreparedEvaluationElement,
|
||||
PreparedTscalar, Proof, VerifiableClient, VerifiableClientBatchFinalizeResult,
|
||||
VerifiableClientBlindResult, VerifiableServer, VerifiableServerBatchEvaluateFinishResult,
|
||||
|
||||
+17
-17
@@ -30,14 +30,14 @@ use crate::{
|
||||
impl<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> NonVerifiableClient<G, H> {
|
||||
/// Serialization into bytes
|
||||
pub fn serialize(&self) -> GenericArray<u8, G::ScalarLen> {
|
||||
G::scalar_as_bytes(self.blind)
|
||||
G::serialize_scalar(self.blind)
|
||||
}
|
||||
|
||||
/// Deserialization from bytes
|
||||
pub fn deserialize(input: &[u8]) -> Result<Self> {
|
||||
let mut input = input.iter().copied();
|
||||
|
||||
let blind = G::from_scalar_slice(&deserialize(&mut input)?)?;
|
||||
let blind = G::deserialize_scalar(&deserialize(&mut input)?)?;
|
||||
|
||||
Ok(Self {
|
||||
blind,
|
||||
@@ -53,15 +53,15 @@ impl<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> VerifiableClient<G,
|
||||
G::ScalarLen: Add<G::ElemLen>,
|
||||
Sum<G::ScalarLen, G::ElemLen>: ArrayLength<u8>,
|
||||
{
|
||||
G::scalar_as_bytes(self.blind).concat(self.blinded_element.to_arr())
|
||||
G::serialize_scalar(self.blind).concat(G::serialize_elem(self.blinded_element))
|
||||
}
|
||||
|
||||
/// Deserialization from bytes
|
||||
pub fn deserialize(input: &[u8]) -> Result<Self> {
|
||||
let mut input = input.iter().copied();
|
||||
|
||||
let blind = G::from_scalar_slice(&deserialize(&mut input)?)?;
|
||||
let blinded_element = G::from_element_slice(&deserialize(&mut input)?)?;
|
||||
let blind = G::deserialize_scalar(&deserialize(&mut input)?)?;
|
||||
let blinded_element = G::deserialize_elem(&deserialize(&mut input)?)?;
|
||||
|
||||
Ok(Self {
|
||||
blind,
|
||||
@@ -74,14 +74,14 @@ impl<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> VerifiableClient<G,
|
||||
impl<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> NonVerifiableServer<G, H> {
|
||||
/// Serialization into bytes
|
||||
pub fn serialize(&self) -> GenericArray<u8, G::ScalarLen> {
|
||||
G::scalar_as_bytes(self.sk)
|
||||
G::serialize_scalar(self.sk)
|
||||
}
|
||||
|
||||
/// Deserialization from bytes
|
||||
pub fn deserialize(input: &[u8]) -> Result<Self> {
|
||||
let mut input = input.iter().copied();
|
||||
|
||||
let sk = G::from_scalar_slice(&deserialize(&mut input)?)?;
|
||||
let sk = G::deserialize_scalar(&deserialize(&mut input)?)?;
|
||||
|
||||
Ok(Self {
|
||||
sk,
|
||||
@@ -97,15 +97,15 @@ impl<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> VerifiableServer<G,
|
||||
G::ScalarLen: Add<G::ElemLen>,
|
||||
Sum<G::ScalarLen, G::ElemLen>: ArrayLength<u8>,
|
||||
{
|
||||
G::scalar_as_bytes(self.sk).concat(self.pk.to_arr())
|
||||
G::serialize_scalar(self.sk).concat(G::serialize_elem(self.pk))
|
||||
}
|
||||
|
||||
/// Deserialization from bytes
|
||||
pub fn deserialize(input: &[u8]) -> Result<Self> {
|
||||
let mut input = input.iter().copied();
|
||||
|
||||
let sk = G::from_scalar_slice(&deserialize(&mut input)?)?;
|
||||
let pk = G::from_element_slice(&deserialize(&mut input)?)?;
|
||||
let sk = G::deserialize_scalar(&deserialize(&mut input)?)?;
|
||||
let pk = G::deserialize_elem(&deserialize(&mut input)?)?;
|
||||
|
||||
Ok(Self {
|
||||
sk,
|
||||
@@ -122,15 +122,15 @@ impl<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> Proof<G, H> {
|
||||
G::ScalarLen: Add<G::ScalarLen>,
|
||||
Sum<G::ScalarLen, G::ScalarLen>: ArrayLength<u8>,
|
||||
{
|
||||
G::scalar_as_bytes(self.c_scalar).concat(G::scalar_as_bytes(self.s_scalar))
|
||||
G::serialize_scalar(self.c_scalar).concat(G::serialize_scalar(self.s_scalar))
|
||||
}
|
||||
|
||||
/// Deserialization from bytes
|
||||
pub fn deserialize(input: &[u8]) -> Result<Self> {
|
||||
let mut input = input.iter().copied();
|
||||
|
||||
let c_scalar = G::from_scalar_slice(&deserialize(&mut input)?)?;
|
||||
let s_scalar = G::from_scalar_slice(&deserialize(&mut input)?)?;
|
||||
let c_scalar = G::deserialize_scalar(&deserialize(&mut input)?)?;
|
||||
let s_scalar = G::deserialize_scalar(&deserialize(&mut input)?)?;
|
||||
|
||||
Ok(Proof {
|
||||
c_scalar,
|
||||
@@ -143,14 +143,14 @@ impl<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> Proof<G, H> {
|
||||
impl<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> BlindedElement<G, H> {
|
||||
/// Serialization into bytes
|
||||
pub fn serialize(&self) -> GenericArray<u8, G::ElemLen> {
|
||||
self.value.to_arr()
|
||||
G::serialize_elem(self.value)
|
||||
}
|
||||
|
||||
/// Deserialization from bytes
|
||||
pub fn deserialize(input: &[u8]) -> Result<Self> {
|
||||
let mut input = input.iter().copied();
|
||||
|
||||
let value = G::from_element_slice(&deserialize(&mut input)?)?;
|
||||
let value = G::deserialize_elem(&deserialize(&mut input)?)?;
|
||||
|
||||
Ok(Self {
|
||||
value,
|
||||
@@ -162,14 +162,14 @@ impl<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> BlindedElement<G, H
|
||||
impl<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> EvaluationElement<G, H> {
|
||||
/// Serialization into bytes
|
||||
pub fn serialize(&self) -> GenericArray<u8, G::ElemLen> {
|
||||
self.value.to_arr()
|
||||
G::serialize_elem(self.value)
|
||||
}
|
||||
|
||||
/// Deserialization from bytes
|
||||
pub fn deserialize(input: &[u8]) -> Result<Self> {
|
||||
let mut input = input.iter().copied();
|
||||
|
||||
let value = G::from_element_slice(&deserialize(&mut input)?)?;
|
||||
let value = G::deserialize_elem(&deserialize(&mut input)?)?;
|
||||
|
||||
Ok(Self {
|
||||
value,
|
||||
|
||||
@@ -90,9 +90,10 @@ fn test_vectors() -> Result<()> {
|
||||
|
||||
#[cfg(feature = "ristretto255")]
|
||||
{
|
||||
use curve25519_dalek::ristretto::RistrettoPoint;
|
||||
use sha2::Sha512;
|
||||
|
||||
use crate::Ristretto255;
|
||||
|
||||
let ristretto_base_tvs = json_to_test_vectors!(
|
||||
rfc,
|
||||
String::from("ristretto255, SHA-512"),
|
||||
@@ -105,20 +106,20 @@ fn test_vectors() -> Result<()> {
|
||||
String::from("Verifiable")
|
||||
);
|
||||
|
||||
test_base_seed_to_key::<RistrettoPoint, Sha512>(&ristretto_base_tvs)?;
|
||||
test_base_blind::<RistrettoPoint, Sha512>(&ristretto_base_tvs)?;
|
||||
test_base_evaluate::<RistrettoPoint, Sha512>(&ristretto_base_tvs)?;
|
||||
test_base_finalize::<RistrettoPoint, Sha512>(&ristretto_base_tvs)?;
|
||||
test_base_seed_to_key::<Ristretto255, Sha512>(&ristretto_base_tvs)?;
|
||||
test_base_blind::<Ristretto255, Sha512>(&ristretto_base_tvs)?;
|
||||
test_base_evaluate::<Ristretto255, Sha512>(&ristretto_base_tvs)?;
|
||||
test_base_finalize::<Ristretto255, Sha512>(&ristretto_base_tvs)?;
|
||||
|
||||
test_verifiable_seed_to_key::<RistrettoPoint, Sha512>(&ristretto_verifiable_tvs)?;
|
||||
test_verifiable_blind::<RistrettoPoint, Sha512>(&ristretto_verifiable_tvs)?;
|
||||
test_verifiable_evaluate::<RistrettoPoint, Sha512>(&ristretto_verifiable_tvs)?;
|
||||
test_verifiable_finalize::<RistrettoPoint, Sha512>(&ristretto_verifiable_tvs)?;
|
||||
test_verifiable_seed_to_key::<Ristretto255, Sha512>(&ristretto_verifiable_tvs)?;
|
||||
test_verifiable_blind::<Ristretto255, Sha512>(&ristretto_verifiable_tvs)?;
|
||||
test_verifiable_evaluate::<Ristretto255, Sha512>(&ristretto_verifiable_tvs)?;
|
||||
test_verifiable_finalize::<Ristretto255, Sha512>(&ristretto_verifiable_tvs)?;
|
||||
}
|
||||
|
||||
#[cfg(feature = "p256")]
|
||||
{
|
||||
use p256_::ProjectivePoint;
|
||||
use p256_::NistP256;
|
||||
use sha2::Sha256;
|
||||
|
||||
let p256_base_tvs =
|
||||
@@ -130,15 +131,15 @@ fn test_vectors() -> Result<()> {
|
||||
String::from("Verifiable")
|
||||
);
|
||||
|
||||
test_base_seed_to_key::<ProjectivePoint, Sha256>(&p256_base_tvs)?;
|
||||
test_base_blind::<ProjectivePoint, Sha256>(&p256_base_tvs)?;
|
||||
test_base_evaluate::<ProjectivePoint, Sha256>(&p256_base_tvs)?;
|
||||
test_base_finalize::<ProjectivePoint, Sha256>(&p256_base_tvs)?;
|
||||
test_base_seed_to_key::<NistP256, Sha256>(&p256_base_tvs)?;
|
||||
test_base_blind::<NistP256, Sha256>(&p256_base_tvs)?;
|
||||
test_base_evaluate::<NistP256, Sha256>(&p256_base_tvs)?;
|
||||
test_base_finalize::<NistP256, Sha256>(&p256_base_tvs)?;
|
||||
|
||||
test_verifiable_seed_to_key::<ProjectivePoint, Sha256>(&p256_verifiable_tvs)?;
|
||||
test_verifiable_blind::<ProjectivePoint, Sha256>(&p256_verifiable_tvs)?;
|
||||
test_verifiable_evaluate::<ProjectivePoint, Sha256>(&p256_verifiable_tvs)?;
|
||||
test_verifiable_finalize::<ProjectivePoint, Sha256>(&p256_verifiable_tvs)?;
|
||||
test_verifiable_seed_to_key::<NistP256, Sha256>(&p256_verifiable_tvs)?;
|
||||
test_verifiable_blind::<NistP256, Sha256>(&p256_verifiable_tvs)?;
|
||||
test_verifiable_evaluate::<NistP256, Sha256>(&p256_verifiable_tvs)?;
|
||||
test_verifiable_finalize::<NistP256, Sha256>(&p256_verifiable_tvs)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
@@ -152,7 +153,7 @@ fn test_base_seed_to_key<G: Group, H: BlockSizeUser + Digest + FixedOutputReset>
|
||||
|
||||
assert_eq!(
|
||||
¶meters.sksm,
|
||||
&G::scalar_as_bytes(server.get_private_key()).to_vec()
|
||||
&G::serialize_scalar(server.get_private_key()).to_vec()
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
@@ -166,9 +167,12 @@ fn test_verifiable_seed_to_key<G: Group, H: BlockSizeUser + Digest + FixedOutput
|
||||
|
||||
assert_eq!(
|
||||
¶meters.sksm,
|
||||
&G::scalar_as_bytes(server.get_private_key()).to_vec()
|
||||
&G::serialize_scalar(server.get_private_key()).to_vec()
|
||||
);
|
||||
assert_eq!(
|
||||
¶meters.pksm,
|
||||
G::serialize_elem(server.get_public_key()).as_slice()
|
||||
);
|
||||
assert_eq!(¶meters.pksm, &server.get_public_key().to_arr().to_vec());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -180,7 +184,7 @@ fn test_base_blind<G: Group, H: BlockSizeUser + Digest + FixedOutputReset>(
|
||||
for parameters in tvs {
|
||||
for i in 0..parameters.input.len() {
|
||||
let blind =
|
||||
G::from_scalar_slice(&GenericArray::clone_from_slice(¶meters.blind[i]))?;
|
||||
G::deserialize_scalar(&GenericArray::clone_from_slice(¶meters.blind[i]))?;
|
||||
let client_result = NonVerifiableClient::<G, H>::deterministic_blind_unchecked(
|
||||
¶meters.input[i],
|
||||
blind,
|
||||
@@ -188,7 +192,7 @@ fn test_base_blind<G: Group, H: BlockSizeUser + Digest + FixedOutputReset>(
|
||||
|
||||
assert_eq!(
|
||||
¶meters.blind[i],
|
||||
&G::scalar_as_bytes(client_result.state.blind).to_vec()
|
||||
&G::serialize_scalar(client_result.state.blind).to_vec()
|
||||
);
|
||||
assert_eq!(
|
||||
parameters.blinded_element[i].as_slice(),
|
||||
@@ -206,7 +210,7 @@ fn test_verifiable_blind<G: Group, H: BlockSizeUser + Digest + FixedOutputReset>
|
||||
for parameters in tvs {
|
||||
for i in 0..parameters.input.len() {
|
||||
let blind =
|
||||
G::from_scalar_slice(&GenericArray::clone_from_slice(¶meters.blind[i]))?;
|
||||
G::deserialize_scalar(&GenericArray::clone_from_slice(¶meters.blind[i]))?;
|
||||
let client_blind_result = VerifiableClient::<G, H>::deterministic_blind_unchecked(
|
||||
¶meters.input[i],
|
||||
blind,
|
||||
@@ -214,7 +218,7 @@ fn test_verifiable_blind<G: Group, H: BlockSizeUser + Digest + FixedOutputReset>
|
||||
|
||||
assert_eq!(
|
||||
¶meters.blind[i],
|
||||
&G::scalar_as_bytes(client_blind_result.state.get_blind()).to_vec()
|
||||
&G::serialize_scalar(client_blind_result.state.get_blind()).to_vec()
|
||||
);
|
||||
assert_eq!(
|
||||
parameters.blinded_element[i].as_slice(),
|
||||
@@ -295,7 +299,7 @@ fn test_base_finalize<G: Group, H: BlockSizeUser + Digest + FixedOutputReset>(
|
||||
) -> Result<()> {
|
||||
for parameters in tvs {
|
||||
for i in 0..parameters.input.len() {
|
||||
let client = NonVerifiableClient::<G, H>::from_blind(G::from_scalar_slice(
|
||||
let client = NonVerifiableClient::<G, H>::from_blind(G::deserialize_scalar(
|
||||
&GenericArray::clone_from_slice(¶meters.blind[i]),
|
||||
)?);
|
||||
|
||||
@@ -318,8 +322,8 @@ fn test_verifiable_finalize<G: Group, H: BlockSizeUser + Digest + FixedOutputRes
|
||||
let mut clients = vec![];
|
||||
for i in 0..parameters.input.len() {
|
||||
let client = VerifiableClient::<G, H>::from_blind_and_element(
|
||||
G::from_scalar_slice(&GenericArray::clone_from_slice(¶meters.blind[i]))?,
|
||||
G::from_element_slice(&GenericArray::clone_from_slice(
|
||||
G::deserialize_scalar(&GenericArray::clone_from_slice(¶meters.blind[i]))?,
|
||||
G::deserialize_elem(&GenericArray::clone_from_slice(
|
||||
¶meters.blinded_element[i],
|
||||
))?,
|
||||
);
|
||||
@@ -337,7 +341,7 @@ fn test_verifiable_finalize<G: Group, H: BlockSizeUser + Digest + FixedOutputRes
|
||||
&clients,
|
||||
&messages,
|
||||
&Proof::deserialize(¶meters.proof)?,
|
||||
G::from_element_slice(GenericArray::from_slice(¶meters.pksm))?,
|
||||
G::deserialize_elem(GenericArray::from_slice(¶meters.pksm))?,
|
||||
Some(¶meters.info),
|
||||
)?;
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
//! The VOPRF test vectors taken from:
|
||||
//! https://github.com/cfrg/draft-irtf-cfrg-voprf/blob/master/draft-irtf-cfrg-voprf.md
|
||||
|
||||
pub(crate) static VECTORS: &str = r#"
|
||||
pub(crate) const VECTORS: &str = r#"
|
||||
## OPRF(ristretto255, SHA-512)
|
||||
|
||||
### Base Mode
|
||||
|
||||
+12
-117
@@ -7,149 +7,44 @@
|
||||
|
||||
//! Helper functions
|
||||
|
||||
use core::array::IntoIter;
|
||||
use core::convert::TryFrom;
|
||||
|
||||
use generic_array::typenum::U0;
|
||||
use generic_array::typenum::{IsLess, U2, U256};
|
||||
use generic_array::{ArrayLength, GenericArray};
|
||||
|
||||
use crate::{Error, Result};
|
||||
|
||||
// Corresponds to the I2OSP() function from RFC8017
|
||||
pub(crate) fn i2osp<L: ArrayLength<u8>>(input: usize) -> Result<GenericArray<u8, L>> {
|
||||
const SIZEOF_USIZE: usize = core::mem::size_of::<usize>();
|
||||
|
||||
// Make sure input fits in output.
|
||||
if (SIZEOF_USIZE as u32 - input.leading_zeros() / 8) > L::U32 {
|
||||
return Err(Error::SerializationError);
|
||||
}
|
||||
|
||||
let mut output = GenericArray::default();
|
||||
output[L::USIZE.saturating_sub(SIZEOF_USIZE)..]
|
||||
.copy_from_slice(&input.to_be_bytes()[SIZEOF_USIZE.saturating_sub(L::USIZE)..]);
|
||||
Ok(output)
|
||||
pub(crate) fn i2osp_2(input: usize) -> Result<GenericArray<u8, U2>> {
|
||||
u16::try_from(input)
|
||||
.map(|input| input.to_be_bytes().into())
|
||||
.map_err(|_| Error::SerializationError)
|
||||
}
|
||||
|
||||
/// Computes `I2OSP(len(input), max_bytes) || input` and helps hold output
|
||||
/// without allocation.
|
||||
pub(crate) struct Serialize<'a, L1: ArrayLength<u8>, L2: ArrayLength<u8> = U0> {
|
||||
octet: GenericArray<u8, L1>,
|
||||
input: Input<'a, L2>,
|
||||
}
|
||||
|
||||
enum Input<'a, L: ArrayLength<u8>> {
|
||||
Owned(GenericArray<u8, L>),
|
||||
Borrowed(&'a [u8]),
|
||||
}
|
||||
|
||||
impl<'a, L1: ArrayLength<u8>, L2: ArrayLength<u8>> IntoIterator for &'a Serialize<'a, L1, L2> {
|
||||
type Item = &'a [u8];
|
||||
|
||||
type IntoIter = IntoIter<&'a [u8], 2>;
|
||||
|
||||
fn into_iter(self) -> Self::IntoIter {
|
||||
// MSRV: array `into_iter` isn't available in 1.51
|
||||
#[allow(deprecated)]
|
||||
IntoIter::new([
|
||||
&self.octet,
|
||||
match self.input {
|
||||
Input::Owned(ref bytes) => bytes,
|
||||
Input::Borrowed(bytes) => bytes,
|
||||
},
|
||||
])
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, L1: ArrayLength<u8>, L2: ArrayLength<u8>> Serialize<'a, L1, L2> {
|
||||
// Variation of `serialize` that takes a borrowed `input.
|
||||
pub(crate) fn from(input: &[u8]) -> Result<Serialize<L1>> {
|
||||
Ok(Serialize {
|
||||
octet: i2osp::<L1>(input.len())?,
|
||||
input: Input::Borrowed(input),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn from_owned(input: GenericArray<u8, L2>) -> Result<Serialize<'static, L1, L2>> {
|
||||
Ok(Serialize {
|
||||
octet: i2osp::<L1>(input.len())?,
|
||||
input: Input::Owned(input),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! chain_name {
|
||||
($var:ident, $mod:ident) => {
|
||||
$mod
|
||||
};
|
||||
($var:ident) => {
|
||||
$var
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! chain_skip {
|
||||
($var:ident, $feed:expr) => {
|
||||
$feed
|
||||
};
|
||||
($var:ident) => {
|
||||
&$var
|
||||
};
|
||||
}
|
||||
|
||||
/// The purpose of this macro is to replace
|
||||
/// [`concat`](alloc::slice::Concat::concat)ing slices into an [`Iterator`] to
|
||||
/// avoid allocation
|
||||
macro_rules! chain {
|
||||
(
|
||||
$var:ident,
|
||||
$item1:expr $(=> |$mod1:ident| $feed1:expr)?,
|
||||
$($item2:expr $(=> |$mod2:ident| $feed2:expr)?),+$(,)?
|
||||
) => {
|
||||
let chain_name!(__temp$(, $mod1)?) = $item1;
|
||||
let $var = (chain_skip!(__temp$(, $feed1)?)).into_iter();
|
||||
$(
|
||||
let chain_name!(__temp$(, $mod2)?) = $item2;
|
||||
let $var = $var.chain(chain_skip!(__temp$(, $feed2)?));
|
||||
)+
|
||||
};
|
||||
pub(crate) fn i2osp_2_array<L: ArrayLength<u8> + IsLess<U256>>(
|
||||
_: GenericArray<u8, L>,
|
||||
) -> GenericArray<u8, U2> {
|
||||
L::U16.to_be_bytes().into()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod unit_tests {
|
||||
use generic_array::typenum::{U1, U2};
|
||||
use proptest::collection::vec;
|
||||
use proptest::prelude::*;
|
||||
|
||||
use super::*;
|
||||
use crate::{
|
||||
BlindedElement, EvaluationElement, NonVerifiableClient, NonVerifiableServer, Proof,
|
||||
VerifiableClient, VerifiableServer,
|
||||
};
|
||||
|
||||
// Test the error condition for I2OSP
|
||||
#[test]
|
||||
fn test_i2osp_err_check() {
|
||||
assert!(i2osp::<U1>(0).is_ok());
|
||||
|
||||
assert!(i2osp::<U1>(255).is_ok());
|
||||
assert!(i2osp::<U1>(256).is_err());
|
||||
assert!(i2osp::<U1>(257).is_err());
|
||||
|
||||
assert!(i2osp::<U2>(256 * 256 - 1).is_ok());
|
||||
assert!(i2osp::<U2>(256 * 256).is_err());
|
||||
assert!(i2osp::<U2>(256 * 256 + 1).is_err());
|
||||
}
|
||||
|
||||
macro_rules! test_deserialize {
|
||||
($item:ident, $bytes:ident) => {
|
||||
#[cfg(feature = "ristretto255")]
|
||||
{
|
||||
let _ =
|
||||
$item::<curve25519_dalek::ristretto::RistrettoPoint, sha2::Sha512>::deserialize(
|
||||
&$bytes[..],
|
||||
);
|
||||
let _ = $item::<crate::Ristretto255, sha2::Sha512>::deserialize(&$bytes[..]);
|
||||
}
|
||||
#[cfg(feature = "p256")]
|
||||
{
|
||||
let _ = $item::<p256_::ProjectivePoint, sha2::Sha256>::deserialize(&$bytes[..]);
|
||||
let _ = $item::<p256_::NistP256, sha2::Sha256>::deserialize(&$bytes[..]);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
+290
-201
@@ -9,7 +9,7 @@
|
||||
|
||||
#[cfg(feature = "alloc")]
|
||||
use alloc::vec::Vec;
|
||||
use core::convert::TryInto;
|
||||
use core::convert::{TryFrom, TryInto};
|
||||
use core::iter::{self, Map, Repeat, Zip};
|
||||
use core::marker::PhantomData;
|
||||
|
||||
@@ -17,12 +17,12 @@ use derive_where::DeriveWhere;
|
||||
use digest::core_api::BlockSizeUser;
|
||||
use digest::{Digest, FixedOutputReset, Output};
|
||||
use generic_array::sequence::Concat;
|
||||
use generic_array::typenum::{U1, U11, U2, U20};
|
||||
use generic_array::typenum::{Unsigned, U11, U20};
|
||||
use generic_array::GenericArray;
|
||||
use rand_core::{CryptoRng, RngCore};
|
||||
use subtle::ConstantTimeEq;
|
||||
|
||||
use crate::util::{i2osp, Serialize};
|
||||
use crate::util::{i2osp_2, i2osp_2_array};
|
||||
use crate::{Error, Group, Result};
|
||||
|
||||
///////////////
|
||||
@@ -30,20 +30,31 @@ use crate::{Error, Group, Result};
|
||||
// ========= //
|
||||
///////////////
|
||||
|
||||
static STR_HASH_TO_SCALAR: [u8; 13] = *b"HashToScalar-";
|
||||
static STR_HASH_TO_GROUP: [u8; 12] = *b"HashToGroup-";
|
||||
static STR_FINALIZE: [u8; 9] = *b"Finalize-";
|
||||
static STR_SEED: [u8; 5] = *b"Seed-";
|
||||
static STR_CONTEXT: [u8; 8] = *b"Context-";
|
||||
static STR_COMPOSITE: [u8; 10] = *b"Composite-";
|
||||
static STR_CHALLENGE: [u8; 10] = *b"Challenge-";
|
||||
static STR_VOPRF: [u8; 8] = *b"VOPRF08-";
|
||||
const STR_FINALIZE: [u8; 9] = *b"Finalize-";
|
||||
const STR_SEED: [u8; 5] = *b"Seed-";
|
||||
const STR_CONTEXT: [u8; 8] = *b"Context-";
|
||||
const STR_COMPOSITE: [u8; 10] = *b"Composite-";
|
||||
const STR_CHALLENGE: [u8; 10] = *b"Challenge-";
|
||||
const STR_VOPRF: [u8; 8] = *b"VOPRF08-";
|
||||
|
||||
/// Determines the mode of operation (either base mode or verifiable mode)
|
||||
/// Determines the mode of operation (either base mode or verifiable mode). This
|
||||
/// is only used for custom implementations for [`Group`].
|
||||
#[derive(Clone, Copy)]
|
||||
enum Mode {
|
||||
Base = 0,
|
||||
Verifiable = 1,
|
||||
pub enum Mode {
|
||||
/// Non-verifiable mode.
|
||||
Base,
|
||||
/// Verifiable mode.
|
||||
Verifiable,
|
||||
}
|
||||
|
||||
impl Mode {
|
||||
/// Mode as it is represented in a context string.
|
||||
pub fn to_u8(self) -> u8 {
|
||||
match self {
|
||||
Mode::Base => 0,
|
||||
Mode::Verifiable => 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////
|
||||
@@ -74,18 +85,18 @@ pub struct NonVerifiableClient<G: Group, H: BlockSizeUser + Digest + FixedOutput
|
||||
/// that the OPRF outputs can be checked against a server public key.
|
||||
#[derive(DeriveWhere)]
|
||||
#[derive_where(Clone, Zeroize(drop))]
|
||||
#[derive_where(Debug, Eq, Hash, Ord, PartialEq, PartialOrd; G, G::Scalar)]
|
||||
#[derive_where(Debug, Eq, Hash, Ord, PartialEq, PartialOrd; G::Elem, G::Scalar)]
|
||||
#[cfg_attr(
|
||||
feature = "serde",
|
||||
derive(serde::Deserialize, serde::Serialize),
|
||||
serde(bound(
|
||||
deserialize = "G::Scalar: serde::Deserialize<'de>, G: serde::Deserialize<'de>",
|
||||
serialize = "G::Scalar: serde::Serialize, G: serde::Serialize"
|
||||
deserialize = "G::Scalar: serde::Deserialize<'de>, G::Elem: serde::Deserialize<'de>",
|
||||
serialize = "G::Scalar: serde::Serialize, G::Elem: serde::Serialize"
|
||||
))
|
||||
)]
|
||||
pub struct VerifiableClient<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> {
|
||||
pub(crate) blind: G::Scalar,
|
||||
pub(crate) blinded_element: G,
|
||||
pub(crate) blinded_element: G::Elem,
|
||||
#[derive_where(skip(Zeroize))]
|
||||
pub(crate) hash: PhantomData<H>,
|
||||
}
|
||||
@@ -113,18 +124,18 @@ pub struct NonVerifiableServer<G: Group, H: BlockSizeUser + Digest + FixedOutput
|
||||
/// that the OPRF outputs can be checked against a server public key.
|
||||
#[derive(DeriveWhere)]
|
||||
#[derive_where(Clone, Zeroize(drop))]
|
||||
#[derive_where(Debug, Eq, Hash, Ord, PartialEq, PartialOrd; G, G::Scalar)]
|
||||
#[derive_where(Debug, Eq, Hash, Ord, PartialEq, PartialOrd; G::Elem, G::Scalar)]
|
||||
#[cfg_attr(
|
||||
feature = "serde",
|
||||
derive(serde::Deserialize, serde::Serialize),
|
||||
serde(bound(
|
||||
deserialize = "G::Scalar: serde::Deserialize<'de>, G: serde::Deserialize<'de>",
|
||||
serialize = "G::Scalar: serde::Serialize, G: serde::Serialize"
|
||||
deserialize = "G::Scalar: serde::Deserialize<'de>, G::Elem: serde::Deserialize<'de>",
|
||||
serialize = "G::Scalar: serde::Serialize, G::Elem: serde::Serialize"
|
||||
))
|
||||
)]
|
||||
pub struct VerifiableServer<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> {
|
||||
pub(crate) sk: G::Scalar,
|
||||
pub(crate) pk: G,
|
||||
pub(crate) pk: G::Elem,
|
||||
#[derive_where(skip(Zeroize))]
|
||||
pub(crate) hash: PhantomData<H>,
|
||||
}
|
||||
@@ -153,17 +164,17 @@ pub struct Proof<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> {
|
||||
/// server (either verifiable or not).
|
||||
#[derive(DeriveWhere)]
|
||||
#[derive_where(Clone, Zeroize(drop))]
|
||||
#[derive_where(Debug, Eq, Hash, Ord, PartialEq, PartialOrd; G)]
|
||||
#[derive_where(Debug, Eq, Hash, Ord, PartialEq, PartialOrd; G::Elem)]
|
||||
#[cfg_attr(
|
||||
feature = "serde",
|
||||
derive(serde::Deserialize, serde::Serialize),
|
||||
serde(bound(
|
||||
deserialize = "G: serde::Deserialize<'de>",
|
||||
serialize = "G: serde::Serialize"
|
||||
deserialize = "G::Elem: serde::Deserialize<'de>",
|
||||
serialize = "G::Elem: serde::Serialize"
|
||||
))
|
||||
)]
|
||||
pub struct BlindedElement<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> {
|
||||
pub(crate) value: G,
|
||||
pub(crate) value: G::Elem,
|
||||
#[derive_where(skip(Zeroize))]
|
||||
pub(crate) hash: PhantomData<H>,
|
||||
}
|
||||
@@ -172,17 +183,17 @@ pub struct BlindedElement<G: Group, H: BlockSizeUser + Digest + FixedOutputReset
|
||||
/// verifiable or not) to a server (either verifiable or not).
|
||||
#[derive(DeriveWhere)]
|
||||
#[derive_where(Clone, Zeroize(drop))]
|
||||
#[derive_where(Debug, Eq, Hash, Ord, PartialEq, PartialOrd; G)]
|
||||
#[derive_where(Debug, Eq, Hash, Ord, PartialEq, PartialOrd; G::Elem)]
|
||||
#[cfg_attr(
|
||||
feature = "serde",
|
||||
derive(serde::Deserialize, serde::Serialize),
|
||||
serde(bound(
|
||||
deserialize = "G: serde::Deserialize<'de>",
|
||||
serialize = "G: serde::Serialize"
|
||||
deserialize = "G::Elem: serde::Deserialize<'de>",
|
||||
serialize = "G::Elem: serde::Serialize"
|
||||
))
|
||||
)]
|
||||
pub struct EvaluationElement<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> {
|
||||
pub(crate) value: G,
|
||||
pub(crate) value: G::Elem,
|
||||
#[derive_where(skip(Zeroize))]
|
||||
pub(crate) hash: PhantomData<H>,
|
||||
}
|
||||
@@ -246,7 +257,7 @@ impl<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> NonVerifiableClient
|
||||
evaluation_element: &EvaluationElement<G, H>,
|
||||
metadata: Option<&[u8]>,
|
||||
) -> Result<Output<H>> {
|
||||
let unblinded_element = evaluation_element.value * &G::scalar_invert(&self.blind);
|
||||
let unblinded_element = evaluation_element.value * &G::invert_scalar(self.blind);
|
||||
let mut outputs = finalize_after_unblind::<G, H, _, _>(
|
||||
Some((input, unblinded_element)).into_iter(),
|
||||
metadata.unwrap_or_default(),
|
||||
@@ -328,7 +339,7 @@ impl<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> VerifiableClient<G,
|
||||
input: &[u8],
|
||||
evaluation_element: &EvaluationElement<G, H>,
|
||||
proof: &Proof<G, H>,
|
||||
pk: G,
|
||||
pk: G::Elem,
|
||||
metadata: Option<&[u8]>,
|
||||
) -> Result<Output<H>> {
|
||||
// `core::array::from_ref` needs a MSRV of 1.53
|
||||
@@ -350,7 +361,7 @@ impl<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> VerifiableClient<G,
|
||||
clients: &'a IC,
|
||||
messages: &'a IM,
|
||||
proof: &Proof<G, H>,
|
||||
pk: G,
|
||||
pk: G::Elem,
|
||||
metadata: Option<&'a [u8]>,
|
||||
) -> Result<VerifiableClientBatchFinalizeResult<'a, G, H, I, II, IC, IM>>
|
||||
where
|
||||
@@ -379,7 +390,7 @@ impl<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> VerifiableClient<G,
|
||||
|
||||
#[cfg(test)]
|
||||
/// Only used for test functions
|
||||
pub fn from_blind_and_element(blind: G::Scalar, blinded_element: G) -> Self {
|
||||
pub fn from_blind_and_element(blind: G::Scalar, blinded_element: G::Elem) -> Self {
|
||||
Self {
|
||||
blind,
|
||||
blinded_element,
|
||||
@@ -405,7 +416,7 @@ impl<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> NonVerifiableServer
|
||||
/// Produces a new instance of a [NonVerifiableServer] using a supplied set
|
||||
/// of bytes to represent the server's private key
|
||||
pub fn new_with_key(private_key_bytes: &[u8]) -> Result<Self> {
|
||||
let sk = G::from_scalar_slice(private_key_bytes)?;
|
||||
let sk = G::deserialize_scalar(private_key_bytes.into())?;
|
||||
Ok(Self {
|
||||
sk,
|
||||
hash: PhantomData,
|
||||
@@ -417,9 +428,7 @@ impl<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> NonVerifiableServer
|
||||
///
|
||||
/// Corresponds to DeriveKeyPair() function from the VOPRF specification.
|
||||
pub fn new_from_seed(seed: &[u8]) -> Result<Self> {
|
||||
let dst =
|
||||
GenericArray::from(STR_HASH_TO_SCALAR).concat(get_context_string::<G>(Mode::Base)?);
|
||||
let sk = G::hash_to_scalar::<H, _, _>(Some(seed), dst)?;
|
||||
let sk = G::hash_to_scalar::<H>(&[seed], Mode::Base)?;
|
||||
Ok(Self {
|
||||
sk,
|
||||
hash: PhantomData,
|
||||
@@ -440,20 +449,27 @@ impl<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> NonVerifiableServer
|
||||
blinded_element: &BlindedElement<G, H>,
|
||||
metadata: Option<&[u8]>,
|
||||
) -> Result<NonVerifiableServerEvaluateResult<G, H>> {
|
||||
chain!(
|
||||
context,
|
||||
STR_CONTEXT => |x| Some(x.as_ref()),
|
||||
get_context_string::<G>(Mode::Base)? => |x| Some(x.as_slice()),
|
||||
Serialize::<U2>::from(metadata.unwrap_or_default())?,
|
||||
);
|
||||
let dst =
|
||||
GenericArray::from(STR_HASH_TO_SCALAR).concat(get_context_string::<G>(Mode::Base)?);
|
||||
let m = G::hash_to_scalar::<H, _, _>(context, dst)?;
|
||||
// https://www.ietf.org/archive/id/draft-irtf-cfrg-voprf-08.html#section-3.3.1.1-1
|
||||
|
||||
let context_string = get_context_string::<G>(Mode::Base);
|
||||
let metadata = metadata.unwrap_or_default();
|
||||
|
||||
// context = "Context-" || contextString || I2OSP(len(info), 2) || info
|
||||
let context = GenericArray::from(STR_CONTEXT)
|
||||
.concat(context_string)
|
||||
.concat(i2osp_2(metadata.len())?);
|
||||
let context = [&context, metadata];
|
||||
|
||||
// m = GG.HashToScalar(context)
|
||||
let m = G::hash_to_scalar::<H>(&context, Mode::Base)?;
|
||||
// t = skS + m
|
||||
let t = self.sk + &m;
|
||||
let evaluation_element = blinded_element.value * &G::scalar_invert(&t);
|
||||
// Z = t^(-1) * R
|
||||
let z = blinded_element.value * &G::invert_scalar(t);
|
||||
|
||||
Ok(NonVerifiableServerEvaluateResult {
|
||||
message: EvaluationElement {
|
||||
value: evaluation_element,
|
||||
value: z,
|
||||
hash: PhantomData,
|
||||
},
|
||||
})
|
||||
@@ -471,8 +487,8 @@ impl<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> VerifiableServer<G,
|
||||
/// Produces a new instance of a [VerifiableServer] using a supplied set of
|
||||
/// bytes to represent the server's private key
|
||||
pub fn new_with_key(key: &[u8]) -> Result<Self> {
|
||||
let sk = G::from_scalar_slice(key)?;
|
||||
let pk = G::base_point() * &sk;
|
||||
let sk = G::deserialize_scalar(key.into())?;
|
||||
let pk = G::base_elem() * &sk;
|
||||
Ok(Self {
|
||||
sk,
|
||||
pk,
|
||||
@@ -485,10 +501,8 @@ impl<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> VerifiableServer<G,
|
||||
///
|
||||
/// Corresponds to DeriveKeyPair() function from the VOPRF specification.
|
||||
pub fn new_from_seed(seed: &[u8]) -> Result<Self> {
|
||||
let dst = GenericArray::from(STR_HASH_TO_SCALAR)
|
||||
.concat(get_context_string::<G>(Mode::Verifiable)?);
|
||||
let sk = G::hash_to_scalar::<H, _, _>(Some(seed), dst)?;
|
||||
let pk = G::base_point() * &sk;
|
||||
let sk = G::hash_to_scalar::<H>(&[seed], Mode::Verifiable)?;
|
||||
let pk = G::base_elem() * &sk;
|
||||
Ok(Self {
|
||||
sk,
|
||||
pk,
|
||||
@@ -579,19 +593,23 @@ impl<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> VerifiableServer<G,
|
||||
blinded_elements: I,
|
||||
metadata: Option<&[u8]>,
|
||||
) -> Result<VerifiableServerBatchEvaluatePrepareResult<'a, G, H, I>> {
|
||||
chain!(context,
|
||||
STR_CONTEXT => |x| Some(x.as_ref()),
|
||||
get_context_string::<G>(Mode::Verifiable)? => |x| Some(x.as_slice()),
|
||||
Serialize::<U2>::from(metadata.unwrap_or_default())?,
|
||||
);
|
||||
let dst = GenericArray::from(STR_HASH_TO_SCALAR)
|
||||
.concat(get_context_string::<G>(Mode::Verifiable)?);
|
||||
let m = G::hash_to_scalar::<H, _, _>(context, dst)?;
|
||||
// https://www.ietf.org/archive/id/draft-irtf-cfrg-voprf-08.html#section-3.3.2.1-1
|
||||
|
||||
let context_string = get_context_string::<G>(Mode::Verifiable);
|
||||
let metadata = metadata.unwrap_or_default();
|
||||
|
||||
// context = "Context-" || contextString || I2OSP(len(info), 2) || info
|
||||
let context = GenericArray::from(STR_CONTEXT)
|
||||
.concat(context_string)
|
||||
.concat(i2osp_2(metadata.len())?);
|
||||
let context = [&context, metadata];
|
||||
|
||||
let m = G::hash_to_scalar::<H>(&context, Mode::Verifiable)?;
|
||||
let t = self.sk + &m;
|
||||
let evaluation_elements = blinded_elements
|
||||
// To make a return type possible, we have to convert to a `fn` pointer, which isn't
|
||||
// possible if we `move` from context.
|
||||
.zip(iter::repeat(G::scalar_invert(&t)))
|
||||
.zip(iter::repeat(G::invert_scalar(t)))
|
||||
.map(<fn((&BlindedElement<G, H>, _)) -> _>::from(|(x, t)| {
|
||||
PreparedEvaluationElement(EvaluationElement {
|
||||
value: x.value * &t,
|
||||
@@ -623,7 +641,7 @@ impl<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> VerifiableServer<G,
|
||||
&'b IE: IntoIterator<Item = &'b PreparedEvaluationElement<G, H>>,
|
||||
<&'b IE as IntoIterator>::IntoIter: ExactSizeIterator,
|
||||
{
|
||||
let g = G::base_point();
|
||||
let g = G::base_elem();
|
||||
let u = g * t;
|
||||
|
||||
let proof = generate_proof(
|
||||
@@ -647,7 +665,7 @@ impl<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> VerifiableServer<G,
|
||||
}
|
||||
|
||||
/// Retrieves the server's public key
|
||||
pub fn get_public_key(&self) -> G {
|
||||
pub fn get_public_key(&self) -> G::Elem {
|
||||
self.pk
|
||||
}
|
||||
}
|
||||
@@ -783,7 +801,7 @@ impl<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> BlindedElement<G, H
|
||||
///
|
||||
/// This should be used with caution, since it does not perform any checks
|
||||
/// on the validity of the value itself!
|
||||
pub fn from_value_unchecked(value: G) -> Self {
|
||||
pub fn from_value_unchecked(value: G::Elem) -> Self {
|
||||
Self {
|
||||
value,
|
||||
hash: PhantomData,
|
||||
@@ -792,7 +810,7 @@ impl<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> BlindedElement<G, H
|
||||
|
||||
#[cfg(feature = "danger")]
|
||||
/// Exposes the internal value
|
||||
pub fn value(&self) -> G {
|
||||
pub fn value(&self) -> G::Elem {
|
||||
self.value
|
||||
}
|
||||
}
|
||||
@@ -813,7 +831,7 @@ impl<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> EvaluationElement<G
|
||||
///
|
||||
/// This should be used with caution, since it does not perform any checks
|
||||
/// on the validity of the value itself!
|
||||
pub fn from_value_unchecked(value: G) -> Self {
|
||||
pub fn from_value_unchecked(value: G::Elem) -> Self {
|
||||
Self {
|
||||
value,
|
||||
hash: PhantomData,
|
||||
@@ -822,7 +840,7 @@ impl<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> EvaluationElement<G
|
||||
|
||||
#[cfg(feature = "danger")]
|
||||
/// Exposes the internal value
|
||||
pub fn value(&self) -> G {
|
||||
pub fn value(&self) -> G::Elem {
|
||||
self.value
|
||||
}
|
||||
}
|
||||
@@ -832,9 +850,9 @@ fn blind<G: Group, H: BlockSizeUser + Digest + FixedOutputReset, R: RngCore + Cr
|
||||
input: &[u8],
|
||||
blinding_factor_rng: &mut R,
|
||||
mode: Mode,
|
||||
) -> Result<(G::Scalar, G)> {
|
||||
) -> Result<(G::Scalar, G::Elem)> {
|
||||
// Choose a random scalar that must be non-zero
|
||||
let blind = G::random_nonzero_scalar(blinding_factor_rng);
|
||||
let blind = G::random_scalar(blinding_factor_rng);
|
||||
let blinded_element = deterministic_blind_unchecked::<G, H>(input, &blind, mode)?;
|
||||
Ok((blind, blinded_element))
|
||||
}
|
||||
@@ -846,9 +864,8 @@ fn deterministic_blind_unchecked<G: Group, H: BlockSizeUser + Digest + FixedOutp
|
||||
input: &[u8],
|
||||
blind: &G::Scalar,
|
||||
mode: Mode,
|
||||
) -> Result<G> {
|
||||
let dst = GenericArray::from(STR_HASH_TO_GROUP).concat(get_context_string::<G>(mode)?);
|
||||
let hashed_point = G::hash_to_curve::<H, _>(input, dst)?;
|
||||
) -> Result<G::Elem> {
|
||||
let hashed_point = G::hash_to_curve::<H>(&[input], mode)?;
|
||||
Ok(hashed_point * blind)
|
||||
}
|
||||
|
||||
@@ -860,7 +877,7 @@ type VerifiableUnblindResult<'a, G, H, IC, IM> = Map<
|
||||
>,
|
||||
<&'a IM as IntoIterator>::IntoIter,
|
||||
>,
|
||||
fn((<G as Group>::Scalar, &EvaluationElement<G, H>)) -> G,
|
||||
fn((<G as Group>::Scalar, &EvaluationElement<G, H>)) -> <G as Group>::Elem,
|
||||
>;
|
||||
|
||||
fn verifiable_unblind<
|
||||
@@ -872,7 +889,7 @@ fn verifiable_unblind<
|
||||
>(
|
||||
clients: &'a IC,
|
||||
messages: &'a IM,
|
||||
pk: G,
|
||||
pk: G::Elem,
|
||||
proof: &Proof<G, H>,
|
||||
info: &[u8],
|
||||
) -> Result<VerifiableUnblindResult<'a, G, H, IC, IM>>
|
||||
@@ -882,17 +899,19 @@ where
|
||||
&'a IM: 'a + IntoIterator<Item = &'a EvaluationElement<G, H>>,
|
||||
<&'a IM as IntoIterator>::IntoIter: ExactSizeIterator,
|
||||
{
|
||||
chain!(context,
|
||||
STR_CONTEXT => |x| Some(x.as_ref()),
|
||||
get_context_string::<G>(Mode::Verifiable)? => |x| Some(x.as_slice()),
|
||||
Serialize::<U2>::from(info)?,
|
||||
);
|
||||
// https://www.ietf.org/archive/id/draft-irtf-cfrg-voprf-08.html#section-3.3.4.2-2
|
||||
|
||||
let dst =
|
||||
GenericArray::from(STR_HASH_TO_SCALAR).concat(get_context_string::<G>(Mode::Verifiable)?);
|
||||
let m = G::hash_to_scalar::<H, _, _>(context, dst)?;
|
||||
let context_string = get_context_string::<G>(Mode::Verifiable);
|
||||
|
||||
let g = G::base_point();
|
||||
// context = "Context-" || contextString || I2OSP(len(info), 2) || info
|
||||
let context = GenericArray::from(STR_CONTEXT)
|
||||
.concat(context_string)
|
||||
.concat(i2osp_2(info.len())?);
|
||||
let context = [&context, info];
|
||||
|
||||
let m = G::hash_to_scalar::<H>(&context, Mode::Verifiable)?;
|
||||
|
||||
let g = G::base_elem();
|
||||
let t = g * &m;
|
||||
let u = t + &pk;
|
||||
|
||||
@@ -910,7 +929,7 @@ where
|
||||
|
||||
Ok(blinds
|
||||
.zip(messages.into_iter())
|
||||
.map(|(blind, x)| x.value * &G::scalar_invert(&blind)))
|
||||
.map(|(blind, x)| x.value * &G::invert_scalar(blind)))
|
||||
}
|
||||
|
||||
#[allow(clippy::many_single_char_names)]
|
||||
@@ -921,33 +940,58 @@ fn generate_proof<
|
||||
>(
|
||||
rng: &mut R,
|
||||
k: G::Scalar,
|
||||
a: G,
|
||||
b: G,
|
||||
a: G::Elem,
|
||||
b: G::Elem,
|
||||
cs: impl Iterator<Item = EvaluationElement<G, H>> + ExactSizeIterator,
|
||||
ds: impl Iterator<Item = BlindedElement<G, H>> + ExactSizeIterator,
|
||||
) -> Result<Proof<G, H>> {
|
||||
// https://www.ietf.org/archive/id/draft-irtf-cfrg-voprf-08.html#section-3.3.2.2-1
|
||||
|
||||
let (m, z) = compute_composites(Some(k), b, cs, ds)?;
|
||||
|
||||
let r = G::random_nonzero_scalar(rng);
|
||||
let r = G::random_scalar(rng);
|
||||
let t2 = a * &r;
|
||||
let t3 = m * &r;
|
||||
|
||||
// Bm = GG.SerializeElement(B)
|
||||
let bm = G::serialize_elem(b);
|
||||
// a0 = GG.SerializeElement(M)
|
||||
let a0 = G::serialize_elem(m);
|
||||
// a1 = GG.SerializeElement(Z)
|
||||
let a1 = G::serialize_elem(z);
|
||||
// a2 = GG.SerializeElement(t2)
|
||||
let a2 = G::serialize_elem(t2);
|
||||
// a3 = GG.SerializeElement(t3)
|
||||
let a3 = G::serialize_elem(t3);
|
||||
|
||||
let elem_len = G::ElemLen::U16.to_be_bytes();
|
||||
|
||||
// challengeDST = "Challenge-" || contextString
|
||||
let challenge_dst =
|
||||
GenericArray::from(STR_CHALLENGE).concat(get_context_string::<G>(Mode::Verifiable)?);
|
||||
chain!(
|
||||
h2_input,
|
||||
Serialize::<U2, _>::from_owned(b.to_arr())?,
|
||||
Serialize::<U2, _>::from_owned(m.to_arr())?,
|
||||
Serialize::<U2, _>::from_owned(z.to_arr())?,
|
||||
Serialize::<U2, _>::from_owned(t2.to_arr())?,
|
||||
Serialize::<U2, _>::from_owned(t3.to_arr())?,
|
||||
Serialize::<U2, _>::from_owned(challenge_dst)?,
|
||||
);
|
||||
GenericArray::from(STR_CHALLENGE).concat(get_context_string::<G>(Mode::Verifiable));
|
||||
let challenge_dst_len = i2osp_2_array(challenge_dst);
|
||||
// h2Input = I2OSP(len(Bm), 2) || Bm ||
|
||||
// I2OSP(len(a0), 2) || a0 ||
|
||||
// I2OSP(len(a1), 2) || a1 ||
|
||||
// I2OSP(len(a2), 2) || a2 ||
|
||||
// I2OSP(len(a3), 2) || a3 ||
|
||||
// I2OSP(len(challengeDST), 2) || challengeDST
|
||||
let h2_input = [
|
||||
&elem_len,
|
||||
bm.as_slice(),
|
||||
&elem_len,
|
||||
&a0,
|
||||
&elem_len,
|
||||
&a1,
|
||||
&elem_len,
|
||||
&a2,
|
||||
&elem_len,
|
||||
&a3,
|
||||
&challenge_dst_len,
|
||||
&challenge_dst,
|
||||
];
|
||||
|
||||
let hash_to_scalar_dst =
|
||||
GenericArray::from(STR_HASH_TO_SCALAR).concat(get_context_string::<G>(Mode::Verifiable)?);
|
||||
|
||||
let c_scalar = G::hash_to_scalar::<H, _, _>(h2_input, hash_to_scalar_dst)?;
|
||||
let c_scalar = G::hash_to_scalar::<H>(&h2_input, Mode::Verifiable)?;
|
||||
let s_scalar = r - &(c_scalar * &k);
|
||||
|
||||
Ok(Proof {
|
||||
@@ -959,31 +1003,56 @@ fn generate_proof<
|
||||
|
||||
#[allow(clippy::many_single_char_names)]
|
||||
fn verify_proof<G: Group, H: BlockSizeUser + Digest + FixedOutputReset>(
|
||||
a: G,
|
||||
b: G,
|
||||
a: G::Elem,
|
||||
b: G::Elem,
|
||||
cs: impl Iterator<Item = EvaluationElement<G, H>> + ExactSizeIterator,
|
||||
ds: impl Iterator<Item = BlindedElement<G, H>> + ExactSizeIterator,
|
||||
proof: &Proof<G, H>,
|
||||
) -> Result<()> {
|
||||
// https://www.ietf.org/archive/id/draft-irtf-cfrg-voprf-08.html#section-3.3.4.1-2
|
||||
let (m, z) = compute_composites(None, b, cs, ds)?;
|
||||
let t2 = (a * &proof.s_scalar) + &(b * &proof.c_scalar);
|
||||
let t3 = (m * &proof.s_scalar) + &(z * &proof.c_scalar);
|
||||
|
||||
let challenge_dst =
|
||||
GenericArray::from(STR_CHALLENGE).concat(get_context_string::<G>(Mode::Verifiable)?);
|
||||
chain!(
|
||||
h2_input,
|
||||
Serialize::<U2, _>::from_owned(b.to_arr())?,
|
||||
Serialize::<U2, _>::from_owned(m.to_arr())?,
|
||||
Serialize::<U2, _>::from_owned(z.to_arr())?,
|
||||
Serialize::<U2, _>::from_owned(t2.to_arr())?,
|
||||
Serialize::<U2, _>::from_owned(t3.to_arr())?,
|
||||
Serialize::<U2, _>::from_owned(challenge_dst)?,
|
||||
);
|
||||
// Bm = GG.SerializeElement(B)
|
||||
let bm = G::serialize_elem(b);
|
||||
// a0 = GG.SerializeElement(M)
|
||||
let a0 = G::serialize_elem(m);
|
||||
// a1 = GG.SerializeElement(Z)
|
||||
let a1 = G::serialize_elem(z);
|
||||
// a2 = GG.SerializeElement(t2)
|
||||
let a2 = G::serialize_elem(t2);
|
||||
// a3 = GG.SerializeElement(t3)
|
||||
let a3 = G::serialize_elem(t3);
|
||||
|
||||
let hash_to_scalar_dst =
|
||||
GenericArray::from(STR_HASH_TO_SCALAR).concat(get_context_string::<G>(Mode::Verifiable)?);
|
||||
let c = G::hash_to_scalar::<H, _, _>(h2_input, hash_to_scalar_dst)?;
|
||||
let elem_len = G::ElemLen::U16.to_be_bytes();
|
||||
|
||||
// challengeDST = "Challenge-" || contextString
|
||||
let challenge_dst =
|
||||
GenericArray::from(STR_CHALLENGE).concat(get_context_string::<G>(Mode::Verifiable));
|
||||
let challenge_dst_len = i2osp_2_array(challenge_dst);
|
||||
// h2Input = I2OSP(len(Bm), 2) || Bm ||
|
||||
// I2OSP(len(a0), 2) || a0 ||
|
||||
// I2OSP(len(a1), 2) || a1 ||
|
||||
// I2OSP(len(a2), 2) || a2 ||
|
||||
// I2OSP(len(a3), 2) || a3 ||
|
||||
// I2OSP(len(challengeDST), 2) || challengeDST
|
||||
let h2_input = [
|
||||
&elem_len,
|
||||
bm.as_slice(),
|
||||
&elem_len,
|
||||
&a0,
|
||||
&elem_len,
|
||||
&a1,
|
||||
&elem_len,
|
||||
&a2,
|
||||
&elem_len,
|
||||
&a3,
|
||||
&challenge_dst_len,
|
||||
&challenge_dst,
|
||||
];
|
||||
|
||||
let c = G::hash_to_scalar::<H>(&h2_input, Mode::Verifiable)?;
|
||||
|
||||
match c.ct_eq(&proof.c_scalar).into() {
|
||||
true => Ok(()),
|
||||
@@ -993,7 +1062,7 @@ fn verify_proof<G: Group, H: BlockSizeUser + Digest + FixedOutputReset>(
|
||||
|
||||
type FinalizeAfterUnblindResult<'a, G, H, I, IE> = Map<
|
||||
Zip<IE, Repeat<(&'a [u8], GenericArray<u8, U20>)>>,
|
||||
fn(((I, G), (&'a [u8], GenericArray<u8, U20>))) -> Result<Output<H>>,
|
||||
fn(((I, <G as Group>::Elem), (&'a [u8], GenericArray<u8, U20>))) -> Result<Output<H>>,
|
||||
>;
|
||||
|
||||
fn finalize_after_unblind<
|
||||
@@ -1001,70 +1070,97 @@ fn finalize_after_unblind<
|
||||
G: Group,
|
||||
H: BlockSizeUser + Digest + FixedOutputReset,
|
||||
I: AsRef<[u8]>,
|
||||
IE: 'a + Iterator<Item = (I, G)>,
|
||||
IE: 'a + Iterator<Item = (I, G::Elem)>,
|
||||
>(
|
||||
inputs_and_unblinded_elements: IE,
|
||||
info: &'a [u8],
|
||||
mode: Mode,
|
||||
) -> Result<FinalizeAfterUnblindResult<G, H, I, IE>> {
|
||||
let finalize_dst = GenericArray::from(STR_FINALIZE).concat(get_context_string::<G>(mode)?);
|
||||
// https://www.ietf.org/archive/id/draft-irtf-cfrg-voprf-08.html#section-3.3.3.2-2
|
||||
// https://www.ietf.org/archive/id/draft-irtf-cfrg-voprf-08.html#section-3.3.4.3-1
|
||||
|
||||
// finalizeDST = "Finalize-" || contextString
|
||||
let finalize_dst = GenericArray::from(STR_FINALIZE).concat(get_context_string::<G>(mode));
|
||||
|
||||
Ok(inputs_and_unblinded_elements
|
||||
// To make a return type possible, we have to convert to a `fn` pointer,
|
||||
// which isn't possible if we `move` from context.
|
||||
.zip(iter::repeat((info, finalize_dst)))
|
||||
.map(|((input, unblinded_element), (info, finalize_dst))| {
|
||||
chain!(
|
||||
hash_input,
|
||||
Serialize::<U2>::from(input.as_ref())?,
|
||||
Serialize::<U2>::from(info)?,
|
||||
Serialize::<U2, _>::from_owned(unblinded_element.to_arr())?,
|
||||
Serialize::<U2, _>::from_owned(finalize_dst)?,
|
||||
);
|
||||
let finalize_dst_len = i2osp_2_array(finalize_dst);
|
||||
let elem_len = G::ElemLen::U16.to_be_bytes();
|
||||
|
||||
Ok(hash_input
|
||||
.fold(H::new(), |h, bytes| h.chain_update(bytes))
|
||||
// hashInput = I2OSP(len(input), 2) || input ||
|
||||
// I2OSP(len(info), 2) || info ||
|
||||
// I2OSP(len(unblindedElement), 2) || unblindedElement ||
|
||||
// I2OSP(len(finalizeDST), 2) || finalizeDST
|
||||
// return Hash(hashInput)
|
||||
Ok(H::new()
|
||||
.chain_update(i2osp_2(input.as_ref().len())?)
|
||||
.chain_update(input.as_ref())
|
||||
.chain_update(i2osp_2(info.len())?)
|
||||
.chain_update(info)
|
||||
.chain_update(elem_len)
|
||||
.chain_update(G::serialize_elem(unblinded_element))
|
||||
.chain_update(finalize_dst_len)
|
||||
.chain_update(finalize_dst)
|
||||
.finalize())
|
||||
}))
|
||||
}
|
||||
|
||||
fn compute_composites<G: Group, H: BlockSizeUser + Digest + FixedOutputReset>(
|
||||
k_option: Option<G::Scalar>,
|
||||
b: G,
|
||||
b: G::Elem,
|
||||
c_slice: impl Iterator<Item = EvaluationElement<G, H>> + ExactSizeIterator,
|
||||
d_slice: impl Iterator<Item = BlindedElement<G, H>> + ExactSizeIterator,
|
||||
) -> Result<(G, G)> {
|
||||
) -> Result<(G::Elem, G::Elem)> {
|
||||
// https://www.ietf.org/archive/id/draft-irtf-cfrg-voprf-08.html#section-3.3.2.3-2
|
||||
|
||||
let elem_len = G::ElemLen::U16.to_be_bytes();
|
||||
|
||||
if c_slice.len() != d_slice.len() {
|
||||
return Err(Error::MismatchedLengthsForCompositeInputs);
|
||||
}
|
||||
|
||||
let seed_dst = GenericArray::from(STR_SEED).concat(get_context_string::<G>(Mode::Verifiable)?);
|
||||
let len = u16::try_from(c_slice.len()).map_err(|_| Error::SerializationError)?;
|
||||
|
||||
let seed_dst = GenericArray::from(STR_SEED).concat(get_context_string::<G>(Mode::Verifiable));
|
||||
let composite_dst =
|
||||
GenericArray::from(STR_COMPOSITE).concat(get_context_string::<G>(Mode::Verifiable)?);
|
||||
GenericArray::from(STR_COMPOSITE).concat(get_context_string::<G>(Mode::Verifiable));
|
||||
let composite_dst_len = i2osp_2_array(composite_dst);
|
||||
|
||||
chain!(
|
||||
h1_input,
|
||||
Serialize::<U2, _>::from_owned(b.to_arr())?,
|
||||
Serialize::<U2, _>::from_owned(seed_dst)?,
|
||||
);
|
||||
let seed = h1_input
|
||||
.fold(H::new(), |h, bytes| h.chain_update(bytes))
|
||||
let seed = H::new()
|
||||
.chain_update(&elem_len)
|
||||
.chain_update(G::serialize_elem(b))
|
||||
.chain_update(i2osp_2_array(seed_dst))
|
||||
.chain_update(seed_dst)
|
||||
.finalize();
|
||||
let seed_len = i2osp_2(seed.len())?;
|
||||
|
||||
let mut m = G::identity();
|
||||
let mut z = G::identity();
|
||||
let mut m = G::identity_elem();
|
||||
let mut z = G::identity_elem();
|
||||
|
||||
for (i, (c, d)) in c_slice.zip(d_slice).enumerate() {
|
||||
chain!(h2_input,
|
||||
Serialize::<U2, _>::from_owned(seed.clone())?,
|
||||
i2osp::<U2>(i)? => |x| Some(x.as_slice()),
|
||||
Serialize::<U2, _>::from_owned(c.value.to_arr())?,
|
||||
Serialize::<U2, _>::from_owned(d.value.to_arr())?,
|
||||
Serialize::<U2, _>::from_owned(composite_dst)?,
|
||||
);
|
||||
let dst = GenericArray::from(STR_HASH_TO_SCALAR)
|
||||
.concat(get_context_string::<G>(Mode::Verifiable)?);
|
||||
let di = G::hash_to_scalar::<H, _, _>(h2_input, dst)?;
|
||||
for (i, (c, d)) in (0..len).zip(c_slice.zip(d_slice)) {
|
||||
// Ci = GG.SerializeElement(Cs[i])
|
||||
let ci = G::serialize_elem(c.value);
|
||||
// Di = GG.SerializeElement(Ds[i])
|
||||
let di = G::serialize_elem(d.value);
|
||||
// h2Input = I2OSP(len(seed), 2) || seed || I2OSP(i, 2) ||
|
||||
// I2OSP(len(Ci), 2) || Ci ||
|
||||
// I2OSP(len(Di), 2) || Di ||
|
||||
// I2OSP(len(compositeDST), 2) || compositeDST
|
||||
let h2_input = [
|
||||
&seed_len,
|
||||
seed.as_slice(),
|
||||
&i.to_be_bytes(),
|
||||
&elem_len,
|
||||
&ci,
|
||||
&elem_len,
|
||||
&di,
|
||||
&composite_dst_len,
|
||||
&composite_dst,
|
||||
];
|
||||
let di = G::hash_to_scalar::<H>(&h2_input, Mode::Verifiable)?;
|
||||
m = c.value * &di + &m;
|
||||
z = match k_option {
|
||||
Some(_) => z,
|
||||
@@ -1082,10 +1178,10 @@ fn compute_composites<G: Group, H: BlockSizeUser + Digest + FixedOutputReset>(
|
||||
|
||||
/// Generates the contextString parameter as defined in
|
||||
/// <https://www.ietf.org/archive/id/draft-irtf-cfrg-voprf-08.html>
|
||||
fn get_context_string<G: Group>(mode: Mode) -> Result<GenericArray<u8, U11>> {
|
||||
Ok(GenericArray::from(STR_VOPRF)
|
||||
.concat(i2osp::<U1>(mode as usize)?)
|
||||
.concat(i2osp::<U2>(G::SUITE_ID)?))
|
||||
pub(crate) fn get_context_string<G: Group>(mode: Mode) -> GenericArray<u8, U11> {
|
||||
GenericArray::from(STR_VOPRF)
|
||||
.concat([mode.to_u8()].into())
|
||||
.concat(G::SUITE_ID.to_be_bytes().into())
|
||||
}
|
||||
|
||||
///////////
|
||||
@@ -1100,7 +1196,7 @@ mod tests {
|
||||
use ::alloc::vec;
|
||||
use ::alloc::vec::Vec;
|
||||
use generic_array::typenum::Sum;
|
||||
use generic_array::{ArrayLength, GenericArray};
|
||||
use generic_array::ArrayLength;
|
||||
use rand::rngs::OsRng;
|
||||
use zeroize::Zeroize;
|
||||
|
||||
@@ -1113,21 +1209,15 @@ mod tests {
|
||||
info: &[u8],
|
||||
mode: Mode,
|
||||
) -> Output<H> {
|
||||
let dst =
|
||||
GenericArray::from(STR_HASH_TO_GROUP).concat(get_context_string::<G>(mode).unwrap());
|
||||
let point = G::hash_to_curve::<H, _>(input, dst).unwrap();
|
||||
let point = G::hash_to_curve::<H>(&[input], mode).unwrap();
|
||||
|
||||
chain!(context,
|
||||
STR_CONTEXT => |x| Some(x.as_ref()),
|
||||
get_context_string::<G>(mode).unwrap() => |x| Some(x.as_slice()),
|
||||
Serialize::<U2>::from(info).unwrap(),
|
||||
);
|
||||
let context_string = get_context_string::<G>(mode);
|
||||
let info_len = i2osp_2(info.len()).unwrap();
|
||||
let context = [&STR_CONTEXT, context_string.as_slice(), &info_len, info];
|
||||
|
||||
let dst =
|
||||
GenericArray::from(STR_HASH_TO_SCALAR).concat(get_context_string::<G>(mode).unwrap());
|
||||
let m = G::hash_to_scalar::<H, _, _>(context, dst).unwrap();
|
||||
let m = G::hash_to_scalar::<H>(&context, mode).unwrap();
|
||||
|
||||
let res = point * &G::scalar_invert(&(key + &m));
|
||||
let res = point * &G::invert_scalar(key + &m);
|
||||
|
||||
finalize_after_unblind::<G, H, _, _>(Some((input, res)).into_iter(), info, mode)
|
||||
.unwrap()
|
||||
@@ -1187,7 +1277,7 @@ mod tests {
|
||||
.unwrap();
|
||||
let wrong_pk = {
|
||||
// Choose a group element that is unlikely to be the right public key
|
||||
G::hash_to_curve::<H, _>(b"msg", (*b"dst").into()).unwrap()
|
||||
G::hash_to_curve::<H>(&[b"msg"], Mode::Base).unwrap()
|
||||
};
|
||||
let client_finalize_result = client_blind_result.state.finalize(
|
||||
input,
|
||||
@@ -1284,7 +1374,7 @@ mod tests {
|
||||
let messages: Vec<_> = messages.collect();
|
||||
let wrong_pk = {
|
||||
// Choose a group element that is unlikely to be the right public key
|
||||
G::hash_to_curve::<H, _>(b"msg", (*b"dst").into()).unwrap()
|
||||
G::hash_to_curve::<H>(&[b"msg"], Mode::Base).unwrap()
|
||||
};
|
||||
let client_finalize_result = VerifiableClient::batch_finalize(
|
||||
&inputs,
|
||||
@@ -1315,9 +1405,7 @@ mod tests {
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let dst = GenericArray::from(STR_HASH_TO_GROUP)
|
||||
.concat(get_context_string::<G>(Mode::Base).unwrap());
|
||||
let point = G::hash_to_curve::<H, _>(&input, dst).unwrap();
|
||||
let point = G::hash_to_curve::<H>(&[&input], Mode::Base).unwrap();
|
||||
let res2 = finalize_after_unblind::<G, H, _, _>(
|
||||
Some((input.as_ref(), point)).into_iter(),
|
||||
info,
|
||||
@@ -1415,38 +1503,39 @@ mod tests {
|
||||
fn test_functionality() -> Result<()> {
|
||||
#[cfg(feature = "ristretto255")]
|
||||
{
|
||||
use curve25519_dalek::ristretto::RistrettoPoint;
|
||||
use sha2::Sha512;
|
||||
|
||||
base_retrieval::<RistrettoPoint, Sha512>();
|
||||
base_inversion_unsalted::<RistrettoPoint, Sha512>();
|
||||
verifiable_retrieval::<RistrettoPoint, Sha512>();
|
||||
verifiable_batch_retrieval::<RistrettoPoint, Sha512>();
|
||||
verifiable_bad_public_key::<RistrettoPoint, Sha512>();
|
||||
verifiable_batch_bad_public_key::<RistrettoPoint, Sha512>();
|
||||
use crate::Ristretto255;
|
||||
|
||||
zeroize_base_client::<RistrettoPoint, Sha512>();
|
||||
zeroize_base_server::<RistrettoPoint, Sha512>();
|
||||
zeroize_verifiable_client::<RistrettoPoint, Sha512>();
|
||||
zeroize_verifiable_server::<RistrettoPoint, Sha512>();
|
||||
base_retrieval::<Ristretto255, Sha512>();
|
||||
base_inversion_unsalted::<Ristretto255, Sha512>();
|
||||
verifiable_retrieval::<Ristretto255, Sha512>();
|
||||
verifiable_batch_retrieval::<Ristretto255, Sha512>();
|
||||
verifiable_bad_public_key::<Ristretto255, Sha512>();
|
||||
verifiable_batch_bad_public_key::<Ristretto255, Sha512>();
|
||||
|
||||
zeroize_base_client::<Ristretto255, Sha512>();
|
||||
zeroize_base_server::<Ristretto255, Sha512>();
|
||||
zeroize_verifiable_client::<Ristretto255, Sha512>();
|
||||
zeroize_verifiable_server::<Ristretto255, Sha512>();
|
||||
}
|
||||
|
||||
#[cfg(feature = "p256")]
|
||||
{
|
||||
use p256_::ProjectivePoint;
|
||||
use p256_::NistP256;
|
||||
use sha2::Sha256;
|
||||
|
||||
base_retrieval::<ProjectivePoint, Sha256>();
|
||||
base_inversion_unsalted::<ProjectivePoint, Sha256>();
|
||||
verifiable_retrieval::<ProjectivePoint, Sha256>();
|
||||
verifiable_batch_retrieval::<ProjectivePoint, Sha256>();
|
||||
verifiable_bad_public_key::<ProjectivePoint, Sha256>();
|
||||
verifiable_batch_bad_public_key::<ProjectivePoint, Sha256>();
|
||||
base_retrieval::<NistP256, Sha256>();
|
||||
base_inversion_unsalted::<NistP256, Sha256>();
|
||||
verifiable_retrieval::<NistP256, Sha256>();
|
||||
verifiable_batch_retrieval::<NistP256, Sha256>();
|
||||
verifiable_bad_public_key::<NistP256, Sha256>();
|
||||
verifiable_batch_bad_public_key::<NistP256, Sha256>();
|
||||
|
||||
zeroize_base_client::<ProjectivePoint, Sha256>();
|
||||
zeroize_base_server::<ProjectivePoint, Sha256>();
|
||||
zeroize_verifiable_client::<ProjectivePoint, Sha256>();
|
||||
zeroize_verifiable_server::<ProjectivePoint, Sha256>();
|
||||
zeroize_base_client::<NistP256, Sha256>();
|
||||
zeroize_base_server::<NistP256, Sha256>();
|
||||
zeroize_verifiable_client::<NistP256, Sha256>();
|
||||
zeroize_verifiable_server::<NistP256, Sha256>();
|
||||
}
|
||||
|
||||
Ok(())
|
||||
|
||||
Reference in New Issue
Block a user