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",
|
"once_cell",
|
||||||
"p256_",
|
"p256_",
|
||||||
]
|
]
|
||||||
ristretto255 = []
|
ristretto255 = ["generic-array/more_lengths"]
|
||||||
ristretto255_fiat_u32 = ["curve25519-dalek/fiat_u32_backend", "ristretto255"]
|
ristretto255_fiat_u32 = ["curve25519-dalek/fiat_u32_backend", "ristretto255"]
|
||||||
ristretto255_fiat_u64 = ["curve25519-dalek/fiat_u64_backend", "ristretto255"]
|
ristretto255_fiat_u64 = ["curve25519-dalek/fiat_u64_backend", "ristretto255"]
|
||||||
ristretto255_simd = ["curve25519-dalek/simd_backend", "ristretto255"]
|
ristretto255_simd = ["curve25519-dalek/simd_backend", "ristretto255"]
|
||||||
|
|||||||
+2
-2
@@ -34,8 +34,8 @@ pub enum Error {
|
|||||||
ProofVerificationError,
|
ProofVerificationError,
|
||||||
/// Encountered insufficient bytes when attempting to deserialize
|
/// Encountered insufficient bytes when attempting to deserialize
|
||||||
SizeError,
|
SizeError,
|
||||||
/// Encountered a zero scalar
|
/// Encountered an invalid scalar
|
||||||
ZeroScalarError,
|
ScalarError,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "std")]
|
#[cfg(feature = "std")]
|
||||||
|
|||||||
+56
-54
@@ -5,74 +5,82 @@
|
|||||||
// License, Version 2.0 found in the LICENSE-APACHE file in the root directory
|
// License, Version 2.0 found in the LICENSE-APACHE file in the root directory
|
||||||
// of this source tree.
|
// 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 digest::{Digest, FixedOutputReset};
|
||||||
use generic_array::sequence::Concat;
|
use generic_array::typenum::{IsLess, NonZero, Unsigned, U65536};
|
||||||
use generic_array::typenum::{Unsigned, U1, U2};
|
|
||||||
use generic_array::{ArrayLength, GenericArray};
|
use generic_array::{ArrayLength, GenericArray};
|
||||||
|
|
||||||
use crate::util::i2osp;
|
|
||||||
use crate::{Error, Result};
|
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> {
|
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()
|
x.into_iter().zip(y).map(|(x1, x2)| x1 ^ x2).collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Corresponds to the expand_message_xmd() function defined in
|
/// Corresponds to the expand_message_xmd() function defined in
|
||||||
/// <https://www.ietf.org/archive/id/draft-irtf-cfrg-hash-to-curve-10.txt>
|
/// <https://www.ietf.org/archive/id/draft-irtf-cfrg-hash-to-curve-10.txt>
|
||||||
pub fn expand_message_xmd<
|
pub fn expand_message_xmd<H: BlockSizeUser + Digest + FixedOutputReset, L: ArrayLength<u8>>(
|
||||||
'a,
|
msg: &[&[u8]],
|
||||||
H: BlockSizeUser + Digest + FixedOutputReset,
|
dst: &[u8],
|
||||||
L: ArrayLength<u8>,
|
|
||||||
M: IntoIterator<Item = &'a [u8]>,
|
|
||||||
D: ArrayLength<u8> + Add<U1>,
|
|
||||||
>(
|
|
||||||
msg: M,
|
|
||||||
dst: GenericArray<u8, D>,
|
|
||||||
) -> Result<GenericArray<u8, L>>
|
) -> Result<GenericArray<u8, L>>
|
||||||
where
|
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;
|
// DST, a byte string of at most 255 bytes.
|
||||||
let ell = div_ceil(L::USIZE, digest_len);
|
let dst_len = u8::try_from(dst.len()).map_err(|_| Error::HashToCurveError)?;
|
||||||
if ell > 255 {
|
|
||||||
|
// 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);
|
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
|
// msg_prime = Z_pad || msg || l_i_b_str || I2OSP(0, 1) || DST_prime
|
||||||
Digest::update(&mut h, z_pad);
|
// Z_pad = I2OSP(0, s_in_bytes)
|
||||||
for bytes in msg {
|
// s_in_bytes, the input block size of H, measured in bytes
|
||||||
Digest::update(&mut h, 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);
|
// l_i_b_str = I2OSP(len_in_bytes, 2)
|
||||||
Digest::update(&mut h, i2osp::<U1>(0)?);
|
Digest::update(&mut hash, L::U16.to_be_bytes());
|
||||||
Digest::update(&mut h, &dst_prime);
|
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 b_i = GenericArray::default();
|
||||||
|
|
||||||
let mut uniform_bytes = GenericArray::default();
|
let mut uniform_bytes = GenericArray::default();
|
||||||
|
|
||||||
for (i, chunk) in (1..(ell + 1)).zip(uniform_bytes.chunks_mut(digest_len)) {
|
// b_1 = H(b_0 || I2OSP(1, 1) || DST_prime)
|
||||||
Digest::update(&mut h, xor(b_0.clone(), b_i.clone()));
|
// for i in (2, ..., ell):
|
||||||
Digest::update(&mut h, i2osp::<U1>(i)?);
|
for (i, chunk) in (1..(ell + 1)).zip(uniform_bytes.chunks_mut(b_in_bytes)) {
|
||||||
Digest::update(&mut h, &dst_prime);
|
// b_i = H(strxor(b_0, b_(i - 1)) || I2OSP(i, 1) || DST_prime)
|
||||||
b_i = h.finalize_reset();
|
Digest::update(&mut hash, xor(b_0.clone(), b_i.clone()));
|
||||||
chunk.copy_from_slice(&b_i[..digest_len.min(chunk.len())]);
|
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)
|
Ok(uniform_bytes)
|
||||||
@@ -81,7 +89,6 @@ where
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use generic_array::typenum::{U128, U32};
|
use generic_array::typenum::{U128, U32};
|
||||||
use generic_array::GenericArray;
|
|
||||||
|
|
||||||
struct Params {
|
struct Params {
|
||||||
msg: &'static str,
|
msg: &'static str,
|
||||||
@@ -91,6 +98,8 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_expand_message_xmd() {
|
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
|
// 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![
|
let test_vectors: alloc::vec::Vec<Params> = alloc::vec![
|
||||||
Params {
|
Params {
|
||||||
@@ -190,20 +199,13 @@ mod tests {
|
|||||||
378fba044a31f5cb44583a892f5969dcd73b3fa128816e",
|
378fba044a31f5cb44583a892f5969dcd73b3fa128816e",
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
let dst = GenericArray::from(*b"QUUX-V01-CS02-with-expander");
|
|
||||||
|
|
||||||
for tv in test_vectors {
|
for tv in test_vectors {
|
||||||
let uniform_bytes = match tv.len_in_bytes {
|
let uniform_bytes = match tv.len_in_bytes {
|
||||||
32 => super::expand_message_xmd::<sha2::Sha256, U32, _, _>(
|
32 => super::expand_message_xmd::<sha2::Sha256, U32>(&[tv.msg.as_bytes()], &DST)
|
||||||
Some(tv.msg.as_bytes()),
|
.map(|bytes| bytes.to_vec()),
|
||||||
dst,
|
128 => super::expand_message_xmd::<sha2::Sha256, U128>(&[tv.msg.as_bytes()], &DST)
|
||||||
)
|
.map(|bytes| bytes.to_vec()),
|
||||||
.map(|bytes| bytes.to_vec()),
|
|
||||||
128 => super::expand_message_xmd::<sha2::Sha256, U128, _, _>(
|
|
||||||
Some(tv.msg.as_bytes()),
|
|
||||||
dst,
|
|
||||||
)
|
|
||||||
.map(|bytes| bytes.to_vec()),
|
|
||||||
_ => unimplemented!(),
|
_ => unimplemented!(),
|
||||||
}
|
}
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|||||||
+48
-87
@@ -18,47 +18,36 @@ use core::ops::{Add, Mul, Sub};
|
|||||||
|
|
||||||
use digest::core_api::BlockSizeUser;
|
use digest::core_api::BlockSizeUser;
|
||||||
use digest::{Digest, FixedOutputReset};
|
use digest::{Digest, FixedOutputReset};
|
||||||
use generic_array::typenum::U1;
|
|
||||||
use generic_array::{ArrayLength, GenericArray};
|
use generic_array::{ArrayLength, GenericArray};
|
||||||
use rand_core::{CryptoRng, RngCore};
|
use rand_core::{CryptoRng, RngCore};
|
||||||
|
#[cfg(feature = "ristretto255")]
|
||||||
|
pub use ristretto::Ristretto255;
|
||||||
use subtle::ConstantTimeEq;
|
use subtle::ConstantTimeEq;
|
||||||
use zeroize::Zeroize;
|
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
|
/// 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.
|
/// subgroup is noted additively — as in the draft RFC — in this trait.
|
||||||
pub trait Group:
|
pub trait Group {
|
||||||
Copy
|
|
||||||
+ Sized
|
|
||||||
+ ConstantTimeEq
|
|
||||||
+ for<'a> Mul<&'a <Self as Group>::Scalar, Output = Self>
|
|
||||||
+ for<'a> Add<&'a Self, Output = Self>
|
|
||||||
{
|
|
||||||
/// The ciphersuite identifier as dictated by
|
/// The ciphersuite identifier as dictated by
|
||||||
/// <https://www.ietf.org/archive/id/draft-irtf-cfrg-voprf-05.txt>
|
/// <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
|
/// The type of group elements
|
||||||
fn hash_to_curve<H: BlockSizeUser + Digest + FixedOutputReset, D: ArrayLength<u8> + Add<U1>>(
|
type Elem: Copy
|
||||||
msg: &[u8],
|
+ Sized
|
||||||
dst: GenericArray<u8, D>,
|
+ ConstantTimeEq
|
||||||
) -> Result<Self>
|
+ Zeroize
|
||||||
where
|
+ for<'a> Mul<&'a Self::Scalar, Output = Self::Elem>
|
||||||
<D as Add<U1>>::Output: ArrayLength<u8>;
|
+ for<'a> Add<&'a Self::Elem, Output = Self::Elem>;
|
||||||
|
|
||||||
/// Hashes a slice of pseudo-random bytes to a scalar
|
/// The byte length necessary to represent group elements
|
||||||
fn hash_to_scalar<
|
type ElemLen: ArrayLength<u8> + 'static;
|
||||||
'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 type of base field scalars
|
/// The type of base field scalars
|
||||||
type Scalar: Zeroize
|
type Scalar: Zeroize
|
||||||
@@ -67,79 +56,51 @@ pub trait Group:
|
|||||||
+ for<'a> Add<&'a Self::Scalar, Output = Self::Scalar>
|
+ for<'a> Add<&'a Self::Scalar, Output = Self::Scalar>
|
||||||
+ for<'a> Sub<&'a Self::Scalar, Output = Self::Scalar>
|
+ for<'a> Sub<&'a Self::Scalar, Output = Self::Scalar>
|
||||||
+ for<'a> Mul<&'a Self::Scalar, Output = Self::Scalar>;
|
+ for<'a> Mul<&'a Self::Scalar, Output = Self::Scalar>;
|
||||||
|
|
||||||
/// The byte length necessary to represent scalars
|
/// The byte length necessary to represent scalars
|
||||||
type ScalarLen: ArrayLength<u8> + 'static;
|
type ScalarLen: ArrayLength<u8> + 'static;
|
||||||
|
|
||||||
/// Return a scalar from its fixed-length bytes representation, without
|
/// transforms a password and domain separation tag (DST) into a curve point
|
||||||
/// checking if the scalar is zero.
|
fn hash_to_curve<H: BlockSizeUser + Digest + FixedOutputReset>(
|
||||||
fn from_scalar_slice_unchecked(
|
msg: &[&[u8]],
|
||||||
scalar_bits: &GenericArray<u8, Self::ScalarLen>,
|
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>;
|
) -> Result<Self::Scalar>;
|
||||||
|
|
||||||
/// Return a scalar from its fixed-length bytes representation. If the
|
/// Get the base point for the group
|
||||||
/// scalar is zero, then return an error.
|
fn base_elem() -> Self::Elem;
|
||||||
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)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// picks a scalar at random
|
/// Returns the identity group element
|
||||||
fn random_nonzero_scalar<R: RngCore + CryptoRng>(rng: &mut R) -> Self::Scalar;
|
fn identity_elem() -> Self::Elem;
|
||||||
/// 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;
|
|
||||||
|
|
||||||
/// The byte length necessary to represent group elements
|
/// Serializes the `self` group element
|
||||||
type ElemLen: ArrayLength<u8> + 'static;
|
fn serialize_elem(elem: Self::Elem) -> GenericArray<u8, Self::ElemLen>;
|
||||||
|
|
||||||
/// 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>;
|
|
||||||
|
|
||||||
/// Return an element from its fixed-length bytes representation. If the
|
/// Return an element from its fixed-length bytes representation. If the
|
||||||
/// element is the identity element, return an error.
|
/// element is the identity element, return an error.
|
||||||
fn from_element_slice<'a>(
|
fn deserialize_elem(element_bits: &GenericArray<u8, Self::ElemLen>) -> Result<Self::Elem>;
|
||||||
element_bits: impl Into<&'a GenericArray<u8, Self::ElemLen>>,
|
|
||||||
) -> Result<Self> {
|
|
||||||
let elem = Self::from_element_slice_unchecked(element_bits.into())?;
|
|
||||||
|
|
||||||
if Self::ct_eq(&elem, &<Self as Group>::identity()).into() {
|
/// picks a scalar at random
|
||||||
// found the identity element
|
fn random_scalar<R: RngCore + CryptoRng>(rng: &mut R) -> Self::Scalar;
|
||||||
return Err(Error::PointError);
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(elem)
|
/// The multiplicative inverse of this scalar
|
||||||
}
|
fn invert_scalar(scalar: Self::Scalar) -> Self::Scalar;
|
||||||
|
|
||||||
/// 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;
|
|
||||||
|
|
||||||
/// Returns the scalar representing zero
|
/// 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
|
/// Serializes a scalar to bytes
|
||||||
fn zeroize(&mut self) {
|
fn serialize_scalar(scalar: Self::Scalar) -> GenericArray<u8, Self::ScalarLen>;
|
||||||
*self = <Self as Group>::identity();
|
|
||||||
}
|
/// 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)]
|
#[cfg(test)]
|
||||||
|
|||||||
+77
-78
@@ -18,22 +18,26 @@ use core::str::FromStr;
|
|||||||
|
|
||||||
use digest::core_api::BlockSizeUser;
|
use digest::core_api::BlockSizeUser;
|
||||||
use digest::{Digest, FixedOutputReset};
|
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 generic_array::{ArrayLength, GenericArray};
|
||||||
use num_bigint::{BigInt, Sign};
|
use num_bigint::{BigInt, Sign};
|
||||||
use num_integer::Integer;
|
use num_integer::Integer;
|
||||||
use num_traits::{One, ToPrimitive, Zero};
|
use num_traits::{One, ToPrimitive, Zero};
|
||||||
use once_cell::unsync::Lazy;
|
use once_cell::unsync::Lazy;
|
||||||
|
use p256_::elliptic_curve::bigint::{Encoding, U384};
|
||||||
use p256_::elliptic_curve::group::prime::PrimeCurveAffine;
|
use p256_::elliptic_curve::group::prime::PrimeCurveAffine;
|
||||||
use p256_::elliptic_curve::group::GroupEncoding;
|
|
||||||
use p256_::elliptic_curve::ops::Reduce;
|
use p256_::elliptic_curve::ops::Reduce;
|
||||||
use p256_::elliptic_curve::sec1::{FromEncodedPoint, ToEncodedPoint};
|
use p256_::elliptic_curve::sec1::{FromEncodedPoint, ToEncodedPoint};
|
||||||
|
#[cfg(test)]
|
||||||
use p256_::elliptic_curve::Field;
|
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 rand_core::{CryptoRng, RngCore};
|
||||||
use subtle::{Choice, ConditionallySelectable};
|
use subtle::{Choice, ConditionallySelectable};
|
||||||
|
|
||||||
use super::Group;
|
use super::Group;
|
||||||
|
use crate::group::{STR_HASH_TO_GROUP, STR_HASH_TO_SCALAR};
|
||||||
|
use crate::voprf::{self, Mode};
|
||||||
use crate::{Error, Result};
|
use crate::{Error, Result};
|
||||||
|
|
||||||
// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-8.2
|
// 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;
|
pub type L = U48;
|
||||||
|
|
||||||
#[cfg(feature = "p256")]
|
#[cfg(feature = "p256")]
|
||||||
impl Group for ProjectivePoint {
|
impl Group for NistP256 {
|
||||||
const SUITE_ID: usize = 0x0003;
|
const SUITE_ID: u16 = 0x0003;
|
||||||
|
|
||||||
|
type Elem = ProjectivePoint;
|
||||||
|
|
||||||
|
type ElemLen = U33;
|
||||||
|
|
||||||
|
type Scalar = Scalar;
|
||||||
|
|
||||||
|
type ScalarLen = U32;
|
||||||
|
|
||||||
// Implements the `hash_to_curve()` function from
|
// Implements the `hash_to_curve()` function from
|
||||||
// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-3
|
// 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>>(
|
fn hash_to_curve<H: BlockSizeUser + Digest + FixedOutputReset>(
|
||||||
msg: &[u8],
|
msg: &[&[u8]],
|
||||||
dst: GenericArray<u8, D>,
|
mode: Mode,
|
||||||
) -> Result<Self>
|
) -> Result<Self::Elem> {
|
||||||
where
|
let dst =
|
||||||
<D as Add<U1>>::Output: ArrayLength<u8>,
|
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
|
// 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`
|
// `p: 2^256 - 2^224 + 2^192 + 2^96 - 1`
|
||||||
const P: Lazy<BigInt> = Lazy::new(|| {
|
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
|
// 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`
|
// `hash_to_field` calls `expand_message` with a `len_in_bytes` of `count * L`
|
||||||
let uniform_bytes =
|
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
|
// hash to curve
|
||||||
let (q0x, q0y) = hash_to_curve_simple_swu(&uniform_bytes[..L::USIZE], &A, &B, &P, &Z);
|
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
|
// Implements the `HashToScalar()` function
|
||||||
fn hash_to_scalar<
|
fn hash_to_scalar<H: BlockSizeUser + Digest + FixedOutputReset>(
|
||||||
'a,
|
input: &[&[u8]],
|
||||||
H: BlockSizeUser + Digest + FixedOutputReset,
|
mode: Mode,
|
||||||
D: ArrayLength<u8> + Add<U1>,
|
) -> Result<Self::Scalar> {
|
||||||
I: IntoIterator<Item = &'a [u8]>,
|
let dst =
|
||||||
>(
|
GenericArray::from(STR_HASH_TO_SCALAR).concat(voprf::get_context_string::<Self>(mode));
|
||||||
input: I,
|
|
||||||
dst: GenericArray<u8, D>,
|
|
||||||
) -> Result<Self::Scalar>
|
|
||||||
where
|
|
||||||
<D as Add<U1>>::Output: ArrayLength<u8>,
|
|
||||||
{
|
|
||||||
// https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf#[{%22num%22:211,%22gen%22:0},{%22name%22:%22XYZ%22},70,700,0]
|
// 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
|
// P-256 `n` is defined as
|
||||||
// `115792089210356248762697446949407573529996955224135760342
|
// `115792089210356248762697446949407573529996955224135760342
|
||||||
// 422259061068512044369`
|
// 422259061068512044369`
|
||||||
const N: Lazy<BigInt> = Lazy::new(|| {
|
const N: U384 =
|
||||||
BigInt::from_str(
|
U384::from_be_hex("00000000000000000000000000000000FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551");
|
||||||
"115792089210356248762697446949407573529996955224135760342422259061068512044369",
|
|
||||||
)
|
|
||||||
.unwrap()
|
|
||||||
});
|
|
||||||
|
|
||||||
// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-5.3
|
// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-5.3
|
||||||
// `HashToScalar` is `hash_to_field`
|
// `HashToScalar` is `hash_to_field`
|
||||||
let uniform_bytes = super::expand::expand_message_xmd::<H, L, _, _>(input, dst)?;
|
let uniform_bytes = super::expand::expand_message_xmd::<H, L>(input, &dst)?;
|
||||||
let bytes = BigInt::from_bytes_be(Sign::Plus, &uniform_bytes)
|
let bytes = Option::<U384>::from(U384::from_be_slice(&uniform_bytes).reduce(&N))
|
||||||
.mod_floor(&N)
|
.unwrap()
|
||||||
.to_bytes_be()
|
.to_be_bytes();
|
||||||
.1;
|
|
||||||
let mut result = GenericArray::default();
|
|
||||||
result[..bytes.len()].copy_from_slice(&bytes);
|
|
||||||
|
|
||||||
Ok(p256_::Scalar::from_be_bytes_reduced(result))
|
Ok(Scalar::from_be_bytes_reduced(
|
||||||
|
GenericArray::clone_from_slice(&bytes[16..]),
|
||||||
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
type ElemLen = U33;
|
fn base_elem() -> Self::Elem {
|
||||||
type Scalar = p256_::Scalar;
|
ProjectivePoint::generator()
|
||||||
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 random_nonzero_scalar<R: RngCore + CryptoRng>(rng: &mut R) -> Self::Scalar {
|
fn identity_elem() -> Self::Elem {
|
||||||
Self::Scalar::random(rng)
|
ProjectivePoint::identity()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn scalar_as_bytes(scalar: Self::Scalar) -> GenericArray<u8, Self::ScalarLen> {
|
fn serialize_elem(elem: Self::Elem) -> GenericArray<u8, Self::ElemLen> {
|
||||||
scalar.into()
|
let bytes = elem.to_affine().to_encoded_point(true);
|
||||||
}
|
|
||||||
|
|
||||||
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);
|
|
||||||
let bytes = bytes.as_bytes();
|
let bytes = bytes.as_bytes();
|
||||||
let mut result = GenericArray::default();
|
let mut result = GenericArray::default();
|
||||||
result[..bytes.len()].copy_from_slice(bytes);
|
result[..bytes.len()].copy_from_slice(bytes);
|
||||||
result
|
result
|
||||||
}
|
}
|
||||||
|
|
||||||
fn base_point() -> Self {
|
fn deserialize_elem(element_bits: &GenericArray<u8, Self::ElemLen>) -> Result<Self::Elem> {
|
||||||
Self::generator()
|
PublicKey::from_sec1_bytes(element_bits)
|
||||||
|
.map(|public_key| public_key.to_projective())
|
||||||
|
.map_err(|_| Error::PointError)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn identity() -> Self {
|
fn random_scalar<R: RngCore + CryptoRng>(rng: &mut R) -> Self::Scalar {
|
||||||
Self::identity()
|
*SecretKey::random(rng).to_nonzero_scalar()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn scalar_zero() -> Self::Scalar {
|
fn invert_scalar(scalar: Self::Scalar) -> Self::Scalar {
|
||||||
Self::Scalar::zero()
|
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]
|
#[test]
|
||||||
fn hash_to_curve_simple_swu() {
|
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(|| {
|
const P: Lazy<BigInt> = Lazy::new(|| {
|
||||||
BigInt::from_str(
|
BigInt::from_str(
|
||||||
"115792089210356248762697446949407573530086143415290314195533631308867097853951",
|
"115792089210356248762697446949407573530086143415290314195533631308867097853951",
|
||||||
@@ -544,15 +545,13 @@ mod tests {
|
|||||||
q1y: "f6ed88a7aab56a488100e6f1174fa9810b47db13e86be999644922961206e184",
|
q1y: "f6ed88a7aab56a488100e6f1174fa9810b47db13e86be999644922961206e184",
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
let dst = GenericArray::from(*b"QUUX-V01-CS02-with-P256_XMD:SHA-256_SSWU_RO_");
|
|
||||||
|
|
||||||
for tv in test_vectors {
|
for tv in test_vectors {
|
||||||
let uniform_bytes =
|
let uniform_bytes = super::super::expand::expand_message_xmd::<sha2::Sha256, U96>(
|
||||||
super::super::expand::expand_message_xmd::<sha2::Sha256, U96, _, _>(
|
&[tv.msg.as_bytes()],
|
||||||
Some(tv.msg.as_bytes()),
|
&DST,
|
||||||
dst,
|
)
|
||||||
)
|
.unwrap();
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
let u0 = BigInt::from_bytes_be(Sign::Plus, &uniform_bytes[..48]).mod_floor(&P);
|
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);
|
let u1 = BigInt::from_bytes_be(Sign::Plus, &uniform_bytes[48..]).mod_floor(&P);
|
||||||
|
|||||||
+64
-66
@@ -6,7 +6,6 @@
|
|||||||
// of this source tree.
|
// of this source tree.
|
||||||
|
|
||||||
use core::convert::TryInto;
|
use core::convert::TryInto;
|
||||||
use core::ops::Add;
|
|
||||||
|
|
||||||
use curve25519_dalek::constants::RISTRETTO_BASEPOINT_POINT;
|
use curve25519_dalek::constants::RISTRETTO_BASEPOINT_POINT;
|
||||||
use curve25519_dalek::ristretto::{CompressedRistretto, RistrettoPoint};
|
use curve25519_dalek::ristretto::{CompressedRistretto, RistrettoPoint};
|
||||||
@@ -14,53 +13,55 @@ use curve25519_dalek::scalar::Scalar;
|
|||||||
use curve25519_dalek::traits::Identity;
|
use curve25519_dalek::traits::Identity;
|
||||||
use digest::core_api::BlockSizeUser;
|
use digest::core_api::BlockSizeUser;
|
||||||
use digest::{Digest, FixedOutputReset};
|
use digest::{Digest, FixedOutputReset};
|
||||||
use generic_array::typenum::{U1, U32, U64};
|
use generic_array::sequence::Concat;
|
||||||
use generic_array::{ArrayLength, GenericArray};
|
use generic_array::typenum::{U32, U64};
|
||||||
|
use generic_array::GenericArray;
|
||||||
use rand_core::{CryptoRng, RngCore};
|
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};
|
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` 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")]
|
#[cfg(feature = "ristretto255")]
|
||||||
/// The implementation of such a subgroup for Ristretto
|
impl Group for Ristretto255 {
|
||||||
impl Group for RistrettoPoint {
|
const SUITE_ID: u16 = 0x0001;
|
||||||
const SUITE_ID: usize = 0x0001;
|
|
||||||
|
type Elem = RistrettoPoint;
|
||||||
|
|
||||||
|
type ElemLen = U32;
|
||||||
|
|
||||||
|
type Scalar = Scalar;
|
||||||
|
|
||||||
|
type ScalarLen = U32;
|
||||||
|
|
||||||
// Implements the `hash_to_ristretto255()` function from
|
// Implements the `hash_to_ristretto255()` function from
|
||||||
// https://www.ietf.org/archive/id/draft-irtf-cfrg-hash-to-curve-10.txt
|
// 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>>(
|
fn hash_to_curve<H: BlockSizeUser + Digest + FixedOutputReset>(
|
||||||
msg: &[u8],
|
msg: &[&[u8]],
|
||||||
dst: GenericArray<u8, D>,
|
mode: Mode,
|
||||||
) -> Result<Self>
|
) -> Result<Self::Elem> {
|
||||||
where
|
let dst =
|
||||||
<D as Add<U1>>::Output: ArrayLength<u8>,
|
GenericArray::from(STR_HASH_TO_GROUP).concat(voprf::get_context_string::<Self>(mode));
|
||||||
{
|
|
||||||
let uniform_bytes = super::expand::expand_message_xmd::<H, U64, _, _>(Some(msg), dst)?;
|
|
||||||
|
|
||||||
Ok(RistrettoPoint::from_uniform_bytes(
|
let uniform_bytes = expand::expand_message_xmd::<H, U64>(msg, &dst)?;
|
||||||
uniform_bytes
|
|
||||||
.as_slice()
|
Ok(RistrettoPoint::from_uniform_bytes(&uniform_bytes.into()))
|
||||||
.try_into()
|
|
||||||
.map_err(|_| Error::HashToCurveError)?,
|
|
||||||
))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Implements the `HashToScalar()` function from
|
// Implements the `HashToScalar()` function from
|
||||||
// https://www.ietf.org/archive/id/draft-irtf-cfrg-voprf-07.html#section-4.1
|
// https://www.ietf.org/archive/id/draft-irtf-cfrg-voprf-07.html#section-4.1
|
||||||
fn hash_to_scalar<
|
fn hash_to_scalar<'a, H: BlockSizeUser + Digest + FixedOutputReset>(
|
||||||
'a,
|
input: &[&[u8]],
|
||||||
H: BlockSizeUser + Digest + FixedOutputReset,
|
mode: Mode,
|
||||||
D: ArrayLength<u8> + Add<U1>,
|
) -> Result<Self::Scalar> {
|
||||||
I: IntoIterator<Item = &'a [u8]>,
|
let dst =
|
||||||
>(
|
GenericArray::from(STR_HASH_TO_SCALAR).concat(voprf::get_context_string::<Self>(mode));
|
||||||
input: I,
|
|
||||||
dst: GenericArray<u8, D>,
|
let uniform_bytes = expand::expand_message_xmd::<H, U64>(input, &dst)?;
|
||||||
) -> Result<Self::Scalar>
|
|
||||||
where
|
|
||||||
<D as Add<U1>>::Output: ArrayLength<u8>,
|
|
||||||
{
|
|
||||||
let uniform_bytes = super::expand::expand_message_xmd::<H, U64, _, _>(input, dst)?;
|
|
||||||
|
|
||||||
Ok(Scalar::from_bytes_mod_order_wide(
|
Ok(Scalar::from_bytes_mod_order_wide(
|
||||||
uniform_bytes
|
uniform_bytes
|
||||||
@@ -70,15 +71,27 @@ impl Group for RistrettoPoint {
|
|||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
type Scalar = Scalar;
|
fn base_elem() -> Self::Elem {
|
||||||
type ScalarLen = U32;
|
RISTRETTO_BASEPOINT_POINT
|
||||||
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 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 {
|
loop {
|
||||||
let scalar = {
|
let scalar = {
|
||||||
let mut scalar_bytes = [0u8; 64];
|
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> {
|
fn invert_scalar(scalar: Self::Scalar) -> Self::Scalar {
|
||||||
scalar.to_bytes().into()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn scalar_invert(scalar: &Self::Scalar) -> Self::Scalar {
|
|
||||||
scalar.invert()
|
scalar.invert()
|
||||||
}
|
}
|
||||||
|
|
||||||
// The byte length necessary to represent group elements
|
#[cfg(test)]
|
||||||
type ElemLen = U32;
|
fn zero_scalar() -> Self::Scalar {
|
||||||
fn from_element_slice_unchecked(
|
Scalar::zero()
|
||||||
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()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn base_point() -> Self {
|
fn serialize_scalar(scalar: Self::Scalar) -> GenericArray<u8, Self::ScalarLen> {
|
||||||
RISTRETTO_BASEPOINT_POINT
|
scalar.to_bytes().into()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn identity() -> Self {
|
fn deserialize_scalar(scalar_bits: &GenericArray<u8, Self::ScalarLen>) -> Result<Self::Scalar> {
|
||||||
<Self as Identity>::identity()
|
Scalar::from_canonical_bytes((*scalar_bits).into())
|
||||||
}
|
.filter(|scalar| scalar != &Scalar::zero())
|
||||||
|
.ok_or(Error::ScalarError)
|
||||||
fn scalar_zero() -> Self::Scalar {
|
|
||||||
Self::Scalar::zero()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+11
-11
@@ -16,18 +16,18 @@ use crate::{Error, Group, Result};
|
|||||||
fn test_group_properties() -> Result<()> {
|
fn test_group_properties() -> Result<()> {
|
||||||
#[cfg(feature = "ristretto255")]
|
#[cfg(feature = "ristretto255")]
|
||||||
{
|
{
|
||||||
use curve25519_dalek::ristretto::RistrettoPoint;
|
use crate::Ristretto255;
|
||||||
|
|
||||||
test_identity_element_error::<RistrettoPoint>()?;
|
test_identity_element_error::<Ristretto255>()?;
|
||||||
test_zero_scalar_error::<RistrettoPoint>()?;
|
test_zero_scalar_error::<Ristretto255>()?;
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "p256")]
|
#[cfg(feature = "p256")]
|
||||||
{
|
{
|
||||||
use p256_::ProjectivePoint;
|
use p256_::NistP256;
|
||||||
|
|
||||||
test_identity_element_error::<ProjectivePoint>()?;
|
test_identity_element_error::<NistP256>()?;
|
||||||
test_zero_scalar_error::<ProjectivePoint>()?;
|
test_zero_scalar_error::<NistP256>()?;
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -35,8 +35,8 @@ fn test_group_properties() -> Result<()> {
|
|||||||
|
|
||||||
// Checks that the identity element cannot be deserialized
|
// Checks that the identity element cannot be deserialized
|
||||||
fn test_identity_element_error<G: Group>() -> Result<()> {
|
fn test_identity_element_error<G: Group>() -> Result<()> {
|
||||||
let identity = G::identity();
|
let identity = G::identity_elem();
|
||||||
let result = G::from_element_slice(&identity.to_arr());
|
let result = G::deserialize_elem(&G::serialize_elem(identity));
|
||||||
assert!(matches!(result, Err(Error::PointError)));
|
assert!(matches!(result, Err(Error::PointError)));
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -44,9 +44,9 @@ fn test_identity_element_error<G: Group>() -> Result<()> {
|
|||||||
|
|
||||||
// Checks that the zero scalar cannot be deserialized
|
// Checks that the zero scalar cannot be deserialized
|
||||||
fn test_zero_scalar_error<G: Group>() -> Result<()> {
|
fn test_zero_scalar_error<G: Group>() -> Result<()> {
|
||||||
let zero_scalar = G::scalar_zero();
|
let zero_scalar = G::zero_scalar();
|
||||||
let result = G::from_scalar_slice(&G::scalar_as_bytes(zero_scalar));
|
let result = G::deserialize_scalar(&G::serialize_scalar(zero_scalar));
|
||||||
assert!(matches!(result, Err(Error::ZeroScalarError)));
|
assert!(matches!(result, Err(Error::ScalarError)));
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
+45
-38
@@ -24,7 +24,7 @@
|
|||||||
//! We will use the following choices in this example:
|
//! We will use the following choices in this example:
|
||||||
//!
|
//!
|
||||||
//! ```ignore
|
//! ```ignore
|
||||||
//! type Group = curve25519_dalek::ristretto::RistrettoPoint;
|
//! type Group = voprf::Ristretto255;
|
||||||
//! type Hash = sha2::Sha512;
|
//! type Hash = sha2::Sha512;
|
||||||
//! ```
|
//! ```
|
||||||
//!
|
//!
|
||||||
@@ -52,11 +52,11 @@
|
|||||||
//!
|
//!
|
||||||
//! ```
|
//! ```
|
||||||
//! # #[cfg(feature = "ristretto255")]
|
//! # #[cfg(feature = "ristretto255")]
|
||||||
//! # type Group = curve25519_dalek::ristretto::RistrettoPoint;
|
//! # type Group = voprf::Ristretto255;
|
||||||
//! # #[cfg(feature = "ristretto255")]
|
//! # #[cfg(feature = "ristretto255")]
|
||||||
//! # type Hash = sha2::Sha512;
|
//! # type Hash = sha2::Sha512;
|
||||||
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
||||||
//! # type Group = p256_::ProjectivePoint;
|
//! # type Group = p256_::NistP256;
|
||||||
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
||||||
//! # type Hash = sha2::Sha256;
|
//! # type Hash = sha2::Sha256;
|
||||||
//! use rand::rngs::OsRng;
|
//! use rand::rngs::OsRng;
|
||||||
@@ -78,11 +78,11 @@
|
|||||||
//!
|
//!
|
||||||
//! ```
|
//! ```
|
||||||
//! # #[cfg(feature = "ristretto255")]
|
//! # #[cfg(feature = "ristretto255")]
|
||||||
//! # type Group = curve25519_dalek::ristretto::RistrettoPoint;
|
//! # type Group = voprf::Ristretto255;
|
||||||
//! # #[cfg(feature = "ristretto255")]
|
//! # #[cfg(feature = "ristretto255")]
|
||||||
//! # type Hash = sha2::Sha512;
|
//! # type Hash = sha2::Sha512;
|
||||||
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
||||||
//! # type Group = p256_::ProjectivePoint;
|
//! # type Group = p256_::NistP256;
|
||||||
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
||||||
//! # type Hash = sha2::Sha256;
|
//! # type Hash = sha2::Sha256;
|
||||||
//! use rand::rngs::OsRng;
|
//! use rand::rngs::OsRng;
|
||||||
@@ -104,11 +104,11 @@
|
|||||||
//!
|
//!
|
||||||
//! ```
|
//! ```
|
||||||
//! # #[cfg(feature = "ristretto255")]
|
//! # #[cfg(feature = "ristretto255")]
|
||||||
//! # type Group = curve25519_dalek::ristretto::RistrettoPoint;
|
//! # type Group = voprf::Ristretto255;
|
||||||
//! # #[cfg(feature = "ristretto255")]
|
//! # #[cfg(feature = "ristretto255")]
|
||||||
//! # type Hash = sha2::Sha512;
|
//! # type Hash = sha2::Sha512;
|
||||||
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
||||||
//! # type Group = p256_::ProjectivePoint;
|
//! # type Group = p256_::NistP256;
|
||||||
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
||||||
//! # type Hash = sha2::Sha256;
|
//! # type Hash = sha2::Sha256;
|
||||||
//! # use voprf::NonVerifiableClient;
|
//! # use voprf::NonVerifiableClient;
|
||||||
@@ -136,11 +136,11 @@
|
|||||||
//!
|
//!
|
||||||
//! ```
|
//! ```
|
||||||
//! # #[cfg(feature = "ristretto255")]
|
//! # #[cfg(feature = "ristretto255")]
|
||||||
//! # type Group = curve25519_dalek::ristretto::RistrettoPoint;
|
//! # type Group = voprf::Ristretto255;
|
||||||
//! # #[cfg(feature = "ristretto255")]
|
//! # #[cfg(feature = "ristretto255")]
|
||||||
//! # type Hash = sha2::Sha512;
|
//! # type Hash = sha2::Sha512;
|
||||||
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
||||||
//! # type Group = p256_::ProjectivePoint;
|
//! # type Group = p256_::NistP256;
|
||||||
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
||||||
//! # type Hash = sha2::Sha256;
|
//! # type Hash = sha2::Sha256;
|
||||||
//! # use voprf::NonVerifiableClient;
|
//! # use voprf::NonVerifiableClient;
|
||||||
@@ -187,11 +187,11 @@
|
|||||||
//!
|
//!
|
||||||
//! ```
|
//! ```
|
||||||
//! # #[cfg(feature = "ristretto255")]
|
//! # #[cfg(feature = "ristretto255")]
|
||||||
//! # type Group = curve25519_dalek::ristretto::RistrettoPoint;
|
//! # type Group = voprf::Ristretto255;
|
||||||
//! # #[cfg(feature = "ristretto255")]
|
//! # #[cfg(feature = "ristretto255")]
|
||||||
//! # type Hash = sha2::Sha512;
|
//! # type Hash = sha2::Sha512;
|
||||||
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
||||||
//! # type Group = p256_::ProjectivePoint;
|
//! # type Group = p256_::NistP256;
|
||||||
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
||||||
//! # type Hash = sha2::Sha256;
|
//! # type Hash = sha2::Sha256;
|
||||||
//! use rand::rngs::OsRng;
|
//! use rand::rngs::OsRng;
|
||||||
@@ -220,11 +220,11 @@
|
|||||||
//!
|
//!
|
||||||
//! ```
|
//! ```
|
||||||
//! # #[cfg(feature = "ristretto255")]
|
//! # #[cfg(feature = "ristretto255")]
|
||||||
//! # type Group = curve25519_dalek::ristretto::RistrettoPoint;
|
//! # type Group = voprf::Ristretto255;
|
||||||
//! # #[cfg(feature = "ristretto255")]
|
//! # #[cfg(feature = "ristretto255")]
|
||||||
//! # type Hash = sha2::Sha512;
|
//! # type Hash = sha2::Sha512;
|
||||||
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
||||||
//! # type Group = p256_::ProjectivePoint;
|
//! # type Group = p256_::NistP256;
|
||||||
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
||||||
//! # type Hash = sha2::Sha256;
|
//! # type Hash = sha2::Sha256;
|
||||||
//! use rand::rngs::OsRng;
|
//! use rand::rngs::OsRng;
|
||||||
@@ -246,11 +246,11 @@
|
|||||||
//!
|
//!
|
||||||
//! ```
|
//! ```
|
||||||
//! # #[cfg(feature = "ristretto255")]
|
//! # #[cfg(feature = "ristretto255")]
|
||||||
//! # type Group = curve25519_dalek::ristretto::RistrettoPoint;
|
//! # type Group = voprf::Ristretto255;
|
||||||
//! # #[cfg(feature = "ristretto255")]
|
//! # #[cfg(feature = "ristretto255")]
|
||||||
//! # type Hash = sha2::Sha512;
|
//! # type Hash = sha2::Sha512;
|
||||||
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
||||||
//! # type Group = p256_::ProjectivePoint;
|
//! # type Group = p256_::NistP256;
|
||||||
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
||||||
//! # type Hash = sha2::Sha256;
|
//! # type Hash = sha2::Sha256;
|
||||||
//! # use voprf::VerifiableClient;
|
//! # use voprf::VerifiableClient;
|
||||||
@@ -279,11 +279,11 @@
|
|||||||
//!
|
//!
|
||||||
//! ```
|
//! ```
|
||||||
//! # #[cfg(feature = "ristretto255")]
|
//! # #[cfg(feature = "ristretto255")]
|
||||||
//! # type Group = curve25519_dalek::ristretto::RistrettoPoint;
|
//! # type Group = voprf::Ristretto255;
|
||||||
//! # #[cfg(feature = "ristretto255")]
|
//! # #[cfg(feature = "ristretto255")]
|
||||||
//! # type Hash = sha2::Sha512;
|
//! # type Hash = sha2::Sha512;
|
||||||
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
||||||
//! # type Group = p256_::ProjectivePoint;
|
//! # type Group = p256_::NistP256;
|
||||||
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
||||||
//! # type Hash = sha2::Sha256;
|
//! # type Hash = sha2::Sha256;
|
||||||
//! # use voprf::VerifiableClient;
|
//! # use voprf::VerifiableClient;
|
||||||
@@ -336,11 +336,11 @@
|
|||||||
//!
|
//!
|
||||||
//! ```
|
//! ```
|
||||||
//! # #[cfg(feature = "ristretto255")]
|
//! # #[cfg(feature = "ristretto255")]
|
||||||
//! # type Group = curve25519_dalek::ristretto::RistrettoPoint;
|
//! # type Group = voprf::Ristretto255;
|
||||||
//! # #[cfg(feature = "ristretto255")]
|
//! # #[cfg(feature = "ristretto255")]
|
||||||
//! # type Hash = sha2::Sha512;
|
//! # type Hash = sha2::Sha512;
|
||||||
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
||||||
//! # type Group = p256_::ProjectivePoint;
|
//! # type Group = p256_::NistP256;
|
||||||
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
||||||
//! # type Hash = sha2::Sha256;
|
//! # type Hash = sha2::Sha256;
|
||||||
//! # use voprf::VerifiableClient;
|
//! # use voprf::VerifiableClient;
|
||||||
@@ -364,11 +364,11 @@
|
|||||||
//!
|
//!
|
||||||
//! ```
|
//! ```
|
||||||
//! # #[cfg(feature = "ristretto255")]
|
//! # #[cfg(feature = "ristretto255")]
|
||||||
//! # type Group = curve25519_dalek::ristretto::RistrettoPoint;
|
//! # type Group = voprf::Ristretto255;
|
||||||
//! # #[cfg(feature = "ristretto255")]
|
//! # #[cfg(feature = "ristretto255")]
|
||||||
//! # type Hash = sha2::Sha512;
|
//! # type Hash = sha2::Sha512;
|
||||||
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
||||||
//! # type Group = p256_::ProjectivePoint;
|
//! # type Group = p256_::NistP256;
|
||||||
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
||||||
//! # type Hash = sha2::Sha256;
|
//! # type Hash = sha2::Sha256;
|
||||||
//! # use voprf::{VerifiableServerBatchEvaluatePrepareResult, VerifiableServerBatchEvaluateFinishResult, VerifiableClient};
|
//! # use voprf::{VerifiableServerBatchEvaluatePrepareResult, VerifiableServerBatchEvaluateFinishResult, VerifiableClient};
|
||||||
@@ -407,11 +407,11 @@
|
|||||||
//! ```
|
//! ```
|
||||||
//! # #[cfg(feature = "alloc")] {
|
//! # #[cfg(feature = "alloc")] {
|
||||||
//! # #[cfg(feature = "ristretto255")]
|
//! # #[cfg(feature = "ristretto255")]
|
||||||
//! # type Group = curve25519_dalek::ristretto::RistrettoPoint;
|
//! # type Group = voprf::Ristretto255;
|
||||||
//! # #[cfg(feature = "ristretto255")]
|
//! # #[cfg(feature = "ristretto255")]
|
||||||
//! # type Hash = sha2::Sha512;
|
//! # type Hash = sha2::Sha512;
|
||||||
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
||||||
//! # type Group = p256_::ProjectivePoint;
|
//! # type Group = p256_::NistP256;
|
||||||
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
||||||
//! # type Hash = sha2::Sha256;
|
//! # type Hash = sha2::Sha256;
|
||||||
//! # use voprf::{VerifiableServerBatchEvaluateResult, VerifiableClient};
|
//! # use voprf::{VerifiableServerBatchEvaluateResult, VerifiableClient};
|
||||||
@@ -446,11 +446,11 @@
|
|||||||
//! ```
|
//! ```
|
||||||
//! # #[cfg(feature = "alloc")] {
|
//! # #[cfg(feature = "alloc")] {
|
||||||
//! # #[cfg(feature = "ristretto255")]
|
//! # #[cfg(feature = "ristretto255")]
|
||||||
//! # type Group = curve25519_dalek::ristretto::RistrettoPoint;
|
//! # type Group = voprf::Ristretto255;
|
||||||
//! # #[cfg(feature = "ristretto255")]
|
//! # #[cfg(feature = "ristretto255")]
|
||||||
//! # type Hash = sha2::Sha512;
|
//! # type Hash = sha2::Sha512;
|
||||||
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
||||||
//! # type Group = p256_::ProjectivePoint;
|
//! # type Group = p256_::NistP256;
|
||||||
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
|
||||||
//! # type Hash = sha2::Sha256;
|
//! # type Hash = sha2::Sha256;
|
||||||
//! # use voprf::{VerifiableServerBatchEvaluateResult, VerifiableClient};
|
//! # use voprf::{VerifiableServerBatchEvaluateResult, VerifiableClient};
|
||||||
@@ -507,9 +507,10 @@
|
|||||||
//! - The `alloc` feature requires Rusts [`alloc`] crate and enables batching
|
//! - The `alloc` feature requires Rusts [`alloc`] crate and enables batching
|
||||||
//! VOPRF evaluations.
|
//! VOPRF evaluations.
|
||||||
//!
|
//!
|
||||||
//! - The `p256` feature enables using p256 as the underlying group for the
|
//! - The `p256` feature enables using [`NistP256`](p256_::NistP256) as the
|
||||||
//! [Group] choice and increases the MSRV to 1.56. Note that this is currently
|
//! underlying group for the [Group] choice and increases the MSRV to 1.56.
|
||||||
//! an experimental feature ⚠️, and is not yet ready for production use.
|
//! 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
|
//! - The `serde` feature, enabled by default, provides convenience functions
|
||||||
//! for serializing and deserializing with [serde](https://serde.rs/).
|
//! 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
|
//! that need access to these raw values and are able to perform the necessary
|
||||||
//! validations on them (such as being valid group elements).
|
//! 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)
|
//! - The `ristretto255` feature enables using [`Ristretto255`] as the
|
||||||
//! and allow for selecting the corresponding backend for the curve arithmetic
|
//! underlying group for the [Group] choice. A backend feature, which are
|
||||||
//! used. The `ristretto255_u64` feature is included as the default. Other
|
//! re-exported from [curve25519-dalek] and allow for selecting the
|
||||||
//! features are mapped as `ristretto255_u32`, `ristretto255_fiat_u64` and
|
//! corresponding backend for the curve arithmetic used, has to be selected,
|
||||||
//! `ristretto255_fiat_u32`. Any `ristretto255_*` backend feature will enable
|
//! otherwise compilation will fail. The `ristretto255_u64` feature is
|
||||||
//! the `ristretto255` feature, which can be used too, but keep in mind that
|
//! included as the default. Other features are mapped as `ristretto255_u32`,
|
||||||
//! `curve25519-dalek` will fail to compile without a selected backend.
|
//! `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)
|
//! - The `ristretto255_simd` feature is re-exported from [curve25519-dalek] and
|
||||||
//! and enables parallel formulas, using either AVX2 or AVX512-IFMA. This will
|
//! enables parallel formulas, using either AVX2 or AVX512-IFMA. This will
|
||||||
//! automatically enable the `ristretto255_u64` feature and requires Rust
|
//! automatically enable the `ristretto255_u64` feature and requires Rust
|
||||||
//! nightly.
|
//! nightly.
|
||||||
|
//!
|
||||||
|
//! [curve25519-dalek]: (https://doc.dalek.rs/curve25519_dalek/index.html#backends-and-features)
|
||||||
|
|
||||||
#![deny(unsafe_code)]
|
#![deny(unsafe_code)]
|
||||||
#![no_std]
|
#![no_std]
|
||||||
@@ -557,12 +561,15 @@ mod tests;
|
|||||||
|
|
||||||
// Exports
|
// Exports
|
||||||
|
|
||||||
|
#[cfg(feature = "ristretto255")]
|
||||||
|
pub use group::Ristretto255;
|
||||||
|
|
||||||
pub use crate::error::{Error, Result};
|
pub use crate::error::{Error, Result};
|
||||||
pub use crate::group::Group;
|
pub use crate::group::Group;
|
||||||
#[cfg(feature = "alloc")]
|
#[cfg(feature = "alloc")]
|
||||||
pub use crate::voprf::VerifiableServerBatchEvaluateResult;
|
pub use crate::voprf::VerifiableServerBatchEvaluateResult;
|
||||||
pub use crate::voprf::{
|
pub use crate::voprf::{
|
||||||
BlindedElement, EvaluationElement, NonVerifiableClient, NonVerifiableClientBlindResult,
|
BlindedElement, EvaluationElement, Mode, NonVerifiableClient, NonVerifiableClientBlindResult,
|
||||||
NonVerifiableServer, NonVerifiableServerEvaluateResult, PreparedEvaluationElement,
|
NonVerifiableServer, NonVerifiableServerEvaluateResult, PreparedEvaluationElement,
|
||||||
PreparedTscalar, Proof, VerifiableClient, VerifiableClientBatchFinalizeResult,
|
PreparedTscalar, Proof, VerifiableClient, VerifiableClientBatchFinalizeResult,
|
||||||
VerifiableClientBlindResult, VerifiableServer, VerifiableServerBatchEvaluateFinishResult,
|
VerifiableClientBlindResult, VerifiableServer, VerifiableServerBatchEvaluateFinishResult,
|
||||||
|
|||||||
+17
-17
@@ -30,14 +30,14 @@ use crate::{
|
|||||||
impl<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> NonVerifiableClient<G, H> {
|
impl<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> NonVerifiableClient<G, H> {
|
||||||
/// Serialization into bytes
|
/// Serialization into bytes
|
||||||
pub fn serialize(&self) -> GenericArray<u8, G::ScalarLen> {
|
pub fn serialize(&self) -> GenericArray<u8, G::ScalarLen> {
|
||||||
G::scalar_as_bytes(self.blind)
|
G::serialize_scalar(self.blind)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Deserialization from bytes
|
/// Deserialization from bytes
|
||||||
pub fn deserialize(input: &[u8]) -> Result<Self> {
|
pub fn deserialize(input: &[u8]) -> Result<Self> {
|
||||||
let mut input = input.iter().copied();
|
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 {
|
Ok(Self {
|
||||||
blind,
|
blind,
|
||||||
@@ -53,15 +53,15 @@ impl<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> VerifiableClient<G,
|
|||||||
G::ScalarLen: Add<G::ElemLen>,
|
G::ScalarLen: Add<G::ElemLen>,
|
||||||
Sum<G::ScalarLen, G::ElemLen>: ArrayLength<u8>,
|
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
|
/// Deserialization from bytes
|
||||||
pub fn deserialize(input: &[u8]) -> Result<Self> {
|
pub fn deserialize(input: &[u8]) -> Result<Self> {
|
||||||
let mut input = input.iter().copied();
|
let mut input = input.iter().copied();
|
||||||
|
|
||||||
let blind = G::from_scalar_slice(&deserialize(&mut input)?)?;
|
let blind = G::deserialize_scalar(&deserialize(&mut input)?)?;
|
||||||
let blinded_element = G::from_element_slice(&deserialize(&mut input)?)?;
|
let blinded_element = G::deserialize_elem(&deserialize(&mut input)?)?;
|
||||||
|
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
blind,
|
blind,
|
||||||
@@ -74,14 +74,14 @@ impl<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> VerifiableClient<G,
|
|||||||
impl<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> NonVerifiableServer<G, H> {
|
impl<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> NonVerifiableServer<G, H> {
|
||||||
/// Serialization into bytes
|
/// Serialization into bytes
|
||||||
pub fn serialize(&self) -> GenericArray<u8, G::ScalarLen> {
|
pub fn serialize(&self) -> GenericArray<u8, G::ScalarLen> {
|
||||||
G::scalar_as_bytes(self.sk)
|
G::serialize_scalar(self.sk)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Deserialization from bytes
|
/// Deserialization from bytes
|
||||||
pub fn deserialize(input: &[u8]) -> Result<Self> {
|
pub fn deserialize(input: &[u8]) -> Result<Self> {
|
||||||
let mut input = input.iter().copied();
|
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 {
|
Ok(Self {
|
||||||
sk,
|
sk,
|
||||||
@@ -97,15 +97,15 @@ impl<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> VerifiableServer<G,
|
|||||||
G::ScalarLen: Add<G::ElemLen>,
|
G::ScalarLen: Add<G::ElemLen>,
|
||||||
Sum<G::ScalarLen, G::ElemLen>: ArrayLength<u8>,
|
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
|
/// Deserialization from bytes
|
||||||
pub fn deserialize(input: &[u8]) -> Result<Self> {
|
pub fn deserialize(input: &[u8]) -> Result<Self> {
|
||||||
let mut input = input.iter().copied();
|
let mut input = input.iter().copied();
|
||||||
|
|
||||||
let sk = G::from_scalar_slice(&deserialize(&mut input)?)?;
|
let sk = G::deserialize_scalar(&deserialize(&mut input)?)?;
|
||||||
let pk = G::from_element_slice(&deserialize(&mut input)?)?;
|
let pk = G::deserialize_elem(&deserialize(&mut input)?)?;
|
||||||
|
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
sk,
|
sk,
|
||||||
@@ -122,15 +122,15 @@ impl<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> Proof<G, H> {
|
|||||||
G::ScalarLen: Add<G::ScalarLen>,
|
G::ScalarLen: Add<G::ScalarLen>,
|
||||||
Sum<G::ScalarLen, G::ScalarLen>: ArrayLength<u8>,
|
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
|
/// Deserialization from bytes
|
||||||
pub fn deserialize(input: &[u8]) -> Result<Self> {
|
pub fn deserialize(input: &[u8]) -> Result<Self> {
|
||||||
let mut input = input.iter().copied();
|
let mut input = input.iter().copied();
|
||||||
|
|
||||||
let c_scalar = G::from_scalar_slice(&deserialize(&mut input)?)?;
|
let c_scalar = G::deserialize_scalar(&deserialize(&mut input)?)?;
|
||||||
let s_scalar = G::from_scalar_slice(&deserialize(&mut input)?)?;
|
let s_scalar = G::deserialize_scalar(&deserialize(&mut input)?)?;
|
||||||
|
|
||||||
Ok(Proof {
|
Ok(Proof {
|
||||||
c_scalar,
|
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> {
|
impl<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> BlindedElement<G, H> {
|
||||||
/// Serialization into bytes
|
/// Serialization into bytes
|
||||||
pub fn serialize(&self) -> GenericArray<u8, G::ElemLen> {
|
pub fn serialize(&self) -> GenericArray<u8, G::ElemLen> {
|
||||||
self.value.to_arr()
|
G::serialize_elem(self.value)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Deserialization from bytes
|
/// Deserialization from bytes
|
||||||
pub fn deserialize(input: &[u8]) -> Result<Self> {
|
pub fn deserialize(input: &[u8]) -> Result<Self> {
|
||||||
let mut input = input.iter().copied();
|
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 {
|
Ok(Self {
|
||||||
value,
|
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> {
|
impl<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> EvaluationElement<G, H> {
|
||||||
/// Serialization into bytes
|
/// Serialization into bytes
|
||||||
pub fn serialize(&self) -> GenericArray<u8, G::ElemLen> {
|
pub fn serialize(&self) -> GenericArray<u8, G::ElemLen> {
|
||||||
self.value.to_arr()
|
G::serialize_elem(self.value)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Deserialization from bytes
|
/// Deserialization from bytes
|
||||||
pub fn deserialize(input: &[u8]) -> Result<Self> {
|
pub fn deserialize(input: &[u8]) -> Result<Self> {
|
||||||
let mut input = input.iter().copied();
|
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 {
|
Ok(Self {
|
||||||
value,
|
value,
|
||||||
|
|||||||
@@ -90,9 +90,10 @@ fn test_vectors() -> Result<()> {
|
|||||||
|
|
||||||
#[cfg(feature = "ristretto255")]
|
#[cfg(feature = "ristretto255")]
|
||||||
{
|
{
|
||||||
use curve25519_dalek::ristretto::RistrettoPoint;
|
|
||||||
use sha2::Sha512;
|
use sha2::Sha512;
|
||||||
|
|
||||||
|
use crate::Ristretto255;
|
||||||
|
|
||||||
let ristretto_base_tvs = json_to_test_vectors!(
|
let ristretto_base_tvs = json_to_test_vectors!(
|
||||||
rfc,
|
rfc,
|
||||||
String::from("ristretto255, SHA-512"),
|
String::from("ristretto255, SHA-512"),
|
||||||
@@ -105,20 +106,20 @@ fn test_vectors() -> Result<()> {
|
|||||||
String::from("Verifiable")
|
String::from("Verifiable")
|
||||||
);
|
);
|
||||||
|
|
||||||
test_base_seed_to_key::<RistrettoPoint, Sha512>(&ristretto_base_tvs)?;
|
test_base_seed_to_key::<Ristretto255, Sha512>(&ristretto_base_tvs)?;
|
||||||
test_base_blind::<RistrettoPoint, Sha512>(&ristretto_base_tvs)?;
|
test_base_blind::<Ristretto255, Sha512>(&ristretto_base_tvs)?;
|
||||||
test_base_evaluate::<RistrettoPoint, Sha512>(&ristretto_base_tvs)?;
|
test_base_evaluate::<Ristretto255, Sha512>(&ristretto_base_tvs)?;
|
||||||
test_base_finalize::<RistrettoPoint, Sha512>(&ristretto_base_tvs)?;
|
test_base_finalize::<Ristretto255, Sha512>(&ristretto_base_tvs)?;
|
||||||
|
|
||||||
test_verifiable_seed_to_key::<RistrettoPoint, Sha512>(&ristretto_verifiable_tvs)?;
|
test_verifiable_seed_to_key::<Ristretto255, Sha512>(&ristretto_verifiable_tvs)?;
|
||||||
test_verifiable_blind::<RistrettoPoint, Sha512>(&ristretto_verifiable_tvs)?;
|
test_verifiable_blind::<Ristretto255, Sha512>(&ristretto_verifiable_tvs)?;
|
||||||
test_verifiable_evaluate::<RistrettoPoint, Sha512>(&ristretto_verifiable_tvs)?;
|
test_verifiable_evaluate::<Ristretto255, Sha512>(&ristretto_verifiable_tvs)?;
|
||||||
test_verifiable_finalize::<RistrettoPoint, Sha512>(&ristretto_verifiable_tvs)?;
|
test_verifiable_finalize::<Ristretto255, Sha512>(&ristretto_verifiable_tvs)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "p256")]
|
#[cfg(feature = "p256")]
|
||||||
{
|
{
|
||||||
use p256_::ProjectivePoint;
|
use p256_::NistP256;
|
||||||
use sha2::Sha256;
|
use sha2::Sha256;
|
||||||
|
|
||||||
let p256_base_tvs =
|
let p256_base_tvs =
|
||||||
@@ -130,15 +131,15 @@ fn test_vectors() -> Result<()> {
|
|||||||
String::from("Verifiable")
|
String::from("Verifiable")
|
||||||
);
|
);
|
||||||
|
|
||||||
test_base_seed_to_key::<ProjectivePoint, Sha256>(&p256_base_tvs)?;
|
test_base_seed_to_key::<NistP256, Sha256>(&p256_base_tvs)?;
|
||||||
test_base_blind::<ProjectivePoint, Sha256>(&p256_base_tvs)?;
|
test_base_blind::<NistP256, Sha256>(&p256_base_tvs)?;
|
||||||
test_base_evaluate::<ProjectivePoint, Sha256>(&p256_base_tvs)?;
|
test_base_evaluate::<NistP256, Sha256>(&p256_base_tvs)?;
|
||||||
test_base_finalize::<ProjectivePoint, Sha256>(&p256_base_tvs)?;
|
test_base_finalize::<NistP256, Sha256>(&p256_base_tvs)?;
|
||||||
|
|
||||||
test_verifiable_seed_to_key::<ProjectivePoint, Sha256>(&p256_verifiable_tvs)?;
|
test_verifiable_seed_to_key::<NistP256, Sha256>(&p256_verifiable_tvs)?;
|
||||||
test_verifiable_blind::<ProjectivePoint, Sha256>(&p256_verifiable_tvs)?;
|
test_verifiable_blind::<NistP256, Sha256>(&p256_verifiable_tvs)?;
|
||||||
test_verifiable_evaluate::<ProjectivePoint, Sha256>(&p256_verifiable_tvs)?;
|
test_verifiable_evaluate::<NistP256, Sha256>(&p256_verifiable_tvs)?;
|
||||||
test_verifiable_finalize::<ProjectivePoint, Sha256>(&p256_verifiable_tvs)?;
|
test_verifiable_finalize::<NistP256, Sha256>(&p256_verifiable_tvs)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -152,7 +153,7 @@ fn test_base_seed_to_key<G: Group, H: BlockSizeUser + Digest + FixedOutputReset>
|
|||||||
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
¶meters.sksm,
|
¶meters.sksm,
|
||||||
&G::scalar_as_bytes(server.get_private_key()).to_vec()
|
&G::serialize_scalar(server.get_private_key()).to_vec()
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -166,9 +167,12 @@ fn test_verifiable_seed_to_key<G: Group, H: BlockSizeUser + Digest + FixedOutput
|
|||||||
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
¶meters.sksm,
|
¶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(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -180,7 +184,7 @@ fn test_base_blind<G: Group, H: BlockSizeUser + Digest + FixedOutputReset>(
|
|||||||
for parameters in tvs {
|
for parameters in tvs {
|
||||||
for i in 0..parameters.input.len() {
|
for i in 0..parameters.input.len() {
|
||||||
let blind =
|
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(
|
let client_result = NonVerifiableClient::<G, H>::deterministic_blind_unchecked(
|
||||||
¶meters.input[i],
|
¶meters.input[i],
|
||||||
blind,
|
blind,
|
||||||
@@ -188,7 +192,7 @@ fn test_base_blind<G: Group, H: BlockSizeUser + Digest + FixedOutputReset>(
|
|||||||
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
¶meters.blind[i],
|
¶meters.blind[i],
|
||||||
&G::scalar_as_bytes(client_result.state.blind).to_vec()
|
&G::serialize_scalar(client_result.state.blind).to_vec()
|
||||||
);
|
);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
parameters.blinded_element[i].as_slice(),
|
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 parameters in tvs {
|
||||||
for i in 0..parameters.input.len() {
|
for i in 0..parameters.input.len() {
|
||||||
let blind =
|
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(
|
let client_blind_result = VerifiableClient::<G, H>::deterministic_blind_unchecked(
|
||||||
¶meters.input[i],
|
¶meters.input[i],
|
||||||
blind,
|
blind,
|
||||||
@@ -214,7 +218,7 @@ fn test_verifiable_blind<G: Group, H: BlockSizeUser + Digest + FixedOutputReset>
|
|||||||
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
¶meters.blind[i],
|
¶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!(
|
assert_eq!(
|
||||||
parameters.blinded_element[i].as_slice(),
|
parameters.blinded_element[i].as_slice(),
|
||||||
@@ -295,7 +299,7 @@ fn test_base_finalize<G: Group, H: BlockSizeUser + Digest + FixedOutputReset>(
|
|||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
for parameters in tvs {
|
for parameters in tvs {
|
||||||
for i in 0..parameters.input.len() {
|
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]),
|
&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![];
|
let mut clients = vec![];
|
||||||
for i in 0..parameters.input.len() {
|
for i in 0..parameters.input.len() {
|
||||||
let client = VerifiableClient::<G, H>::from_blind_and_element(
|
let client = VerifiableClient::<G, H>::from_blind_and_element(
|
||||||
G::from_scalar_slice(&GenericArray::clone_from_slice(¶meters.blind[i]))?,
|
G::deserialize_scalar(&GenericArray::clone_from_slice(¶meters.blind[i]))?,
|
||||||
G::from_element_slice(&GenericArray::clone_from_slice(
|
G::deserialize_elem(&GenericArray::clone_from_slice(
|
||||||
¶meters.blinded_element[i],
|
¶meters.blinded_element[i],
|
||||||
))?,
|
))?,
|
||||||
);
|
);
|
||||||
@@ -337,7 +341,7 @@ fn test_verifiable_finalize<G: Group, H: BlockSizeUser + Digest + FixedOutputRes
|
|||||||
&clients,
|
&clients,
|
||||||
&messages,
|
&messages,
|
||||||
&Proof::deserialize(¶meters.proof)?,
|
&Proof::deserialize(¶meters.proof)?,
|
||||||
G::from_element_slice(GenericArray::from_slice(¶meters.pksm))?,
|
G::deserialize_elem(GenericArray::from_slice(¶meters.pksm))?,
|
||||||
Some(¶meters.info),
|
Some(¶meters.info),
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
|
|||||||
@@ -8,7 +8,7 @@
|
|||||||
//! The VOPRF test vectors taken from:
|
//! The VOPRF test vectors taken from:
|
||||||
//! https://github.com/cfrg/draft-irtf-cfrg-voprf/blob/master/draft-irtf-cfrg-voprf.md
|
//! 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)
|
## OPRF(ristretto255, SHA-512)
|
||||||
|
|
||||||
### Base Mode
|
### Base Mode
|
||||||
|
|||||||
+12
-117
@@ -7,149 +7,44 @@
|
|||||||
|
|
||||||
//! Helper functions
|
//! 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 generic_array::{ArrayLength, GenericArray};
|
||||||
|
|
||||||
use crate::{Error, Result};
|
use crate::{Error, Result};
|
||||||
|
|
||||||
// Corresponds to the I2OSP() function from RFC8017
|
pub(crate) fn i2osp_2(input: usize) -> Result<GenericArray<u8, U2>> {
|
||||||
pub(crate) fn i2osp<L: ArrayLength<u8>>(input: usize) -> Result<GenericArray<u8, L>> {
|
u16::try_from(input)
|
||||||
const SIZEOF_USIZE: usize = core::mem::size_of::<usize>();
|
.map(|input| input.to_be_bytes().into())
|
||||||
|
.map_err(|_| Error::SerializationError)
|
||||||
// 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)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Computes `I2OSP(len(input), max_bytes) || input` and helps hold output
|
pub(crate) fn i2osp_2_array<L: ArrayLength<u8> + IsLess<U256>>(
|
||||||
/// without allocation.
|
_: GenericArray<u8, L>,
|
||||||
pub(crate) struct Serialize<'a, L1: ArrayLength<u8>, L2: ArrayLength<u8> = U0> {
|
) -> GenericArray<u8, U2> {
|
||||||
octet: GenericArray<u8, L1>,
|
L::U16.to_be_bytes().into()
|
||||||
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)?));
|
|
||||||
)+
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod unit_tests {
|
mod unit_tests {
|
||||||
use generic_array::typenum::{U1, U2};
|
|
||||||
use proptest::collection::vec;
|
use proptest::collection::vec;
|
||||||
use proptest::prelude::*;
|
use proptest::prelude::*;
|
||||||
|
|
||||||
use super::*;
|
|
||||||
use crate::{
|
use crate::{
|
||||||
BlindedElement, EvaluationElement, NonVerifiableClient, NonVerifiableServer, Proof,
|
BlindedElement, EvaluationElement, NonVerifiableClient, NonVerifiableServer, Proof,
|
||||||
VerifiableClient, VerifiableServer,
|
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 {
|
macro_rules! test_deserialize {
|
||||||
($item:ident, $bytes:ident) => {
|
($item:ident, $bytes:ident) => {
|
||||||
#[cfg(feature = "ristretto255")]
|
#[cfg(feature = "ristretto255")]
|
||||||
{
|
{
|
||||||
let _ =
|
let _ = $item::<crate::Ristretto255, sha2::Sha512>::deserialize(&$bytes[..]);
|
||||||
$item::<curve25519_dalek::ristretto::RistrettoPoint, sha2::Sha512>::deserialize(
|
|
||||||
&$bytes[..],
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
#[cfg(feature = "p256")]
|
#[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")]
|
#[cfg(feature = "alloc")]
|
||||||
use alloc::vec::Vec;
|
use alloc::vec::Vec;
|
||||||
use core::convert::TryInto;
|
use core::convert::{TryFrom, TryInto};
|
||||||
use core::iter::{self, Map, Repeat, Zip};
|
use core::iter::{self, Map, Repeat, Zip};
|
||||||
use core::marker::PhantomData;
|
use core::marker::PhantomData;
|
||||||
|
|
||||||
@@ -17,12 +17,12 @@ use derive_where::DeriveWhere;
|
|||||||
use digest::core_api::BlockSizeUser;
|
use digest::core_api::BlockSizeUser;
|
||||||
use digest::{Digest, FixedOutputReset, Output};
|
use digest::{Digest, FixedOutputReset, Output};
|
||||||
use generic_array::sequence::Concat;
|
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 generic_array::GenericArray;
|
||||||
use rand_core::{CryptoRng, RngCore};
|
use rand_core::{CryptoRng, RngCore};
|
||||||
use subtle::ConstantTimeEq;
|
use subtle::ConstantTimeEq;
|
||||||
|
|
||||||
use crate::util::{i2osp, Serialize};
|
use crate::util::{i2osp_2, i2osp_2_array};
|
||||||
use crate::{Error, Group, Result};
|
use crate::{Error, Group, Result};
|
||||||
|
|
||||||
///////////////
|
///////////////
|
||||||
@@ -30,20 +30,31 @@ use crate::{Error, Group, Result};
|
|||||||
// ========= //
|
// ========= //
|
||||||
///////////////
|
///////////////
|
||||||
|
|
||||||
static STR_HASH_TO_SCALAR: [u8; 13] = *b"HashToScalar-";
|
const STR_FINALIZE: [u8; 9] = *b"Finalize-";
|
||||||
static STR_HASH_TO_GROUP: [u8; 12] = *b"HashToGroup-";
|
const STR_SEED: [u8; 5] = *b"Seed-";
|
||||||
static STR_FINALIZE: [u8; 9] = *b"Finalize-";
|
const STR_CONTEXT: [u8; 8] = *b"Context-";
|
||||||
static STR_SEED: [u8; 5] = *b"Seed-";
|
const STR_COMPOSITE: [u8; 10] = *b"Composite-";
|
||||||
static STR_CONTEXT: [u8; 8] = *b"Context-";
|
const STR_CHALLENGE: [u8; 10] = *b"Challenge-";
|
||||||
static STR_COMPOSITE: [u8; 10] = *b"Composite-";
|
const STR_VOPRF: [u8; 8] = *b"VOPRF08-";
|
||||||
static STR_CHALLENGE: [u8; 10] = *b"Challenge-";
|
|
||||||
static 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)]
|
#[derive(Clone, Copy)]
|
||||||
enum Mode {
|
pub enum Mode {
|
||||||
Base = 0,
|
/// Non-verifiable mode.
|
||||||
Verifiable = 1,
|
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.
|
/// that the OPRF outputs can be checked against a server public key.
|
||||||
#[derive(DeriveWhere)]
|
#[derive(DeriveWhere)]
|
||||||
#[derive_where(Clone, Zeroize(drop))]
|
#[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(
|
#[cfg_attr(
|
||||||
feature = "serde",
|
feature = "serde",
|
||||||
derive(serde::Deserialize, serde::Serialize),
|
derive(serde::Deserialize, serde::Serialize),
|
||||||
serde(bound(
|
serde(bound(
|
||||||
deserialize = "G::Scalar: serde::Deserialize<'de>, G: serde::Deserialize<'de>",
|
deserialize = "G::Scalar: serde::Deserialize<'de>, G::Elem: serde::Deserialize<'de>",
|
||||||
serialize = "G::Scalar: serde::Serialize, G: serde::Serialize"
|
serialize = "G::Scalar: serde::Serialize, G::Elem: serde::Serialize"
|
||||||
))
|
))
|
||||||
)]
|
)]
|
||||||
pub struct VerifiableClient<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> {
|
pub struct VerifiableClient<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> {
|
||||||
pub(crate) blind: G::Scalar,
|
pub(crate) blind: G::Scalar,
|
||||||
pub(crate) blinded_element: G,
|
pub(crate) blinded_element: G::Elem,
|
||||||
#[derive_where(skip(Zeroize))]
|
#[derive_where(skip(Zeroize))]
|
||||||
pub(crate) hash: PhantomData<H>,
|
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.
|
/// that the OPRF outputs can be checked against a server public key.
|
||||||
#[derive(DeriveWhere)]
|
#[derive(DeriveWhere)]
|
||||||
#[derive_where(Clone, Zeroize(drop))]
|
#[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(
|
#[cfg_attr(
|
||||||
feature = "serde",
|
feature = "serde",
|
||||||
derive(serde::Deserialize, serde::Serialize),
|
derive(serde::Deserialize, serde::Serialize),
|
||||||
serde(bound(
|
serde(bound(
|
||||||
deserialize = "G::Scalar: serde::Deserialize<'de>, G: serde::Deserialize<'de>",
|
deserialize = "G::Scalar: serde::Deserialize<'de>, G::Elem: serde::Deserialize<'de>",
|
||||||
serialize = "G::Scalar: serde::Serialize, G: serde::Serialize"
|
serialize = "G::Scalar: serde::Serialize, G::Elem: serde::Serialize"
|
||||||
))
|
))
|
||||||
)]
|
)]
|
||||||
pub struct VerifiableServer<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> {
|
pub struct VerifiableServer<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> {
|
||||||
pub(crate) sk: G::Scalar,
|
pub(crate) sk: G::Scalar,
|
||||||
pub(crate) pk: G,
|
pub(crate) pk: G::Elem,
|
||||||
#[derive_where(skip(Zeroize))]
|
#[derive_where(skip(Zeroize))]
|
||||||
pub(crate) hash: PhantomData<H>,
|
pub(crate) hash: PhantomData<H>,
|
||||||
}
|
}
|
||||||
@@ -153,17 +164,17 @@ pub struct Proof<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> {
|
|||||||
/// server (either verifiable or not).
|
/// server (either verifiable or not).
|
||||||
#[derive(DeriveWhere)]
|
#[derive(DeriveWhere)]
|
||||||
#[derive_where(Clone, Zeroize(drop))]
|
#[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(
|
#[cfg_attr(
|
||||||
feature = "serde",
|
feature = "serde",
|
||||||
derive(serde::Deserialize, serde::Serialize),
|
derive(serde::Deserialize, serde::Serialize),
|
||||||
serde(bound(
|
serde(bound(
|
||||||
deserialize = "G: serde::Deserialize<'de>",
|
deserialize = "G::Elem: serde::Deserialize<'de>",
|
||||||
serialize = "G: serde::Serialize"
|
serialize = "G::Elem: serde::Serialize"
|
||||||
))
|
))
|
||||||
)]
|
)]
|
||||||
pub struct BlindedElement<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> {
|
pub struct BlindedElement<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> {
|
||||||
pub(crate) value: G,
|
pub(crate) value: G::Elem,
|
||||||
#[derive_where(skip(Zeroize))]
|
#[derive_where(skip(Zeroize))]
|
||||||
pub(crate) hash: PhantomData<H>,
|
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).
|
/// verifiable or not) to a server (either verifiable or not).
|
||||||
#[derive(DeriveWhere)]
|
#[derive(DeriveWhere)]
|
||||||
#[derive_where(Clone, Zeroize(drop))]
|
#[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(
|
#[cfg_attr(
|
||||||
feature = "serde",
|
feature = "serde",
|
||||||
derive(serde::Deserialize, serde::Serialize),
|
derive(serde::Deserialize, serde::Serialize),
|
||||||
serde(bound(
|
serde(bound(
|
||||||
deserialize = "G: serde::Deserialize<'de>",
|
deserialize = "G::Elem: serde::Deserialize<'de>",
|
||||||
serialize = "G: serde::Serialize"
|
serialize = "G::Elem: serde::Serialize"
|
||||||
))
|
))
|
||||||
)]
|
)]
|
||||||
pub struct EvaluationElement<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> {
|
pub struct EvaluationElement<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> {
|
||||||
pub(crate) value: G,
|
pub(crate) value: G::Elem,
|
||||||
#[derive_where(skip(Zeroize))]
|
#[derive_where(skip(Zeroize))]
|
||||||
pub(crate) hash: PhantomData<H>,
|
pub(crate) hash: PhantomData<H>,
|
||||||
}
|
}
|
||||||
@@ -246,7 +257,7 @@ impl<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> NonVerifiableClient
|
|||||||
evaluation_element: &EvaluationElement<G, H>,
|
evaluation_element: &EvaluationElement<G, H>,
|
||||||
metadata: Option<&[u8]>,
|
metadata: Option<&[u8]>,
|
||||||
) -> Result<Output<H>> {
|
) -> 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, _, _>(
|
let mut outputs = finalize_after_unblind::<G, H, _, _>(
|
||||||
Some((input, unblinded_element)).into_iter(),
|
Some((input, unblinded_element)).into_iter(),
|
||||||
metadata.unwrap_or_default(),
|
metadata.unwrap_or_default(),
|
||||||
@@ -328,7 +339,7 @@ impl<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> VerifiableClient<G,
|
|||||||
input: &[u8],
|
input: &[u8],
|
||||||
evaluation_element: &EvaluationElement<G, H>,
|
evaluation_element: &EvaluationElement<G, H>,
|
||||||
proof: &Proof<G, H>,
|
proof: &Proof<G, H>,
|
||||||
pk: G,
|
pk: G::Elem,
|
||||||
metadata: Option<&[u8]>,
|
metadata: Option<&[u8]>,
|
||||||
) -> Result<Output<H>> {
|
) -> Result<Output<H>> {
|
||||||
// `core::array::from_ref` needs a MSRV of 1.53
|
// `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,
|
clients: &'a IC,
|
||||||
messages: &'a IM,
|
messages: &'a IM,
|
||||||
proof: &Proof<G, H>,
|
proof: &Proof<G, H>,
|
||||||
pk: G,
|
pk: G::Elem,
|
||||||
metadata: Option<&'a [u8]>,
|
metadata: Option<&'a [u8]>,
|
||||||
) -> Result<VerifiableClientBatchFinalizeResult<'a, G, H, I, II, IC, IM>>
|
) -> Result<VerifiableClientBatchFinalizeResult<'a, G, H, I, II, IC, IM>>
|
||||||
where
|
where
|
||||||
@@ -379,7 +390,7 @@ impl<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> VerifiableClient<G,
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
/// Only used for test functions
|
/// 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 {
|
Self {
|
||||||
blind,
|
blind,
|
||||||
blinded_element,
|
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
|
/// Produces a new instance of a [NonVerifiableServer] using a supplied set
|
||||||
/// of bytes to represent the server's private key
|
/// of bytes to represent the server's private key
|
||||||
pub fn new_with_key(private_key_bytes: &[u8]) -> Result<Self> {
|
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 {
|
Ok(Self {
|
||||||
sk,
|
sk,
|
||||||
hash: PhantomData,
|
hash: PhantomData,
|
||||||
@@ -417,9 +428,7 @@ impl<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> NonVerifiableServer
|
|||||||
///
|
///
|
||||||
/// Corresponds to DeriveKeyPair() function from the VOPRF specification.
|
/// Corresponds to DeriveKeyPair() function from the VOPRF specification.
|
||||||
pub fn new_from_seed(seed: &[u8]) -> Result<Self> {
|
pub fn new_from_seed(seed: &[u8]) -> Result<Self> {
|
||||||
let dst =
|
let sk = G::hash_to_scalar::<H>(&[seed], Mode::Base)?;
|
||||||
GenericArray::from(STR_HASH_TO_SCALAR).concat(get_context_string::<G>(Mode::Base)?);
|
|
||||||
let sk = G::hash_to_scalar::<H, _, _>(Some(seed), dst)?;
|
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
sk,
|
sk,
|
||||||
hash: PhantomData,
|
hash: PhantomData,
|
||||||
@@ -440,20 +449,27 @@ impl<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> NonVerifiableServer
|
|||||||
blinded_element: &BlindedElement<G, H>,
|
blinded_element: &BlindedElement<G, H>,
|
||||||
metadata: Option<&[u8]>,
|
metadata: Option<&[u8]>,
|
||||||
) -> Result<NonVerifiableServerEvaluateResult<G, H>> {
|
) -> Result<NonVerifiableServerEvaluateResult<G, H>> {
|
||||||
chain!(
|
// https://www.ietf.org/archive/id/draft-irtf-cfrg-voprf-08.html#section-3.3.1.1-1
|
||||||
context,
|
|
||||||
STR_CONTEXT => |x| Some(x.as_ref()),
|
let context_string = get_context_string::<G>(Mode::Base);
|
||||||
get_context_string::<G>(Mode::Base)? => |x| Some(x.as_slice()),
|
let metadata = metadata.unwrap_or_default();
|
||||||
Serialize::<U2>::from(metadata.unwrap_or_default())?,
|
|
||||||
);
|
// context = "Context-" || contextString || I2OSP(len(info), 2) || info
|
||||||
let dst =
|
let context = GenericArray::from(STR_CONTEXT)
|
||||||
GenericArray::from(STR_HASH_TO_SCALAR).concat(get_context_string::<G>(Mode::Base)?);
|
.concat(context_string)
|
||||||
let m = G::hash_to_scalar::<H, _, _>(context, dst)?;
|
.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 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 {
|
Ok(NonVerifiableServerEvaluateResult {
|
||||||
message: EvaluationElement {
|
message: EvaluationElement {
|
||||||
value: evaluation_element,
|
value: z,
|
||||||
hash: PhantomData,
|
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
|
/// Produces a new instance of a [VerifiableServer] using a supplied set of
|
||||||
/// bytes to represent the server's private key
|
/// bytes to represent the server's private key
|
||||||
pub fn new_with_key(key: &[u8]) -> Result<Self> {
|
pub fn new_with_key(key: &[u8]) -> Result<Self> {
|
||||||
let sk = G::from_scalar_slice(key)?;
|
let sk = G::deserialize_scalar(key.into())?;
|
||||||
let pk = G::base_point() * &sk;
|
let pk = G::base_elem() * &sk;
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
sk,
|
sk,
|
||||||
pk,
|
pk,
|
||||||
@@ -485,10 +501,8 @@ impl<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> VerifiableServer<G,
|
|||||||
///
|
///
|
||||||
/// Corresponds to DeriveKeyPair() function from the VOPRF specification.
|
/// Corresponds to DeriveKeyPair() function from the VOPRF specification.
|
||||||
pub fn new_from_seed(seed: &[u8]) -> Result<Self> {
|
pub fn new_from_seed(seed: &[u8]) -> Result<Self> {
|
||||||
let dst = GenericArray::from(STR_HASH_TO_SCALAR)
|
let sk = G::hash_to_scalar::<H>(&[seed], Mode::Verifiable)?;
|
||||||
.concat(get_context_string::<G>(Mode::Verifiable)?);
|
let pk = G::base_elem() * &sk;
|
||||||
let sk = G::hash_to_scalar::<H, _, _>(Some(seed), dst)?;
|
|
||||||
let pk = G::base_point() * &sk;
|
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
sk,
|
sk,
|
||||||
pk,
|
pk,
|
||||||
@@ -579,19 +593,23 @@ impl<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> VerifiableServer<G,
|
|||||||
blinded_elements: I,
|
blinded_elements: I,
|
||||||
metadata: Option<&[u8]>,
|
metadata: Option<&[u8]>,
|
||||||
) -> Result<VerifiableServerBatchEvaluatePrepareResult<'a, G, H, I>> {
|
) -> Result<VerifiableServerBatchEvaluatePrepareResult<'a, G, H, I>> {
|
||||||
chain!(context,
|
// https://www.ietf.org/archive/id/draft-irtf-cfrg-voprf-08.html#section-3.3.2.1-1
|
||||||
STR_CONTEXT => |x| Some(x.as_ref()),
|
|
||||||
get_context_string::<G>(Mode::Verifiable)? => |x| Some(x.as_slice()),
|
let context_string = get_context_string::<G>(Mode::Verifiable);
|
||||||
Serialize::<U2>::from(metadata.unwrap_or_default())?,
|
let metadata = metadata.unwrap_or_default();
|
||||||
);
|
|
||||||
let dst = GenericArray::from(STR_HASH_TO_SCALAR)
|
// context = "Context-" || contextString || I2OSP(len(info), 2) || info
|
||||||
.concat(get_context_string::<G>(Mode::Verifiable)?);
|
let context = GenericArray::from(STR_CONTEXT)
|
||||||
let m = G::hash_to_scalar::<H, _, _>(context, dst)?;
|
.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 t = self.sk + &m;
|
||||||
let evaluation_elements = blinded_elements
|
let evaluation_elements = blinded_elements
|
||||||
// To make a return type possible, we have to convert to a `fn` pointer, which isn't
|
// To make a return type possible, we have to convert to a `fn` pointer, which isn't
|
||||||
// possible if we `move` from context.
|
// 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)| {
|
.map(<fn((&BlindedElement<G, H>, _)) -> _>::from(|(x, t)| {
|
||||||
PreparedEvaluationElement(EvaluationElement {
|
PreparedEvaluationElement(EvaluationElement {
|
||||||
value: x.value * &t,
|
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: IntoIterator<Item = &'b PreparedEvaluationElement<G, H>>,
|
||||||
<&'b IE as IntoIterator>::IntoIter: ExactSizeIterator,
|
<&'b IE as IntoIterator>::IntoIter: ExactSizeIterator,
|
||||||
{
|
{
|
||||||
let g = G::base_point();
|
let g = G::base_elem();
|
||||||
let u = g * t;
|
let u = g * t;
|
||||||
|
|
||||||
let proof = generate_proof(
|
let proof = generate_proof(
|
||||||
@@ -647,7 +665,7 @@ impl<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> VerifiableServer<G,
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Retrieves the server's public key
|
/// Retrieves the server's public key
|
||||||
pub fn get_public_key(&self) -> G {
|
pub fn get_public_key(&self) -> G::Elem {
|
||||||
self.pk
|
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
|
/// This should be used with caution, since it does not perform any checks
|
||||||
/// on the validity of the value itself!
|
/// 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 {
|
Self {
|
||||||
value,
|
value,
|
||||||
hash: PhantomData,
|
hash: PhantomData,
|
||||||
@@ -792,7 +810,7 @@ impl<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> BlindedElement<G, H
|
|||||||
|
|
||||||
#[cfg(feature = "danger")]
|
#[cfg(feature = "danger")]
|
||||||
/// Exposes the internal value
|
/// Exposes the internal value
|
||||||
pub fn value(&self) -> G {
|
pub fn value(&self) -> G::Elem {
|
||||||
self.value
|
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
|
/// This should be used with caution, since it does not perform any checks
|
||||||
/// on the validity of the value itself!
|
/// 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 {
|
Self {
|
||||||
value,
|
value,
|
||||||
hash: PhantomData,
|
hash: PhantomData,
|
||||||
@@ -822,7 +840,7 @@ impl<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> EvaluationElement<G
|
|||||||
|
|
||||||
#[cfg(feature = "danger")]
|
#[cfg(feature = "danger")]
|
||||||
/// Exposes the internal value
|
/// Exposes the internal value
|
||||||
pub fn value(&self) -> G {
|
pub fn value(&self) -> G::Elem {
|
||||||
self.value
|
self.value
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -832,9 +850,9 @@ fn blind<G: Group, H: BlockSizeUser + Digest + FixedOutputReset, R: RngCore + Cr
|
|||||||
input: &[u8],
|
input: &[u8],
|
||||||
blinding_factor_rng: &mut R,
|
blinding_factor_rng: &mut R,
|
||||||
mode: Mode,
|
mode: Mode,
|
||||||
) -> Result<(G::Scalar, G)> {
|
) -> Result<(G::Scalar, G::Elem)> {
|
||||||
// Choose a random scalar that must be non-zero
|
// 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)?;
|
let blinded_element = deterministic_blind_unchecked::<G, H>(input, &blind, mode)?;
|
||||||
Ok((blind, blinded_element))
|
Ok((blind, blinded_element))
|
||||||
}
|
}
|
||||||
@@ -846,9 +864,8 @@ fn deterministic_blind_unchecked<G: Group, H: BlockSizeUser + Digest + FixedOutp
|
|||||||
input: &[u8],
|
input: &[u8],
|
||||||
blind: &G::Scalar,
|
blind: &G::Scalar,
|
||||||
mode: Mode,
|
mode: Mode,
|
||||||
) -> Result<G> {
|
) -> Result<G::Elem> {
|
||||||
let dst = GenericArray::from(STR_HASH_TO_GROUP).concat(get_context_string::<G>(mode)?);
|
let hashed_point = G::hash_to_curve::<H>(&[input], mode)?;
|
||||||
let hashed_point = G::hash_to_curve::<H, _>(input, dst)?;
|
|
||||||
Ok(hashed_point * blind)
|
Ok(hashed_point * blind)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -860,7 +877,7 @@ type VerifiableUnblindResult<'a, G, H, IC, IM> = Map<
|
|||||||
>,
|
>,
|
||||||
<&'a IM as IntoIterator>::IntoIter,
|
<&'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<
|
fn verifiable_unblind<
|
||||||
@@ -872,7 +889,7 @@ fn verifiable_unblind<
|
|||||||
>(
|
>(
|
||||||
clients: &'a IC,
|
clients: &'a IC,
|
||||||
messages: &'a IM,
|
messages: &'a IM,
|
||||||
pk: G,
|
pk: G::Elem,
|
||||||
proof: &Proof<G, H>,
|
proof: &Proof<G, H>,
|
||||||
info: &[u8],
|
info: &[u8],
|
||||||
) -> Result<VerifiableUnblindResult<'a, G, H, IC, IM>>
|
) -> Result<VerifiableUnblindResult<'a, G, H, IC, IM>>
|
||||||
@@ -882,17 +899,19 @@ where
|
|||||||
&'a IM: 'a + IntoIterator<Item = &'a EvaluationElement<G, H>>,
|
&'a IM: 'a + IntoIterator<Item = &'a EvaluationElement<G, H>>,
|
||||||
<&'a IM as IntoIterator>::IntoIter: ExactSizeIterator,
|
<&'a IM as IntoIterator>::IntoIter: ExactSizeIterator,
|
||||||
{
|
{
|
||||||
chain!(context,
|
// https://www.ietf.org/archive/id/draft-irtf-cfrg-voprf-08.html#section-3.3.4.2-2
|
||||||
STR_CONTEXT => |x| Some(x.as_ref()),
|
|
||||||
get_context_string::<G>(Mode::Verifiable)? => |x| Some(x.as_slice()),
|
|
||||||
Serialize::<U2>::from(info)?,
|
|
||||||
);
|
|
||||||
|
|
||||||
let dst =
|
let context_string = get_context_string::<G>(Mode::Verifiable);
|
||||||
GenericArray::from(STR_HASH_TO_SCALAR).concat(get_context_string::<G>(Mode::Verifiable)?);
|
|
||||||
let m = G::hash_to_scalar::<H, _, _>(context, dst)?;
|
|
||||||
|
|
||||||
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 t = g * &m;
|
||||||
let u = t + &pk;
|
let u = t + &pk;
|
||||||
|
|
||||||
@@ -910,7 +929,7 @@ where
|
|||||||
|
|
||||||
Ok(blinds
|
Ok(blinds
|
||||||
.zip(messages.into_iter())
|
.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)]
|
#[allow(clippy::many_single_char_names)]
|
||||||
@@ -921,33 +940,58 @@ fn generate_proof<
|
|||||||
>(
|
>(
|
||||||
rng: &mut R,
|
rng: &mut R,
|
||||||
k: G::Scalar,
|
k: G::Scalar,
|
||||||
a: G,
|
a: G::Elem,
|
||||||
b: G,
|
b: G::Elem,
|
||||||
cs: impl Iterator<Item = EvaluationElement<G, H>> + ExactSizeIterator,
|
cs: impl Iterator<Item = EvaluationElement<G, H>> + ExactSizeIterator,
|
||||||
ds: impl Iterator<Item = BlindedElement<G, H>> + ExactSizeIterator,
|
ds: impl Iterator<Item = BlindedElement<G, H>> + ExactSizeIterator,
|
||||||
) -> Result<Proof<G, H>> {
|
) -> 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 (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 t2 = a * &r;
|
||||||
let t3 = m * &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 =
|
let challenge_dst =
|
||||||
GenericArray::from(STR_CHALLENGE).concat(get_context_string::<G>(Mode::Verifiable)?);
|
GenericArray::from(STR_CHALLENGE).concat(get_context_string::<G>(Mode::Verifiable));
|
||||||
chain!(
|
let challenge_dst_len = i2osp_2_array(challenge_dst);
|
||||||
h2_input,
|
// h2Input = I2OSP(len(Bm), 2) || Bm ||
|
||||||
Serialize::<U2, _>::from_owned(b.to_arr())?,
|
// I2OSP(len(a0), 2) || a0 ||
|
||||||
Serialize::<U2, _>::from_owned(m.to_arr())?,
|
// I2OSP(len(a1), 2) || a1 ||
|
||||||
Serialize::<U2, _>::from_owned(z.to_arr())?,
|
// I2OSP(len(a2), 2) || a2 ||
|
||||||
Serialize::<U2, _>::from_owned(t2.to_arr())?,
|
// I2OSP(len(a3), 2) || a3 ||
|
||||||
Serialize::<U2, _>::from_owned(t3.to_arr())?,
|
// I2OSP(len(challengeDST), 2) || challengeDST
|
||||||
Serialize::<U2, _>::from_owned(challenge_dst)?,
|
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 =
|
let c_scalar = G::hash_to_scalar::<H>(&h2_input, Mode::Verifiable)?;
|
||||||
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 s_scalar = r - &(c_scalar * &k);
|
let s_scalar = r - &(c_scalar * &k);
|
||||||
|
|
||||||
Ok(Proof {
|
Ok(Proof {
|
||||||
@@ -959,31 +1003,56 @@ fn generate_proof<
|
|||||||
|
|
||||||
#[allow(clippy::many_single_char_names)]
|
#[allow(clippy::many_single_char_names)]
|
||||||
fn verify_proof<G: Group, H: BlockSizeUser + Digest + FixedOutputReset>(
|
fn verify_proof<G: Group, H: BlockSizeUser + Digest + FixedOutputReset>(
|
||||||
a: G,
|
a: G::Elem,
|
||||||
b: G,
|
b: G::Elem,
|
||||||
cs: impl Iterator<Item = EvaluationElement<G, H>> + ExactSizeIterator,
|
cs: impl Iterator<Item = EvaluationElement<G, H>> + ExactSizeIterator,
|
||||||
ds: impl Iterator<Item = BlindedElement<G, H>> + ExactSizeIterator,
|
ds: impl Iterator<Item = BlindedElement<G, H>> + ExactSizeIterator,
|
||||||
proof: &Proof<G, H>,
|
proof: &Proof<G, H>,
|
||||||
) -> Result<()> {
|
) -> 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 (m, z) = compute_composites(None, b, cs, ds)?;
|
||||||
let t2 = (a * &proof.s_scalar) + &(b * &proof.c_scalar);
|
let t2 = (a * &proof.s_scalar) + &(b * &proof.c_scalar);
|
||||||
let t3 = (m * &proof.s_scalar) + &(z * &proof.c_scalar);
|
let t3 = (m * &proof.s_scalar) + &(z * &proof.c_scalar);
|
||||||
|
|
||||||
let challenge_dst =
|
// Bm = GG.SerializeElement(B)
|
||||||
GenericArray::from(STR_CHALLENGE).concat(get_context_string::<G>(Mode::Verifiable)?);
|
let bm = G::serialize_elem(b);
|
||||||
chain!(
|
// a0 = GG.SerializeElement(M)
|
||||||
h2_input,
|
let a0 = G::serialize_elem(m);
|
||||||
Serialize::<U2, _>::from_owned(b.to_arr())?,
|
// a1 = GG.SerializeElement(Z)
|
||||||
Serialize::<U2, _>::from_owned(m.to_arr())?,
|
let a1 = G::serialize_elem(z);
|
||||||
Serialize::<U2, _>::from_owned(z.to_arr())?,
|
// a2 = GG.SerializeElement(t2)
|
||||||
Serialize::<U2, _>::from_owned(t2.to_arr())?,
|
let a2 = G::serialize_elem(t2);
|
||||||
Serialize::<U2, _>::from_owned(t3.to_arr())?,
|
// a3 = GG.SerializeElement(t3)
|
||||||
Serialize::<U2, _>::from_owned(challenge_dst)?,
|
let a3 = G::serialize_elem(t3);
|
||||||
);
|
|
||||||
|
|
||||||
let hash_to_scalar_dst =
|
let elem_len = G::ElemLen::U16.to_be_bytes();
|
||||||
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)?;
|
// 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() {
|
match c.ct_eq(&proof.c_scalar).into() {
|
||||||
true => Ok(()),
|
true => Ok(()),
|
||||||
@@ -993,7 +1062,7 @@ fn verify_proof<G: Group, H: BlockSizeUser + Digest + FixedOutputReset>(
|
|||||||
|
|
||||||
type FinalizeAfterUnblindResult<'a, G, H, I, IE> = Map<
|
type FinalizeAfterUnblindResult<'a, G, H, I, IE> = Map<
|
||||||
Zip<IE, Repeat<(&'a [u8], GenericArray<u8, U20>)>>,
|
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<
|
fn finalize_after_unblind<
|
||||||
@@ -1001,70 +1070,97 @@ fn finalize_after_unblind<
|
|||||||
G: Group,
|
G: Group,
|
||||||
H: BlockSizeUser + Digest + FixedOutputReset,
|
H: BlockSizeUser + Digest + FixedOutputReset,
|
||||||
I: AsRef<[u8]>,
|
I: AsRef<[u8]>,
|
||||||
IE: 'a + Iterator<Item = (I, G)>,
|
IE: 'a + Iterator<Item = (I, G::Elem)>,
|
||||||
>(
|
>(
|
||||||
inputs_and_unblinded_elements: IE,
|
inputs_and_unblinded_elements: IE,
|
||||||
info: &'a [u8],
|
info: &'a [u8],
|
||||||
mode: Mode,
|
mode: Mode,
|
||||||
) -> Result<FinalizeAfterUnblindResult<G, H, I, IE>> {
|
) -> 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
|
Ok(inputs_and_unblinded_elements
|
||||||
// To make a return type possible, we have to convert to a `fn` pointer,
|
// To make a return type possible, we have to convert to a `fn` pointer,
|
||||||
// which isn't possible if we `move` from context.
|
// which isn't possible if we `move` from context.
|
||||||
.zip(iter::repeat((info, finalize_dst)))
|
.zip(iter::repeat((info, finalize_dst)))
|
||||||
.map(|((input, unblinded_element), (info, finalize_dst))| {
|
.map(|((input, unblinded_element), (info, finalize_dst))| {
|
||||||
chain!(
|
let finalize_dst_len = i2osp_2_array(finalize_dst);
|
||||||
hash_input,
|
let elem_len = G::ElemLen::U16.to_be_bytes();
|
||||||
Serialize::<U2>::from(input.as_ref())?,
|
|
||||||
Serialize::<U2>::from(info)?,
|
|
||||||
Serialize::<U2, _>::from_owned(unblinded_element.to_arr())?,
|
|
||||||
Serialize::<U2, _>::from_owned(finalize_dst)?,
|
|
||||||
);
|
|
||||||
|
|
||||||
Ok(hash_input
|
// hashInput = I2OSP(len(input), 2) || input ||
|
||||||
.fold(H::new(), |h, bytes| h.chain_update(bytes))
|
// 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())
|
.finalize())
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn compute_composites<G: Group, H: BlockSizeUser + Digest + FixedOutputReset>(
|
fn compute_composites<G: Group, H: BlockSizeUser + Digest + FixedOutputReset>(
|
||||||
k_option: Option<G::Scalar>,
|
k_option: Option<G::Scalar>,
|
||||||
b: G,
|
b: G::Elem,
|
||||||
c_slice: impl Iterator<Item = EvaluationElement<G, H>> + ExactSizeIterator,
|
c_slice: impl Iterator<Item = EvaluationElement<G, H>> + ExactSizeIterator,
|
||||||
d_slice: impl Iterator<Item = BlindedElement<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() {
|
if c_slice.len() != d_slice.len() {
|
||||||
return Err(Error::MismatchedLengthsForCompositeInputs);
|
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 =
|
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!(
|
let seed = H::new()
|
||||||
h1_input,
|
.chain_update(&elem_len)
|
||||||
Serialize::<U2, _>::from_owned(b.to_arr())?,
|
.chain_update(G::serialize_elem(b))
|
||||||
Serialize::<U2, _>::from_owned(seed_dst)?,
|
.chain_update(i2osp_2_array(seed_dst))
|
||||||
);
|
.chain_update(seed_dst)
|
||||||
let seed = h1_input
|
|
||||||
.fold(H::new(), |h, bytes| h.chain_update(bytes))
|
|
||||||
.finalize();
|
.finalize();
|
||||||
|
let seed_len = i2osp_2(seed.len())?;
|
||||||
|
|
||||||
let mut m = G::identity();
|
let mut m = G::identity_elem();
|
||||||
let mut z = G::identity();
|
let mut z = G::identity_elem();
|
||||||
|
|
||||||
for (i, (c, d)) in c_slice.zip(d_slice).enumerate() {
|
for (i, (c, d)) in (0..len).zip(c_slice.zip(d_slice)) {
|
||||||
chain!(h2_input,
|
// Ci = GG.SerializeElement(Cs[i])
|
||||||
Serialize::<U2, _>::from_owned(seed.clone())?,
|
let ci = G::serialize_elem(c.value);
|
||||||
i2osp::<U2>(i)? => |x| Some(x.as_slice()),
|
// Di = GG.SerializeElement(Ds[i])
|
||||||
Serialize::<U2, _>::from_owned(c.value.to_arr())?,
|
let di = G::serialize_elem(d.value);
|
||||||
Serialize::<U2, _>::from_owned(d.value.to_arr())?,
|
// h2Input = I2OSP(len(seed), 2) || seed || I2OSP(i, 2) ||
|
||||||
Serialize::<U2, _>::from_owned(composite_dst)?,
|
// I2OSP(len(Ci), 2) || Ci ||
|
||||||
);
|
// I2OSP(len(Di), 2) || Di ||
|
||||||
let dst = GenericArray::from(STR_HASH_TO_SCALAR)
|
// I2OSP(len(compositeDST), 2) || compositeDST
|
||||||
.concat(get_context_string::<G>(Mode::Verifiable)?);
|
let h2_input = [
|
||||||
let di = G::hash_to_scalar::<H, _, _>(h2_input, dst)?;
|
&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;
|
m = c.value * &di + &m;
|
||||||
z = match k_option {
|
z = match k_option {
|
||||||
Some(_) => z,
|
Some(_) => z,
|
||||||
@@ -1082,10 +1178,10 @@ fn compute_composites<G: Group, H: BlockSizeUser + Digest + FixedOutputReset>(
|
|||||||
|
|
||||||
/// Generates the contextString parameter as defined in
|
/// Generates the contextString parameter as defined in
|
||||||
/// <https://www.ietf.org/archive/id/draft-irtf-cfrg-voprf-08.html>
|
/// <https://www.ietf.org/archive/id/draft-irtf-cfrg-voprf-08.html>
|
||||||
fn get_context_string<G: Group>(mode: Mode) -> Result<GenericArray<u8, U11>> {
|
pub(crate) fn get_context_string<G: Group>(mode: Mode) -> GenericArray<u8, U11> {
|
||||||
Ok(GenericArray::from(STR_VOPRF)
|
GenericArray::from(STR_VOPRF)
|
||||||
.concat(i2osp::<U1>(mode as usize)?)
|
.concat([mode.to_u8()].into())
|
||||||
.concat(i2osp::<U2>(G::SUITE_ID)?))
|
.concat(G::SUITE_ID.to_be_bytes().into())
|
||||||
}
|
}
|
||||||
|
|
||||||
///////////
|
///////////
|
||||||
@@ -1100,7 +1196,7 @@ mod tests {
|
|||||||
use ::alloc::vec;
|
use ::alloc::vec;
|
||||||
use ::alloc::vec::Vec;
|
use ::alloc::vec::Vec;
|
||||||
use generic_array::typenum::Sum;
|
use generic_array::typenum::Sum;
|
||||||
use generic_array::{ArrayLength, GenericArray};
|
use generic_array::ArrayLength;
|
||||||
use rand::rngs::OsRng;
|
use rand::rngs::OsRng;
|
||||||
use zeroize::Zeroize;
|
use zeroize::Zeroize;
|
||||||
|
|
||||||
@@ -1113,21 +1209,15 @@ mod tests {
|
|||||||
info: &[u8],
|
info: &[u8],
|
||||||
mode: Mode,
|
mode: Mode,
|
||||||
) -> Output<H> {
|
) -> Output<H> {
|
||||||
let dst =
|
let point = G::hash_to_curve::<H>(&[input], mode).unwrap();
|
||||||
GenericArray::from(STR_HASH_TO_GROUP).concat(get_context_string::<G>(mode).unwrap());
|
|
||||||
let point = G::hash_to_curve::<H, _>(input, dst).unwrap();
|
|
||||||
|
|
||||||
chain!(context,
|
let context_string = get_context_string::<G>(mode);
|
||||||
STR_CONTEXT => |x| Some(x.as_ref()),
|
let info_len = i2osp_2(info.len()).unwrap();
|
||||||
get_context_string::<G>(mode).unwrap() => |x| Some(x.as_slice()),
|
let context = [&STR_CONTEXT, context_string.as_slice(), &info_len, info];
|
||||||
Serialize::<U2>::from(info).unwrap(),
|
|
||||||
);
|
|
||||||
|
|
||||||
let dst =
|
let m = G::hash_to_scalar::<H>(&context, mode).unwrap();
|
||||||
GenericArray::from(STR_HASH_TO_SCALAR).concat(get_context_string::<G>(mode).unwrap());
|
|
||||||
let m = G::hash_to_scalar::<H, _, _>(context, dst).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)
|
finalize_after_unblind::<G, H, _, _>(Some((input, res)).into_iter(), info, mode)
|
||||||
.unwrap()
|
.unwrap()
|
||||||
@@ -1187,7 +1277,7 @@ mod tests {
|
|||||||
.unwrap();
|
.unwrap();
|
||||||
let wrong_pk = {
|
let wrong_pk = {
|
||||||
// Choose a group element that is unlikely to be the right public key
|
// 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(
|
let client_finalize_result = client_blind_result.state.finalize(
|
||||||
input,
|
input,
|
||||||
@@ -1284,7 +1374,7 @@ mod tests {
|
|||||||
let messages: Vec<_> = messages.collect();
|
let messages: Vec<_> = messages.collect();
|
||||||
let wrong_pk = {
|
let wrong_pk = {
|
||||||
// Choose a group element that is unlikely to be the right public key
|
// 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(
|
let client_finalize_result = VerifiableClient::batch_finalize(
|
||||||
&inputs,
|
&inputs,
|
||||||
@@ -1315,9 +1405,7 @@ mod tests {
|
|||||||
)
|
)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
let dst = GenericArray::from(STR_HASH_TO_GROUP)
|
let point = G::hash_to_curve::<H>(&[&input], Mode::Base).unwrap();
|
||||||
.concat(get_context_string::<G>(Mode::Base).unwrap());
|
|
||||||
let point = G::hash_to_curve::<H, _>(&input, dst).unwrap();
|
|
||||||
let res2 = finalize_after_unblind::<G, H, _, _>(
|
let res2 = finalize_after_unblind::<G, H, _, _>(
|
||||||
Some((input.as_ref(), point)).into_iter(),
|
Some((input.as_ref(), point)).into_iter(),
|
||||||
info,
|
info,
|
||||||
@@ -1415,38 +1503,39 @@ mod tests {
|
|||||||
fn test_functionality() -> Result<()> {
|
fn test_functionality() -> Result<()> {
|
||||||
#[cfg(feature = "ristretto255")]
|
#[cfg(feature = "ristretto255")]
|
||||||
{
|
{
|
||||||
use curve25519_dalek::ristretto::RistrettoPoint;
|
|
||||||
use sha2::Sha512;
|
use sha2::Sha512;
|
||||||
|
|
||||||
base_retrieval::<RistrettoPoint, Sha512>();
|
use crate::Ristretto255;
|
||||||
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>();
|
|
||||||
|
|
||||||
zeroize_base_client::<RistrettoPoint, Sha512>();
|
base_retrieval::<Ristretto255, Sha512>();
|
||||||
zeroize_base_server::<RistrettoPoint, Sha512>();
|
base_inversion_unsalted::<Ristretto255, Sha512>();
|
||||||
zeroize_verifiable_client::<RistrettoPoint, Sha512>();
|
verifiable_retrieval::<Ristretto255, Sha512>();
|
||||||
zeroize_verifiable_server::<RistrettoPoint, 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")]
|
#[cfg(feature = "p256")]
|
||||||
{
|
{
|
||||||
use p256_::ProjectivePoint;
|
use p256_::NistP256;
|
||||||
use sha2::Sha256;
|
use sha2::Sha256;
|
||||||
|
|
||||||
base_retrieval::<ProjectivePoint, Sha256>();
|
base_retrieval::<NistP256, Sha256>();
|
||||||
base_inversion_unsalted::<ProjectivePoint, Sha256>();
|
base_inversion_unsalted::<NistP256, Sha256>();
|
||||||
verifiable_retrieval::<ProjectivePoint, Sha256>();
|
verifiable_retrieval::<NistP256, Sha256>();
|
||||||
verifiable_batch_retrieval::<ProjectivePoint, Sha256>();
|
verifiable_batch_retrieval::<NistP256, Sha256>();
|
||||||
verifiable_bad_public_key::<ProjectivePoint, Sha256>();
|
verifiable_bad_public_key::<NistP256, Sha256>();
|
||||||
verifiable_batch_bad_public_key::<ProjectivePoint, Sha256>();
|
verifiable_batch_bad_public_key::<NistP256, Sha256>();
|
||||||
|
|
||||||
zeroize_base_client::<ProjectivePoint, Sha256>();
|
zeroize_base_client::<NistP256, Sha256>();
|
||||||
zeroize_base_server::<ProjectivePoint, Sha256>();
|
zeroize_base_server::<NistP256, Sha256>();
|
||||||
zeroize_verifiable_client::<ProjectivePoint, Sha256>();
|
zeroize_verifiable_client::<NistP256, Sha256>();
|
||||||
zeroize_verifiable_server::<ProjectivePoint, Sha256>();
|
zeroize_verifiable_server::<NistP256, Sha256>();
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|||||||
Reference in New Issue
Block a user