Group trait overhaul part 2 (#53)

* Rely on elliptic-curve for hash-to-curve and P-256 implementations

* Update MSRV

* Remove unnecessary `#[macro_use]`

* Re-introduce `CipherSuite`

* Provide types for length shortcuts

* Remove `SUITE_ID` from `Group`

* Blanket implementation for RustCrypto `Curve`s

* Remove the p256 crate feature

* Rename `ristretto_*` crate features to `ristretto-*` for consistency

* Remove unnecessary allowed Clippy lints

* Remove some unnecessary constraints
This commit is contained in:
daxpedda
2022-01-21 13:52:09 -08:00
committed by GitHub
parent 652fd1d1d0
commit 16e072dcd4
15 changed files with 1038 additions and 1643 deletions
+10 -17
View File
@@ -35,22 +35,16 @@ jobs:
fail-fast: false fail-fast: false
matrix: matrix:
backend_feature: backend_feature:
- ristretto255_u64 - --features ristretto255-ciphersuite,ristretto255-u64
- ristretto255_u32 - --features ristretto255-ciphersuite,ristretto255-u32
- p256 -
- ristretto255_u64,p256
frontend_feature: frontend_feature:
- -
- --features danger - --features danger
- --features serde - --features serde
toolchain: toolchain:
- stable - stable
- 1.51.0 - 1.57.0
exclude:
- backend_feature: p256
toolchain: 1.51.0
- backend_feature: ristretto255_u64,p256
toolchain: 1.51.0
name: test name: test
steps: steps:
- name: Checkout sources - name: Checkout sources
@@ -67,19 +61,19 @@ jobs:
uses: actions-rs/cargo@v1 uses: actions-rs/cargo@v1
with: with:
command: test command: test
args: --no-default-features --features ${{ matrix.backend_feature }} args: --no-default-features ${{ matrix.backend_feature }}
- name: Run cargo test with alloc - name: Run cargo test with alloc
uses: actions-rs/cargo@v1 uses: actions-rs/cargo@v1
with: with:
command: test command: test
args: --no-default-features ${{ matrix.frontend_feature }},alloc --features ${{ matrix.backend_feature }} args: --no-default-features ${{ matrix.frontend_feature }},alloc ${{ matrix.backend_feature }}
- name: Run cargo test with std - name: Run cargo test with std
uses: actions-rs/cargo@v1 uses: actions-rs/cargo@v1
with: with:
command: test command: test
args: --no-default-features ${{ matrix.frontend_feature }},std --features ${{ matrix.backend_feature }} args: --no-default-features ${{ matrix.frontend_feature }},std ${{ matrix.backend_feature }}
build-no-std: build-no-std:
name: Build with no-std on ${{ matrix.target }} name: Build with no-std on ${{ matrix.target }}
@@ -94,9 +88,8 @@ jobs:
- thumbv6m-none-eabi - thumbv6m-none-eabi
backend_feature: backend_feature:
- -
- --features ristretto255_u64 - --features ristretto255-ciphersuite,ristretto255-u64
- --features ristretto255_u32 - --features ristretto255-ciphersuite,ristretto255-u32
- --features p256
frontend_feature: frontend_feature:
- -
- --features danger - --features danger
@@ -135,7 +128,7 @@ jobs:
RUSTDOCFLAGS: -D warnings RUSTDOCFLAGS: -D warnings
with: with:
command: doc command: doc
args: --no-deps --document-private-items --features std,p256 args: --no-deps --document-private-items --features danger,std
rustfmt: rustfmt:
+20 -25
View File
@@ -2,34 +2,26 @@
authors = ["Kevin Lewi <[email protected]>"] authors = ["Kevin Lewi <[email protected]>"]
categories = ["no-std", "algorithms", "cryptography"] categories = ["no-std", "algorithms", "cryptography"]
description = "An implementation of a verifiable oblivious pseudorandom function (VOPRF)" description = "An implementation of a verifiable oblivious pseudorandom function (VOPRF)"
edition = "2018" edition = "2021"
keywords = ["oprf"] keywords = ["oprf"]
license = "MIT" license = "MIT"
name = "voprf" name = "voprf"
readme = "README.md" readme = "README.md"
repository = "https://github.com/novifinancial/voprf/" repository = "https://github.com/novifinancial/voprf/"
resolver = "2" rust-version = "1.57"
rust-version = "1.51"
version = "0.3.0" version = "0.3.0"
[features] [features]
alloc = [] alloc = []
danger = [] danger = []
default = ["ristretto255_u64", "serde"] default = ["ristretto255-ciphersuite", "ristretto255-u64", "serde"]
p256 = [
"alloc",
"num-bigint",
"num-integer",
"num-traits",
"once_cell",
"p256_",
]
ristretto255 = ["generic-array/more_lengths"] ristretto255 = ["generic-array/more_lengths"]
ristretto255_fiat_u32 = ["curve25519-dalek/fiat_u32_backend", "ristretto255"] ristretto255-ciphersuite = ["ristretto255", "sha2"]
ristretto255_fiat_u64 = ["curve25519-dalek/fiat_u64_backend", "ristretto255"] ristretto255-fiat-u32 = ["curve25519-dalek/fiat_u32_backend", "ristretto255"]
ristretto255_simd = ["curve25519-dalek/simd_backend", "ristretto255"] ristretto255-fiat-u64 = ["curve25519-dalek/fiat_u64_backend", "ristretto255"]
ristretto255_u32 = ["curve25519-dalek/u32_backend", "ristretto255"] ristretto255-simd = ["curve25519-dalek/simd_backend", "ristretto255"]
ristretto255_u64 = ["curve25519-dalek/u64_backend", "ristretto255"] ristretto255-u32 = ["curve25519-dalek/u32_backend", "ristretto255"]
ristretto255-u64 = ["curve25519-dalek/u64_backend", "ristretto255"]
std = ["alloc"] std = ["alloc"]
[dependencies] [dependencies]
@@ -37,18 +29,17 @@ curve25519-dalek = { version = "3", default-features = false, optional = true }
derive-where = { version = "1.0.0-rc.1", features = ["zeroize"] } derive-where = { version = "1.0.0-rc.1", features = ["zeroize"] }
digest = "0.10" digest = "0.10"
displaydoc = { version = "0.2", default-features = false } displaydoc = { version = "0.2", default-features = false }
elliptic-curve = { version = "0.12.0-pre.1", features = [
"hash2curve",
"sec1",
"voprf",
] }
generic-array = "0.14" generic-array = "0.14"
num-bigint = { version = "0.4", default-features = false, optional = true }
num-integer = { version = "0.1", default-features = false, optional = true }
num-traits = { version = "0.2", default-features = false, optional = true }
once_cell = { version = "1", default-features = false, optional = true }
p256_ = { package = "p256", version = "0.10", default-features = false, features = [
"arithmetic",
], optional = true }
rand_core = { version = "0.6", default-features = false } rand_core = { version = "0.6", default-features = false }
serde = { version = "1", default-features = false, features = [ serde = { version = "1", default-features = false, features = [
"derive", "derive",
], optional = true } ], optional = true }
sha2 = { version = "0.10", default-features = false, optional = true }
subtle = { version = "2.3", default-features = false } subtle = { version = "2.3", default-features = false }
zeroize = { version = "1", default-features = false } zeroize = { version = "1", default-features = false }
@@ -56,11 +47,15 @@ zeroize = { version = "1", default-features = false }
generic-array = { version = "0.14", features = ["more_lengths"] } generic-array = { version = "0.14", features = ["more_lengths"] }
hex = "0.4" hex = "0.4"
json = "0.12" json = "0.12"
p256 = { version = "0.11.0-pre.0", default-features = false, features = [
"hash2curve",
"voprf",
] }
proptest = "1" proptest = "1"
rand = "0.8" rand = "0.8"
regex = "1" regex = "1"
sha2 = "0.10" sha2 = "0.10"
[package.metadata.docs.rs] [package.metadata.docs.rs]
features = ["danger", "p256", "std"] features = ["danger", "std"]
targets = [] targets = []
+1 -1
View File
@@ -21,7 +21,7 @@ voprf = "0.3"
### Minimum Supported Rust Version ### Minimum Supported Rust Version
Rust **1.51** or higher. Rust **1.57** or higher.
Contributors Contributors
------------ ------------
+48
View File
@@ -0,0 +1,48 @@
// Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under both the MIT license found in the
// LICENSE-MIT file in the root directory of this source tree and the Apache
// License, Version 2.0 found in the LICENSE-APACHE file in the root directory
// of this source tree.
//! Defines the CipherSuite trait to specify the underlying primitives for VOPRF
use digest::core_api::BlockSizeUser;
use digest::{Digest, OutputSizeUser};
use elliptic_curve::VoprfParameters;
use generic_array::typenum::{IsLess, IsLessOrEqual, U256};
use crate::Group;
/// Configures the underlying primitives used in VOPRF
pub trait CipherSuite
where
<Self::Hash as OutputSizeUser>::OutputSize:
IsLess<U256> + IsLessOrEqual<<Self::Hash as BlockSizeUser>::BlockSize>,
{
/// The ciphersuite identifier as dictated by
/// <https://www.ietf.org/archive/id/draft-irtf-cfrg-voprf-08.html>
const ID: u16;
/// A finite cyclic group along with a point representation that allows some
/// customization on how to hash an input to a curve point. See [`Group`].
type Group: Group;
/// The main hash function to use (for HKDF computations and hashing
/// transcripts).
type Hash: BlockSizeUser + Digest;
}
impl<T: VoprfParameters> CipherSuite for T
where
T: Group,
T::Hash: BlockSizeUser + Digest,
<T::Hash as OutputSizeUser>::OutputSize:
IsLess<U256> + IsLessOrEqual<<T::Hash as BlockSizeUser>::BlockSize>,
{
const ID: u16 = T::ID;
type Group = T;
type Hash = T::Hash;
}
+113
View File
@@ -0,0 +1,113 @@
// Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under both the MIT license found in the
// LICENSE-MIT file in the root directory of this source tree and the Apache
// License, Version 2.0 found in the LICENSE-APACHE file in the root directory
// of this source tree.
use digest::core_api::BlockSizeUser;
use digest::OutputSizeUser;
use elliptic_curve::group::cofactor::CofactorGroup;
use elliptic_curve::hash2curve::{ExpandMsgXmd, FromOkm, GroupDigest};
use elliptic_curve::sec1::{FromEncodedPoint, ModulusSize, ToEncodedPoint};
use elliptic_curve::{
AffinePoint, Field, FieldSize, Group as _, ProjectivePoint, PublicKey, Scalar, SecretKey,
};
use generic_array::sequence::Concat;
use generic_array::typenum::{IsLess, IsLessOrEqual, U256};
use generic_array::GenericArray;
use rand_core::{CryptoRng, RngCore};
use super::Group;
use crate::group::{STR_HASH_TO_GROUP, STR_HASH_TO_SCALAR};
use crate::voprf::{self, Mode};
use crate::{CipherSuite, Error, Result};
impl<C> Group for C
where
C: GroupDigest,
ProjectivePoint<Self>: CofactorGroup,
FieldSize<Self>: ModulusSize,
AffinePoint<Self>: FromEncodedPoint<Self> + ToEncodedPoint<Self>,
Scalar<Self>: FromOkm,
{
type Elem = ProjectivePoint<Self>;
type ElemLen = <FieldSize<Self> as ModulusSize>::CompressedPointSize;
type Scalar = Scalar<Self>;
type ScalarLen = FieldSize<Self>;
// Implements the `hash_to_curve()` function from
// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-3
fn hash_to_curve<CS: CipherSuite>(msg: &[&[u8]], mode: Mode) -> Result<Self::Elem>
where
<CS::Hash as OutputSizeUser>::OutputSize:
IsLess<U256> + IsLessOrEqual<<CS::Hash as BlockSizeUser>::BlockSize>,
{
let dst =
GenericArray::from(STR_HASH_TO_GROUP).concat(voprf::get_context_string::<CS>(mode));
Self::hash_from_bytes::<ExpandMsgXmd<CS::Hash>>(msg, &dst).map_err(|_| Error::PointError)
}
// Implements the `HashToScalar()` function
fn hash_to_scalar<CS: CipherSuite>(input: &[&[u8]], mode: Mode) -> Result<Self::Scalar>
where
<CS::Hash as OutputSizeUser>::OutputSize:
IsLess<U256> + IsLessOrEqual<<CS::Hash as BlockSizeUser>::BlockSize>,
{
let dst =
GenericArray::from(STR_HASH_TO_SCALAR).concat(voprf::get_context_string::<CS>(mode));
<Self as GroupDigest>::hash_to_scalar::<ExpandMsgXmd<CS::Hash>>(input, &dst)
.map_err(|_| Error::PointError)
}
fn base_elem() -> Self::Elem {
ProjectivePoint::<Self>::generator()
}
fn identity_elem() -> Self::Elem {
ProjectivePoint::<Self>::identity()
}
fn serialize_elem(elem: Self::Elem) -> GenericArray<u8, Self::ElemLen> {
let point: AffinePoint<Self> = elem.into();
let bytes = point.to_encoded_point(true);
let bytes = bytes.as_bytes();
let mut result = GenericArray::default();
result[..bytes.len()].copy_from_slice(bytes);
result
}
fn deserialize_elem(element_bits: &GenericArray<u8, Self::ElemLen>) -> Result<Self::Elem> {
PublicKey::<Self>::from_sec1_bytes(element_bits)
.map(|public_key| public_key.to_projective())
.map_err(|_| Error::PointError)
}
fn random_scalar<R: RngCore + CryptoRng>(rng: &mut R) -> Self::Scalar {
*SecretKey::<Self>::random(rng).to_nonzero_scalar()
}
fn invert_scalar(scalar: Self::Scalar) -> Self::Scalar {
Option::from(scalar.invert()).unwrap()
}
#[cfg(test)]
fn zero_scalar() -> Self::Scalar {
Scalar::<Self>::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::<Self>::from_be_bytes(scalar_bits)
.map(|secret_key| *secret_key.to_nonzero_scalar())
.map_err(|_| Error::ScalarError)
}
}
-215
View File
@@ -1,215 +0,0 @@
// Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under both the MIT license found in the
// LICENSE-MIT file in the root directory of this source tree and the Apache
// License, Version 2.0 found in the LICENSE-APACHE file in the root directory
// of this source tree.
use core::convert::TryFrom;
use digest::core_api::{Block, BlockSizeUser};
use digest::{Digest, FixedOutputReset};
use generic_array::typenum::{IsLess, NonZero, Unsigned, U65536};
use generic_array::{ArrayLength, GenericArray};
use crate::{Error, Result};
fn xor<L: ArrayLength<u8>>(x: GenericArray<u8, L>, y: GenericArray<u8, L>) -> GenericArray<u8, L> {
x.into_iter().zip(y).map(|(x1, x2)| x1 ^ x2).collect()
}
/// Corresponds to the expand_message_xmd() function defined in
/// <https://www.ietf.org/archive/id/draft-irtf-cfrg-hash-to-curve-10.txt>
pub fn expand_message_xmd<H: BlockSizeUser + Digest + FixedOutputReset, L: ArrayLength<u8>>(
msg: &[&[u8]],
dst: &[u8],
) -> Result<GenericArray<u8, L>>
where
// 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>,
{
// DST, a byte string of at most 255 bytes.
let dst_len = u8::try_from(dst.len()).map_err(|_| Error::HashToCurveError)?;
// b_in_bytes, b / 8 for b the output size of H in bits.
let b_in_bytes = H::OutputSize::to_usize();
// Constraint set by `expand_message_xmd`:
// https://www.ietf.org/archive/id/draft-irtf-cfrg-hash-to-curve-13.html#section-5.4.1-4
if b_in_bytes > H::BlockSize::USIZE {
return Err(Error::HashToCurveError);
}
// 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
// Z_pad = I2OSP(0, s_in_bytes)
// s_in_bytes, the input block size of H, measured in bytes
Digest::update(&mut hash, Block::<H>::default());
for msg in msg {
Digest::update(&mut hash, msg);
}
// l_i_b_str = I2OSP(len_in_bytes, 2)
Digest::update(&mut hash, L::U16.to_be_bytes());
Digest::update(&mut hash, [0]);
// DST_prime = DST || I2OSP(len(DST), 1)
Digest::update(&mut hash, dst);
Digest::update(&mut hash, [dst_len]);
let b_0 = hash.finalize_reset();
let mut b_i = GenericArray::default();
let mut uniform_bytes = GenericArray::default();
// b_1 = H(b_0 || I2OSP(1, 1) || DST_prime)
// for i in (2, ..., ell):
for (i, chunk) in (1..(ell + 1)).zip(uniform_bytes.chunks_mut(b_in_bytes)) {
// b_i = H(strxor(b_0, b_(i - 1)) || I2OSP(i, 1) || DST_prime)
Digest::update(&mut hash, xor(b_0.clone(), b_i.clone()));
Digest::update(&mut hash, [i]);
// DST_prime = DST || I2OSP(len(DST), 1)
Digest::update(&mut hash, dst);
Digest::update(&mut hash, [dst_len]);
b_i = hash.finalize_reset();
// uniform_bytes = b_1 || ... || b_ell
// return substr(uniform_bytes, 0, len_in_bytes)
chunk.copy_from_slice(&b_i[..b_in_bytes.min(chunk.len())]);
}
Ok(uniform_bytes)
}
#[cfg(test)]
mod tests {
use generic_array::typenum::{U128, U32};
struct Params {
msg: &'static str,
len_in_bytes: usize,
uniform_bytes: &'static str,
}
#[test]
fn test_expand_message_xmd() {
const DST: [u8; 27] = *b"QUUX-V01-CS02-with-expander";
// Test vectors taken from Section K.1 of https://www.ietf.org/archive/id/draft-irtf-cfrg-hash-to-curve-10.txt
let test_vectors: alloc::vec::Vec<Params> = alloc::vec![
Params {
msg: "",
len_in_bytes: 0x20,
uniform_bytes: "f659819a6473c1835b25ea59e3d38914c98b374f0970b7e4c\
92181df928fca88",
},
Params {
msg: "abc",
len_in_bytes: 0x20,
uniform_bytes: "1c38f7c211ef233367b2420d04798fa4698080a8901021a79\
5a1151775fe4da7",
},
Params {
msg: "abcdef0123456789",
len_in_bytes: 0x20,
uniform_bytes: "8f7e7b66791f0da0dbb5ec7c22ec637f79758c0a48170bfb7c4611bd304ece89",
},
Params {
msg: "q128_qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\
qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\
qqqqqqqqqqqqqqqqqqqqqqqqq",
len_in_bytes: 0x20,
uniform_bytes: "72d5aa5ec810370d1f0013c0df2f1d65699494ee2a39f72e\
1716b1b964e1c642",
},
Params {
msg: "a512_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
len_in_bytes: 0x20,
uniform_bytes: "3b8e704fc48336aca4c2a12195b720882f2162a4b7b13a9c\
350db46f429b771b",
},
Params {
msg: "",
len_in_bytes: 0x80,
uniform_bytes: "8bcffd1a3cae24cf9cd7ab85628fd111bb17e3739d3b53f8\
9580d217aa79526f1708354a76a402d3569d6a9d19ef3de4d0b991\
e4f54b9f20dcde9b95a66824cbdf6c1a963a1913d43fd7ac443a02\
fc5d9d8d77e2071b86ab114a9f34150954a7531da568a1ea8c7608\
61c0cde2005afc2c114042ee7b5848f5303f0611cf297f",
},
Params {
msg: "abc",
len_in_bytes: 0x80,
uniform_bytes: "fe994ec51bdaa821598047b3121c149b364b178606d5e72b\
fbb713933acc29c186f316baecf7ea22212f2496ef3f785a27e84a\
40d8b299cec56032763eceeff4c61bd1fe65ed81decafff4a31d01\
98619c0aa0c6c51fca15520789925e813dcfd318b542f879944127\
1f4db9ee3b8092a7a2e8d5b75b73e28fb1ab6b4573c192",
},
Params {
msg: "abcdef0123456789",
len_in_bytes: 0x80,
uniform_bytes: "c9ec7941811b1e19ce98e21db28d22259354d4d0643e3011\
75e2f474e030d32694e9dd5520dde93f3600d8edad94e5c3649030\
88a7228cc9eff685d7eaac50d5a5a8229d083b51de4ccc3733917f\
4b9535a819b445814890b7029b5de805bf62b33a4dc7e24acdf2c9\
24e9fe50d55a6b832c8c84c7f82474b34e48c6d43867be",
},
Params {
msg: "q128_qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\
qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\
qqqqqqqqqqqqqqqqqqqqqqqqq",
len_in_bytes: 0x80,
uniform_bytes: "48e256ddba722053ba462b2b93351fc966026e6d6db49318\
9798181c5f3feea377b5a6f1d8368d7453faef715f9aecb078cd40\
2cbd548c0e179c4ed1e4c7e5b048e0a39d31817b5b24f50db58bb3\
720fe96ba53db947842120a068816ac05c159bb5266c63658b4f00\
0cbf87b1209a225def8ef1dca917bcda79a1e42acd8069",
},
Params {
msg: "a512_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
len_in_bytes: 0x80,
uniform_bytes: "396962db47f749ec3b5042ce2452b619607f27fd3939ece2\
746a7614fb83a1d097f554df3927b084e55de92c7871430d6b95c2\
a13896d8a33bc48587b1f66d21b128a1a8240d5b0c26dfe795a1a8\
42a0807bb148b77c2ef82ed4b6c9f7fcb732e7f94466c8b51e52bf\
378fba044a31f5cb44583a892f5969dcd73b3fa128816e",
},
];
for tv in test_vectors {
let uniform_bytes = match tv.len_in_bytes {
32 => super::expand_message_xmd::<sha2::Sha256, U32>(&[tv.msg.as_bytes()], &DST)
.map(|bytes| bytes.to_vec()),
128 => super::expand_message_xmd::<sha2::Sha256, U128>(&[tv.msg.as_bytes()], &DST)
.map(|bytes| bytes.to_vec()),
_ => unimplemented!(),
}
.unwrap();
assert_eq!(tv.uniform_bytes, hex::encode(uniform_bytes));
}
}
}
+18 -26
View File
@@ -7,17 +7,15 @@
//! Defines the Group trait to specify the underlying prime order group //! Defines the Group trait to specify the underlying prime order group
#[cfg(any(feature = "ristretto255", feature = "p256",))] mod elliptic_curve;
mod expand;
#[cfg(feature = "p256")]
mod p256;
#[cfg(feature = "ristretto255")] #[cfg(feature = "ristretto255")]
mod ristretto; mod ristretto;
use core::ops::{Add, Mul, Sub}; use core::ops::{Add, Mul, Sub};
use digest::core_api::BlockSizeUser; use digest::core_api::BlockSizeUser;
use digest::{Digest, FixedOutputReset}; use digest::OutputSizeUser;
use generic_array::typenum::{IsLess, IsLessOrEqual, U256};
use generic_array::{ArrayLength, GenericArray}; use generic_array::{ArrayLength, GenericArray};
use rand_core::{CryptoRng, RngCore}; use rand_core::{CryptoRng, RngCore};
#[cfg(feature = "ristretto255")] #[cfg(feature = "ristretto255")]
@@ -26,7 +24,7 @@ use subtle::ConstantTimeEq;
use zeroize::Zeroize; use zeroize::Zeroize;
use crate::voprf::Mode; use crate::voprf::Mode;
use crate::Result; use crate::{CipherSuite, Result};
pub(crate) const STR_HASH_TO_SCALAR: [u8; 13] = *b"HashToScalar-"; pub(crate) const STR_HASH_TO_SCALAR: [u8; 13] = *b"HashToScalar-";
pub(crate) const STR_HASH_TO_GROUP: [u8; 12] = *b"HashToGroup-"; pub(crate) const STR_HASH_TO_GROUP: [u8; 12] = *b"HashToGroup-";
@@ -34,43 +32,37 @@ 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 {
/// The ciphersuite identifier as dictated by
/// <https://www.ietf.org/archive/id/draft-irtf-cfrg-voprf-05.txt>
const SUITE_ID: u16;
/// The type of group elements /// The type of group elements
type Elem: Copy type Elem: Copy
+ Sized
+ ConstantTimeEq
+ Zeroize + Zeroize
+ for<'a> Mul<&'a Self::Scalar, Output = Self::Elem> + for<'a> Add<&'a Self::Elem, Output = Self::Elem>
+ for<'a> Add<&'a Self::Elem, Output = Self::Elem>; + for<'a> Mul<&'a Self::Scalar, Output = Self::Elem>;
/// The byte length necessary to represent group elements /// The byte length necessary to represent group elements
type ElemLen: ArrayLength<u8> + 'static; type ElemLen: ArrayLength<u8> + 'static;
/// The type of base field scalars /// The type of base field scalars
type Scalar: Zeroize type Scalar: ConstantTimeEq
+ Copy + Copy
+ ConstantTimeEq + Zeroize
+ 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> Mul<&'a Self::Scalar, Output = Self::Scalar>
+ for<'a> Mul<&'a Self::Scalar, Output = Self::Scalar>; + for<'a> Sub<&'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;
/// transforms a password and domain separation tag (DST) into a curve point /// transforms a password and domain separation tag (DST) into a curve point
fn hash_to_curve<H: BlockSizeUser + Digest + FixedOutputReset>( fn hash_to_curve<CS: CipherSuite>(msg: &[&[u8]], mode: Mode) -> Result<Self::Elem>
msg: &[&[u8]], where
mode: Mode, <CS::Hash as OutputSizeUser>::OutputSize:
) -> Result<Self::Elem>; IsLess<U256> + IsLessOrEqual<<CS::Hash as BlockSizeUser>::BlockSize>;
/// Hashes a slice of pseudo-random bytes to a scalar /// Hashes a slice of pseudo-random bytes to a scalar
fn hash_to_scalar<H: BlockSizeUser + Digest + FixedOutputReset>( fn hash_to_scalar<CS: CipherSuite>(input: &[&[u8]], mode: Mode) -> Result<Self::Scalar>
input: &[&[u8]], where
mode: Mode, <CS::Hash as OutputSizeUser>::OutputSize:
) -> Result<Self::Scalar>; IsLess<U256> + IsLessOrEqual<<CS::Hash as BlockSizeUser>::BlockSize>;
/// Get the base point for the group /// Get the base point for the group
fn base_elem() -> Self::Elem; fn base_elem() -> Self::Elem;
-586
View File
@@ -1,586 +0,0 @@
// Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under both the MIT license found in the
// LICENSE-MIT file in the root directory of this source tree and the Apache
// License, Version 2.0 found in the LICENSE-APACHE file in the root directory
// of this source tree.
// Note: This group implementation of p256 is experimental for now, until
// hash-to-curve or crypto-bigint are fully supported.
#![allow(
clippy::borrow_interior_mutable_const,
clippy::declare_interior_mutable_const
)]
use core::ops::{Add, Div, Mul, Neg};
use core::str::FromStr;
use digest::core_api::BlockSizeUser;
use digest::{Digest, FixedOutputReset};
use generic_array::sequence::Concat;
use generic_array::typenum::{Unsigned, U2, U32, U33, U48};
use generic_array::{ArrayLength, GenericArray};
use num_bigint::{BigInt, Sign};
use num_integer::Integer;
use num_traits::{One, ToPrimitive, Zero};
use once_cell::unsync::Lazy;
use p256_::elliptic_curve::bigint::{Encoding, U384};
use p256_::elliptic_curve::group::prime::PrimeCurveAffine;
use p256_::elliptic_curve::ops::Reduce;
use p256_::elliptic_curve::sec1::{FromEncodedPoint, ToEncodedPoint};
#[cfg(test)]
use p256_::elliptic_curve::Field;
use p256_::{AffinePoint, EncodedPoint, NistP256, ProjectivePoint, PublicKey, Scalar, SecretKey};
use rand_core::{CryptoRng, RngCore};
use subtle::{Choice, ConditionallySelectable};
use super::Group;
use crate::group::{STR_HASH_TO_GROUP, STR_HASH_TO_SCALAR};
use crate::voprf::{self, Mode};
use crate::{Error, Result};
// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-8.2
// `L: 48`
pub type L = U48;
#[cfg(feature = "p256")]
impl Group for NistP256 {
const SUITE_ID: u16 = 0x0003;
type Elem = ProjectivePoint;
type ElemLen = U33;
type Scalar = Scalar;
type ScalarLen = U32;
// Implements the `hash_to_curve()` function from
// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-3
fn hash_to_curve<H: BlockSizeUser + Digest + FixedOutputReset>(
msg: &[&[u8]],
mode: Mode,
) -> Result<Self::Elem> {
let dst =
GenericArray::from(STR_HASH_TO_GROUP).concat(voprf::get_context_string::<Self>(mode));
// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-8.2
// `p: 2^256 - 2^224 + 2^192 + 2^96 - 1`
const P: Lazy<BigInt> = Lazy::new(|| {
BigInt::from_str(
"115792089210356248762697446949407573530086143415290314195533631308867097853951",
)
.unwrap()
});
// `A: -3`
const A: Lazy<BigInt> = Lazy::new(|| BigInt::from(-3));
// `B: 0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b`
const B: Lazy<BigInt> = Lazy::new(|| {
BigInt::parse_bytes(
b"5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b",
16,
)
.unwrap()
});
// `Z: -10`
const Z: Lazy<BigInt> = Lazy::new(|| BigInt::from(-10));
// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-3
// `hash_to_curve` calls `hash_to_field` with a `count` of `2`
// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-5.3
// `hash_to_field` calls `expand_message` with a `len_in_bytes` of `count * L`
let uniform_bytes =
super::expand::expand_message_xmd::<H, <L as Mul<U2>>::Output>(msg, &dst)?;
// hash to curve
let (q0x, q0y) = hash_to_curve_simple_swu(&uniform_bytes[..L::USIZE], &A, &B, &P, &Z);
let (q1x, q1y) = hash_to_curve_simple_swu(&uniform_bytes[L::USIZE..], &A, &B, &P, &Z);
// convert to `p256` types
let p0 = Option::<AffinePoint>::from(AffinePoint::from_encoded_point(
&EncodedPoint::from_affine_coordinates(&q0x, &q0y, false),
))
.ok_or(Error::PointError)?
.to_curve();
let p1 = Option::<AffinePoint>::from(AffinePoint::from_encoded_point(
&EncodedPoint::from_affine_coordinates(&q1x, &q1y, false),
))
.ok_or(Error::PointError)?;
Ok(p0 + p1)
}
// Implements the `HashToScalar()` function
fn hash_to_scalar<H: BlockSizeUser + Digest + FixedOutputReset>(
input: &[&[u8]],
mode: Mode,
) -> Result<Self::Scalar> {
let dst =
GenericArray::from(STR_HASH_TO_SCALAR).concat(voprf::get_context_string::<Self>(mode));
// https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf#[{%22num%22:211,%22gen%22:0},{%22name%22:%22XYZ%22},70,700,0]
// P-256 `n` is defined as
// `115792089210356248762697446949407573529996955224135760342
// 422259061068512044369`
const N: U384 =
U384::from_be_hex("00000000000000000000000000000000FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551");
// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-5.3
// `HashToScalar` is `hash_to_field`
let uniform_bytes = super::expand::expand_message_xmd::<H, L>(input, &dst)?;
let bytes = Option::<U384>::from(U384::from_be_slice(&uniform_bytes).reduce(&N))
.unwrap()
.to_be_bytes();
Ok(Scalar::from_be_bytes_reduced(
GenericArray::clone_from_slice(&bytes[16..]),
))
}
fn base_elem() -> Self::Elem {
ProjectivePoint::generator()
}
fn identity_elem() -> Self::Elem {
ProjectivePoint::identity()
}
fn serialize_elem(elem: Self::Elem) -> GenericArray<u8, Self::ElemLen> {
let bytes = elem.to_affine().to_encoded_point(true);
let bytes = bytes.as_bytes();
let mut result = GenericArray::default();
result[..bytes.len()].copy_from_slice(bytes);
result
}
fn deserialize_elem(element_bits: &GenericArray<u8, Self::ElemLen>) -> Result<Self::Elem> {
PublicKey::from_sec1_bytes(element_bits)
.map(|public_key| public_key.to_projective())
.map_err(|_| Error::PointError)
}
fn random_scalar<R: RngCore + CryptoRng>(rng: &mut R) -> Self::Scalar {
*SecretKey::random(rng).to_nonzero_scalar()
}
fn invert_scalar(scalar: Self::Scalar) -> Self::Scalar {
Option::from(scalar.invert()).unwrap()
}
#[cfg(test)]
fn zero_scalar() -> Self::Scalar {
Scalar::zero()
}
fn serialize_scalar(scalar: Self::Scalar) -> GenericArray<u8, Self::ScalarLen> {
scalar.into()
}
fn deserialize_scalar(scalar_bits: &GenericArray<u8, Self::ScalarLen>) -> Result<Self::Scalar> {
SecretKey::from_be_bytes(scalar_bits)
.map(|secret_key| *secret_key.to_nonzero_scalar())
.map_err(|_| Error::ScalarError)
}
}
/// Corresponds to the hash_to_curve_simple_swu() function defined in
/// <https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#appendix-F.2>
///
/// `cmov`, `mod_floor` and `modpow` needs to be made constant-time, which will
/// be supported after crypto-bigint is no longer experimental. See
/// <https://github.com/novifinancial/voprf/issues/13> for more context.
#[allow(clippy::many_single_char_names)]
fn hash_to_curve_simple_swu<N: ArrayLength<u8>>(
u: &[u8],
a: &BigInt,
b: &BigInt,
p: &BigInt,
z: &BigInt,
) -> (GenericArray<u8, N>, GenericArray<u8, N>) {
#[derive(Clone)]
struct Field<'a>(&'a BigInt);
impl<'a> Field<'a> {
fn new(p: &'a BigInt) -> Self {
Self(p)
}
fn element(&'a self, number: &BigInt) -> FieldElement<'a> {
FieldElement {
number: number.mod_floor(self.0),
f: self,
}
}
fn one(&'a self) -> FieldElement<'a> {
self.element(&BigInt::one())
}
}
/// Finite field arithmetic
#[derive(Clone)]
struct FieldElement<'a> {
number: BigInt,
f: &'a Field<'a>,
}
impl<'a> Add for FieldElement<'a> {
type Output = FieldElement<'a>;
fn add(self, rhs: Self) -> Self::Output {
&self + &rhs
}
}
impl<'a> Add for &FieldElement<'a> {
type Output = FieldElement<'a>;
fn add(self, rhs: Self) -> Self::Output {
self.f.element(&(&self.number + &rhs.number))
}
}
impl<'a> Neg for FieldElement<'a> {
type Output = FieldElement<'a>;
fn neg(self) -> Self::Output {
-&self
}
}
impl<'a> Neg for &FieldElement<'a> {
type Output = FieldElement<'a>;
fn neg(self) -> Self::Output {
self.f.element(&-&self.number)
}
}
impl<'a> Mul for FieldElement<'a> {
type Output = FieldElement<'a>;
fn mul(self, rhs: Self) -> Self::Output {
&self * &rhs
}
}
impl<'a> Mul<&Self> for FieldElement<'a> {
type Output = FieldElement<'a>;
fn mul(self, rhs: &Self) -> Self::Output {
&self * rhs
}
}
impl<'a> Mul<FieldElement<'a>> for &FieldElement<'a> {
type Output = FieldElement<'a>;
fn mul(self, rhs: FieldElement<'a>) -> Self::Output {
self * &rhs
}
}
impl<'a> Mul for &FieldElement<'a> {
type Output = FieldElement<'a>;
fn mul(self, rhs: Self) -> Self::Output {
self.f.element(&(&self.number * &rhs.number))
}
}
impl<'a> Div<&Self> for FieldElement<'a> {
type Output = FieldElement<'a>;
#[allow(clippy::suspicious_arithmetic_impl)]
fn div(self, rhs: &Self) -> Self::Output {
self * rhs.inv0()
}
}
impl<'a> FieldElement<'a> {
fn square(&self) -> Self {
self * self
}
fn pow_internal(&self, exponent: &BigInt) -> Self {
let exponent = exponent.mod_floor(&(self.f.0 - 1));
Self {
number: self.number.modpow(&exponent, self.f.0),
f: self.f,
}
}
/// Corresponds to the sqrt_3mod4() function defined in
/// <https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#appendix-I.1>
fn sqrt(&self) -> Self {
// constant
let c1 = (self.f.0 + 1) >> 2;
self.pow_internal(&c1)
}
/// Corresponds to the sgn0_m_eq_1() function defined in
/// <https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-4.1>
fn sgn0(&self) -> i32 {
(&self.number % 2_usize).to_i32().unwrap()
}
/// See <https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-4>
fn inv0(&self) -> Self {
self.pow_internal(&(self.f.0 - 2))
}
fn is_zero(&self) -> bool {
self.number.is_zero()
}
/// Corresponds to the is_square() function defined in
/// <https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-4>
fn is_square(&self) -> bool {
// constant
let exponent = (self.f.0 - 1) >> 1;
let result = self.pow_internal(&exponent);
result.is_zero() || result.number.is_one()
}
fn to_bytes<N: ArrayLength<u8>>(&self) -> GenericArray<u8, N> {
let bytes = self.number.to_bytes_be().1;
let mut result = GenericArray::default();
result[N::USIZE - bytes.len()..].copy_from_slice(&bytes);
result
}
}
fn cmov<'a>(x: &FieldElement<'a>, y: &FieldElement<'a>, b: bool) -> FieldElement<'a> {
let f = x.f;
let x_bytes = x.number.to_bytes_le().1;
let mut x = [0; 32];
x[..x_bytes.len()].copy_from_slice(&x_bytes);
let y_bytes = y.number.to_bytes_le().1;
let mut y = [0; 32];
y[..y_bytes.len()].copy_from_slice(&y_bytes);
let mut bytes = [0; 32];
let choice = Choice::from(u8::from(b));
for ((byte, x), y) in bytes.iter_mut().zip(&x).zip(&y) {
*byte = u8::conditional_select(x, y, choice);
}
FieldElement {
f,
number: BigInt::from_bytes_le(Sign::Plus, &bytes),
}
}
let f = Field::new(p);
let a = f.element(a);
let b = f.element(b);
let z = f.element(z);
let u = f.element(&BigInt::from_bytes_be(Sign::Plus, u));
// Constants:
// 1. c1 = -B / A
let c1 = -&b / &a;
// 2. c2 = -1 / Z
let c2 = -f.one() / &z;
// Steps:
// 1. tv1 = Z * u^2
let tv1 = z * u.square();
// 2. tv2 = tv1^2
let mut tv2 = tv1.square();
// 3. x1 = tv1 + tv2
let mut x1 = &tv1 + &tv2;
// 4. x1 = inv0(x1)
x1 = x1.inv0();
// 5. e1 = x1 == 0
let e1 = x1.is_zero();
// 6. x1 = x1 + 1
x1 = x1 + f.one();
// 7. x1 = CMOV(x1, c2, e1) # If (tv1 + tv2) == 0, set x1 = -1 / Z
x1 = cmov(&x1, &c2, e1);
// 8. x1 = x1 * c1 # x1 = (-B / A) * (1 + (1 / (Z^2 * u^4 + Z * u^2)))
x1 = x1 * c1;
// 9. gx1 = x1^2
let mut gx1 = x1.square();
// 10. gx1 = gx1 + A
gx1 = gx1 + a;
// 11. gx1 = gx1 * x1
gx1 = gx1 * &x1;
// 12. gx1 = gx1 + B # gx1 = g(x1) = x1^3 + A * x1 + B
gx1 = gx1 + b;
// 13. x2 = tv1 * x1 # x2 = Z * u^2 * x1
let x2 = &tv1 * &x1;
// 14. tv2 = tv1 * tv2
tv2 = tv1 * tv2;
// 15. gx2 = gx1 * tv2 # gx2 = (Z * u^2)^3 * gx1
let gx2 = &gx1 * tv2;
// 16. e2 = is_square(gx1)
let e2 = gx1.is_square();
// 17. x = CMOV(x2, x1, e2) # If is_square(gx1), x = x1, else x = x2
let x = cmov(&x2, &x1, e2);
// 18. y2 = CMOV(gx2, gx1, e2) # If is_square(gx1), y2 = gx1, else y2 = gx2
let y2 = cmov(&gx2, &gx1, e2);
// 19. y = sqrt(y2)
let mut y = y2.sqrt();
// 20. e3 = sgn0(u) == sgn0(y) # Fix sign of y
let e3 = u.sgn0() == y.sgn0();
// 21. y = CMOV(-y, y, e3)
y = cmov(&-&y, &y, e3);
// 22. return (x, y)
(x.to_bytes(), y.to_bytes())
}
#[cfg(test)]
mod tests {
use generic_array::typenum::U96;
use super::*;
struct Params {
msg: &'static str,
px: &'static str,
py: &'static str,
u0: &'static str,
u1: &'static str,
q0x: &'static str,
q0y: &'static str,
q1x: &'static str,
q1y: &'static str,
}
#[test]
fn hash_to_curve_simple_swu() {
const DST: [u8; 44] = *b"QUUX-V01-CS02-with-P256_XMD:SHA-256_SSWU_RO_";
const P: Lazy<BigInt> = Lazy::new(|| {
BigInt::from_str(
"115792089210356248762697446949407573530086143415290314195533631308867097853951",
)
.unwrap()
});
const A: Lazy<BigInt> = Lazy::new(|| BigInt::from(-3));
const B: Lazy<BigInt> = Lazy::new(|| {
BigInt::parse_bytes(
b"5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b",
16,
)
.unwrap()
});
const Z: Lazy<BigInt> = Lazy::new(|| BigInt::from(-10));
// Test vectors taken from https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#appendix-J.1.1
let test_vectors = alloc::vec![
Params {
msg: "",
px: "2c15230b26dbc6fc9a37051158c95b79656e17a1a920b11394ca91c44247d3e4",
py: "8a7a74985cc5c776cdfe4b1f19884970453912e9d31528c060be9ab5c43e8415",
u0: "ad5342c66a6dd0ff080df1da0ea1c04b96e0330dd89406465eeba11582515009",
u1: "8c0f1d43204bd6f6ea70ae8013070a1518b43873bcd850aafa0a9e220e2eea5a",
q0x: "ab640a12220d3ff283510ff3f4b1953d09fad35795140b1c5d64f313967934d5",
q0y: "dccb558863804a881d4fff3455716c836cef230e5209594ddd33d85c565b19b1",
q1x: "51cce63c50d972a6e51c61334f0f4875c9ac1cd2d3238412f84e31da7d980ef5",
q1y: "b45d1a36d00ad90e5ec7840a60a4de411917fbe7c82c3949a6e699e5a1b66aac",
},
Params {
msg: "abc",
px: "0bb8b87485551aa43ed54f009230450b492fead5f1cc91658775dac4a3388a0f",
py: "5c41b3d0731a27a7b14bc0bf0ccded2d8751f83493404c84a88e71ffd424212e",
u0: "afe47f2ea2b10465cc26ac403194dfb68b7f5ee865cda61e9f3e07a537220af1",
u1: "379a27833b0bfe6f7bdca08e1e83c760bf9a338ab335542704edcd69ce9e46e0",
q0x: "5219ad0ddef3cc49b714145e91b2f7de6ce0a7a7dc7406c7726c7e373c58cb48",
q0y: "7950144e52d30acbec7b624c203b1996c99617d0b61c2442354301b191d93ecf",
q1x: "019b7cb4efcfeaf39f738fe638e31d375ad6837f58a852d032ff60c69ee3875f",
q1y: "589a62d2b22357fed5449bc38065b760095ebe6aeac84b01156ee4252715446e",
},
Params {
msg: "abcdef0123456789",
px: "65038ac8f2b1def042a5df0b33b1f4eca6bff7cb0f9c6c1526811864e544ed80",
py: "cad44d40a656e7aff4002a8de287abc8ae0482b5ae825822bb870d6df9b56ca3",
u0: "0fad9d125a9477d55cf9357105b0eb3a5c4259809bf87180aa01d651f53d312c",
u1: "b68597377392cd3419d8fcc7d7660948c8403b19ea78bbca4b133c9d2196c0fb",
q0x: "a17bdf2965eb88074bc01157e644ed409dac97cfcf0c61c998ed0fa45e79e4a2",
q0y: "4f1bc80c70d411a3cc1d67aeae6e726f0f311639fee560c7f5a664554e3c9c2e",
q1x: "7da48bb67225c1a17d452c983798113f47e438e4202219dd0715f8419b274d66",
q1y: "b765696b2913e36db3016c47edb99e24b1da30e761a8a3215dc0ec4d8f96e6f9",
},
Params {
msg: "q128_qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\
qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\
qqqqqqqqqqqqqqqqqqqqqqqqq",
px: "4be61ee205094282ba8a2042bcb48d88dfbb609301c49aa8b078533dc65a0b5d",
py: "98f8df449a072c4721d241a3b1236d3caccba603f916ca680f4539d2bfb3c29e",
u0: "3bbc30446f39a7befad080f4d5f32ed116b9534626993d2cc5033f6f8d805919",
u1: "76bb02db019ca9d3c1e02f0c17f8baf617bbdae5c393a81d9ce11e3be1bf1d33",
q0x: "c76aaa823aeadeb3f356909cb08f97eee46ecb157c1f56699b5efebddf0e6398",
q0y: "776a6f45f528a0e8d289a4be12c4fab80762386ec644abf2bffb9b627e4352b1",
q1x: "418ac3d85a5ccc4ea8dec14f750a3a9ec8b85176c95a7022f391826794eb5a75",
q1y: "fd6604f69e9d9d2b74b072d14ea13050db72c932815523305cb9e807cc900aff",
},
Params {
msg: "a512_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
px: "457ae2981f70ca85d8e24c308b14db22f3e3862c5ea0f652ca38b5e49cd64bc5",
py: "ecb9f0eadc9aeed232dabc53235368c1394c78de05dd96893eefa62b0f4757dc",
u0: "4ebc95a6e839b1ae3c63b847798e85cb3c12d3817ec6ebc10af6ee51adb29fec",
u1: "4e21af88e22ea80156aff790750121035b3eefaa96b425a8716e0d20b4e269ee",
q0x: "d88b989ee9d1295df413d4456c5c850b8b2fb0f5402cc5c4c7e815412e926db8",
q0y: "bb4a1edeff506cf16def96afff41b16fc74f6dbd55c2210e5b8f011ba32f4f40",
q1x: "a281e34e628f3a4d2a53fa87ff973537d68ad4fbc28d3be5e8d9f6a2571c5a4b",
q1y: "f6ed88a7aab56a488100e6f1174fa9810b47db13e86be999644922961206e184",
},
];
for tv in test_vectors {
let uniform_bytes = super::super::expand::expand_message_xmd::<sha2::Sha256, U96>(
&[tv.msg.as_bytes()],
&DST,
)
.unwrap();
let u0 = BigInt::from_bytes_be(Sign::Plus, &uniform_bytes[..48]).mod_floor(&P);
let u1 = BigInt::from_bytes_be(Sign::Plus, &uniform_bytes[48..]).mod_floor(&P);
assert_eq!(BigInt::parse_bytes(tv.u0.as_bytes(), 16).unwrap(), u0);
assert_eq!(BigInt::parse_bytes(tv.u1.as_bytes(), 16).unwrap(), u1);
let (q0x, q0y) = super::hash_to_curve_simple_swu(&u0.to_bytes_be().1, &A, &B, &P, &Z);
let (q1x, q1y) = super::hash_to_curve_simple_swu(&u1.to_bytes_be().1, &A, &B, &P, &Z);
assert_eq!(tv.q0x, hex::encode(q0x));
assert_eq!(tv.q0y, hex::encode(q0y));
assert_eq!(tv.q1x, hex::encode(q1x));
assert_eq!(tv.q1y, hex::encode(q1y));
let p0 = AffinePoint::from_encoded_point(&EncodedPoint::from_affine_coordinates(
&q0x, &q0y, false,
))
.unwrap()
.to_curve();
let p1 = AffinePoint::from_encoded_point(&EncodedPoint::from_affine_coordinates(
&q1x, &q1y, false,
))
.unwrap();
let p = (p0 + p1).to_encoded_point(false);
assert_eq!(tv.px, hex::encode(p.x().unwrap()));
assert_eq!(tv.py, hex::encode(p.y().unwrap()));
}
}
}
+33 -24
View File
@@ -5,31 +5,37 @@
// 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::convert::TryInto;
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};
use curve25519_dalek::scalar::Scalar; 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::OutputSizeUser;
use elliptic_curve::hash2curve::{ExpandMsg, ExpandMsgXmd, Expander};
use generic_array::sequence::Concat; use generic_array::sequence::Concat;
use generic_array::typenum::{U32, U64}; use generic_array::typenum::{IsLess, IsLessOrEqual, U256, U32, U64};
use generic_array::GenericArray; use generic_array::GenericArray;
use rand_core::{CryptoRng, RngCore}; use rand_core::{CryptoRng, RngCore};
use super::{expand, Group, STR_HASH_TO_GROUP, STR_HASH_TO_SCALAR}; use super::{Group, STR_HASH_TO_GROUP, STR_HASH_TO_SCALAR};
use crate::voprf::{self, Mode}; use crate::voprf::{self, Mode};
use crate::{Error, Result}; use crate::{CipherSuite, Error, Result};
/// [`Group`] implementation for Ristretto255. /// [`Group`] implementation for Ristretto255.
pub struct Ristretto255; pub struct Ristretto255;
#[cfg(feature = "ristretto255-ciphersuite")]
impl crate::CipherSuite for Ristretto255 {
const ID: u16 = 0x0001;
type Group = Ristretto255;
type Hash = sha2::Sha512;
}
// `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")]
impl Group for Ristretto255 { impl Group for Ristretto255 {
const SUITE_ID: u16 = 0x0001;
type Elem = RistrettoPoint; type Elem = RistrettoPoint;
type ElemLen = U32; type ElemLen = U32;
@@ -40,35 +46,38 @@ impl Group for Ristretto255 {
// 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>( fn hash_to_curve<CS: CipherSuite>(msg: &[&[u8]], mode: Mode) -> Result<Self::Elem>
msg: &[&[u8]], where
mode: Mode, <CS::Hash as OutputSizeUser>::OutputSize:
) -> Result<Self::Elem> { IsLess<U256> + IsLessOrEqual<<CS::Hash as BlockSizeUser>::BlockSize>,
{
let dst = let dst =
GenericArray::from(STR_HASH_TO_GROUP).concat(voprf::get_context_string::<Self>(mode)); GenericArray::from(STR_HASH_TO_GROUP).concat(voprf::get_context_string::<Self>(mode));
let uniform_bytes = expand::expand_message_xmd::<H, U64>(msg, &dst)?; let mut uniform_bytes = GenericArray::<_, U64>::default();
ExpandMsgXmd::<CS::Hash>::expand_message(msg, &dst, 64)
.map_err(|_| Error::PointError)?
.fill_bytes(&mut uniform_bytes);
Ok(RistrettoPoint::from_uniform_bytes(&uniform_bytes.into())) Ok(RistrettoPoint::from_uniform_bytes(&uniform_bytes.into()))
} }
// 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<'a, H: BlockSizeUser + Digest + FixedOutputReset>( fn hash_to_scalar<'a, CS: CipherSuite>(input: &[&[u8]], mode: Mode) -> Result<Self::Scalar>
input: &[&[u8]], where
mode: Mode, <CS::Hash as OutputSizeUser>::OutputSize:
) -> Result<Self::Scalar> { IsLess<U256> + IsLessOrEqual<<CS::Hash as BlockSizeUser>::BlockSize>,
{
let dst = let dst =
GenericArray::from(STR_HASH_TO_SCALAR).concat(voprf::get_context_string::<Self>(mode)); GenericArray::from(STR_HASH_TO_SCALAR).concat(voprf::get_context_string::<Self>(mode));
let uniform_bytes = expand::expand_message_xmd::<H, U64>(input, &dst)?; let mut uniform_bytes = GenericArray::<_, U64>::default();
ExpandMsgXmd::<CS::Hash>::expand_message(input, &dst, 64)
.map_err(|_| Error::PointError)?
.fill_bytes(&mut uniform_bytes);
Ok(Scalar::from_bytes_mod_order_wide( Ok(Scalar::from_bytes_mod_order_wide(&uniform_bytes.into()))
uniform_bytes
.as_slice()
.try_into()
.map_err(|_| Error::HashToCurveError)?,
))
} }
fn base_elem() -> Self::Elem { fn base_elem() -> Self::Elem {
+4 -7
View File
@@ -14,6 +14,8 @@ use crate::{Error, Group, Result};
#[test] #[test]
fn test_group_properties() -> Result<()> { fn test_group_properties() -> Result<()> {
use p256::NistP256;
#[cfg(feature = "ristretto255")] #[cfg(feature = "ristretto255")]
{ {
use crate::Ristretto255; use crate::Ristretto255;
@@ -22,13 +24,8 @@ fn test_group_properties() -> Result<()> {
test_zero_scalar_error::<Ristretto255>()?; test_zero_scalar_error::<Ristretto255>()?;
} }
#[cfg(feature = "p256")] test_identity_element_error::<NistP256>()?;
{ test_zero_scalar_error::<NistP256>()?;
use p256_::NistP256;
test_identity_element_error::<NistP256>()?;
test_zero_scalar_error::<NistP256>()?;
}
Ok(()) Ok(())
} }
+74 -122
View File
@@ -24,8 +24,7 @@
//! We will use the following choices in this example: //! We will use the following choices in this example:
//! //!
//! ```ignore //! ```ignore
//! type Group = voprf::Ristretto255; //! type CipherSuite = voprf::Ristretto255;
//! type Hash = sha2::Sha512;
//! ``` //! ```
//! //!
//! ## Modes of Operation //! ## Modes of Operation
@@ -52,19 +51,15 @@
//! //!
//! ``` //! ```
//! # #[cfg(feature = "ristretto255")] //! # #[cfg(feature = "ristretto255")]
//! # type Group = voprf::Ristretto255; //! # type CipherSuite = voprf::Ristretto255;
//! # #[cfg(feature = "ristretto255")] //! # #[cfg(not(feature = "ristretto255"))]
//! # type Hash = sha2::Sha512; //! # type CipherSuite = p256::NistP256;
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
//! # type Group = p256_::NistP256;
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
//! # type Hash = sha2::Sha256;
//! use rand::rngs::OsRng; //! use rand::rngs::OsRng;
//! use rand::RngCore; //! use rand::RngCore;
//! use voprf::NonVerifiableServer; //! use voprf::NonVerifiableServer;
//! //!
//! let mut server_rng = OsRng; //! let mut server_rng = OsRng;
//! let server = NonVerifiableServer::<Group, Hash>::new(&mut server_rng) //! let server = NonVerifiableServer::<CipherSuite>::new(&mut server_rng)
//! .expect("Unable to construct server"); //! .expect("Unable to construct server");
//! ``` //! ```
//! //!
@@ -78,19 +73,15 @@
//! //!
//! ``` //! ```
//! # #[cfg(feature = "ristretto255")] //! # #[cfg(feature = "ristretto255")]
//! # type Group = voprf::Ristretto255; //! # type CipherSuite = voprf::Ristretto255;
//! # #[cfg(feature = "ristretto255")] //! # #[cfg(not(feature = "ristretto255"))]
//! # type Hash = sha2::Sha512; //! # type CipherSuite = p256::NistP256;
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
//! # type Group = p256_::NistP256;
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
//! # type Hash = sha2::Sha256;
//! use rand::rngs::OsRng; //! use rand::rngs::OsRng;
//! use rand::RngCore; //! use rand::RngCore;
//! use voprf::NonVerifiableClient; //! use voprf::NonVerifiableClient;
//! //!
//! let mut client_rng = OsRng; //! let mut client_rng = OsRng;
//! let client_blind_result = NonVerifiableClient::<Group, Hash>::blind(b"input", &mut client_rng) //! let client_blind_result = NonVerifiableClient::<CipherSuite>::blind(b"input", &mut client_rng)
//! .expect("Unable to construct client"); //! .expect("Unable to construct client");
//! ``` //! ```
//! //!
@@ -104,24 +95,20 @@
//! //!
//! ``` //! ```
//! # #[cfg(feature = "ristretto255")] //! # #[cfg(feature = "ristretto255")]
//! # type Group = voprf::Ristretto255; //! # type CipherSuite = voprf::Ristretto255;
//! # #[cfg(feature = "ristretto255")] //! # #[cfg(not(feature = "ristretto255"))]
//! # type Hash = sha2::Sha512; //! # type CipherSuite = p256::NistP256;
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
//! # type Group = p256_::NistP256;
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
//! # type Hash = sha2::Sha256;
//! # use voprf::NonVerifiableClient; //! # use voprf::NonVerifiableClient;
//! # use rand::{rngs::OsRng, RngCore}; //! # use rand::{rngs::OsRng, RngCore};
//! # //! #
//! # let mut client_rng = OsRng; //! # let mut client_rng = OsRng;
//! # let client_blind_result = NonVerifiableClient::<Group, Hash>::blind( //! # let client_blind_result = NonVerifiableClient::<CipherSuite>::blind(
//! # b"input", //! # b"input",
//! # &mut client_rng, //! # &mut client_rng,
//! # ).expect("Unable to construct client"); //! # ).expect("Unable to construct client");
//! # use voprf::NonVerifiableServer; //! # use voprf::NonVerifiableServer;
//! # let mut server_rng = OsRng; //! # let mut server_rng = OsRng;
//! # let server = NonVerifiableServer::<Group, Hash>::new(&mut server_rng) //! # let server = NonVerifiableServer::<CipherSuite>::new(&mut server_rng)
//! # .expect("Unable to construct server"); //! # .expect("Unable to construct server");
//! let server_evaluate_result = server //! let server_evaluate_result = server
//! .evaluate(&client_blind_result.message, None) //! .evaluate(&client_blind_result.message, None)
@@ -136,24 +123,20 @@
//! //!
//! ``` //! ```
//! # #[cfg(feature = "ristretto255")] //! # #[cfg(feature = "ristretto255")]
//! # type Group = voprf::Ristretto255; //! # type CipherSuite = voprf::Ristretto255;
//! # #[cfg(feature = "ristretto255")] //! # #[cfg(not(feature = "ristretto255"))]
//! # type Hash = sha2::Sha512; //! # type CipherSuite = p256::NistP256;
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
//! # type Group = p256_::NistP256;
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
//! # type Hash = sha2::Sha256;
//! # use voprf::NonVerifiableClient; //! # use voprf::NonVerifiableClient;
//! # use rand::{rngs::OsRng, RngCore}; //! # use rand::{rngs::OsRng, RngCore};
//! # //! #
//! # let mut client_rng = OsRng; //! # let mut client_rng = OsRng;
//! # let client_blind_result = NonVerifiableClient::<Group, Hash>::blind( //! # let client_blind_result = NonVerifiableClient::<CipherSuite>::blind(
//! # b"input", //! # b"input",
//! # &mut client_rng, //! # &mut client_rng,
//! # ).expect("Unable to construct client"); //! # ).expect("Unable to construct client");
//! # use voprf::NonVerifiableServer; //! # use voprf::NonVerifiableServer;
//! # let mut server_rng = OsRng; //! # let mut server_rng = OsRng;
//! # let server = NonVerifiableServer::<Group, Hash>::new(&mut server_rng) //! # let server = NonVerifiableServer::<CipherSuite>::new(&mut server_rng)
//! # .expect("Unable to construct server"); //! # .expect("Unable to construct server");
//! # let server_evaluate_result = server.evaluate( //! # let server_evaluate_result = server.evaluate(
//! # &client_blind_result.message, //! # &client_blind_result.message,
@@ -187,20 +170,16 @@
//! //!
//! ``` //! ```
//! # #[cfg(feature = "ristretto255")] //! # #[cfg(feature = "ristretto255")]
//! # type Group = voprf::Ristretto255; //! # type CipherSuite = voprf::Ristretto255;
//! # #[cfg(feature = "ristretto255")] //! # #[cfg(not(feature = "ristretto255"))]
//! # type Hash = sha2::Sha512; //! # type CipherSuite = p256::NistP256;
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
//! # type Group = p256_::NistP256;
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
//! # type Hash = sha2::Sha256;
//! use rand::rngs::OsRng; //! use rand::rngs::OsRng;
//! use rand::RngCore; //! use rand::RngCore;
//! use voprf::VerifiableServer; //! use voprf::VerifiableServer;
//! //!
//! let mut server_rng = OsRng; //! let mut server_rng = OsRng;
//! let server = //! let server =
//! VerifiableServer::<Group, Hash>::new(&mut server_rng).expect("Unable to construct server"); //! VerifiableServer::<CipherSuite>::new(&mut server_rng).expect("Unable to construct server");
//! //!
//! // To be sent to the client //! // To be sent to the client
//! println!("Server public key: {:?}", server.get_public_key()); //! println!("Server public key: {:?}", server.get_public_key());
@@ -220,19 +199,15 @@
//! //!
//! ``` //! ```
//! # #[cfg(feature = "ristretto255")] //! # #[cfg(feature = "ristretto255")]
//! # type Group = voprf::Ristretto255; //! # type CipherSuite = voprf::Ristretto255;
//! # #[cfg(feature = "ristretto255")] //! # #[cfg(not(feature = "ristretto255"))]
//! # type Hash = sha2::Sha512; //! # type CipherSuite = p256::NistP256;
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
//! # type Group = p256_::NistP256;
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
//! # type Hash = sha2::Sha256;
//! use rand::rngs::OsRng; //! use rand::rngs::OsRng;
//! use rand::RngCore; //! use rand::RngCore;
//! use voprf::VerifiableClient; //! use voprf::VerifiableClient;
//! //!
//! let mut client_rng = OsRng; //! let mut client_rng = OsRng;
//! let client_blind_result = VerifiableClient::<Group, Hash>::blind(b"input", &mut client_rng) //! let client_blind_result = VerifiableClient::<CipherSuite>::blind(b"input", &mut client_rng)
//! .expect("Unable to construct client"); //! .expect("Unable to construct client");
//! ``` //! ```
//! //!
@@ -246,24 +221,20 @@
//! //!
//! ``` //! ```
//! # #[cfg(feature = "ristretto255")] //! # #[cfg(feature = "ristretto255")]
//! # type Group = voprf::Ristretto255; //! # type CipherSuite = voprf::Ristretto255;
//! # #[cfg(feature = "ristretto255")] //! # #[cfg(not(feature = "ristretto255"))]
//! # type Hash = sha2::Sha512; //! # type CipherSuite = p256::NistP256;
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
//! # type Group = p256_::NistP256;
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
//! # type Hash = sha2::Sha256;
//! # use voprf::VerifiableClient; //! # use voprf::VerifiableClient;
//! # use rand::{rngs::OsRng, RngCore}; //! # use rand::{rngs::OsRng, RngCore};
//! # //! #
//! # let mut client_rng = OsRng; //! # let mut client_rng = OsRng;
//! # let client_blind_result = VerifiableClient::<Group, Hash>::blind( //! # let client_blind_result = VerifiableClient::<CipherSuite>::blind(
//! # b"input", //! # b"input",
//! # &mut client_rng, //! # &mut client_rng,
//! # ).expect("Unable to construct client"); //! # ).expect("Unable to construct client");
//! # use voprf::VerifiableServer; //! # use voprf::VerifiableServer;
//! # let mut server_rng = OsRng; //! # let mut server_rng = OsRng;
//! # let server = VerifiableServer::<Group, Hash>::new(&mut server_rng) //! # let server = VerifiableServer::<CipherSuite>::new(&mut server_rng)
//! # .expect("Unable to construct server"); //! # .expect("Unable to construct server");
//! let server_evaluate_result = server //! let server_evaluate_result = server
//! .evaluate(&mut server_rng, &client_blind_result.message, None) //! .evaluate(&mut server_rng, &client_blind_result.message, None)
@@ -279,24 +250,20 @@
//! //!
//! ``` //! ```
//! # #[cfg(feature = "ristretto255")] //! # #[cfg(feature = "ristretto255")]
//! # type Group = voprf::Ristretto255; //! # type CipherSuite = voprf::Ristretto255;
//! # #[cfg(feature = "ristretto255")] //! # #[cfg(not(feature = "ristretto255"))]
//! # type Hash = sha2::Sha512; //! # type CipherSuite = p256::NistP256;
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
//! # type Group = p256_::NistP256;
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
//! # type Hash = sha2::Sha256;
//! # use voprf::VerifiableClient; //! # use voprf::VerifiableClient;
//! # use rand::{rngs::OsRng, RngCore}; //! # use rand::{rngs::OsRng, RngCore};
//! # //! #
//! # let mut client_rng = OsRng; //! # let mut client_rng = OsRng;
//! # let client_blind_result = VerifiableClient::<Group, Hash>::blind( //! # let client_blind_result = VerifiableClient::<CipherSuite>::blind(
//! # b"input", //! # b"input",
//! # &mut client_rng, //! # &mut client_rng,
//! # ).expect("Unable to construct client"); //! # ).expect("Unable to construct client");
//! # use voprf::VerifiableServer; //! # use voprf::VerifiableServer;
//! # let mut server_rng = OsRng; //! # let mut server_rng = OsRng;
//! # let server = VerifiableServer::<Group, Hash>::new(&mut server_rng) //! # let server = VerifiableServer::<CipherSuite>::new(&mut server_rng)
//! # .expect("Unable to construct server"); //! # .expect("Unable to construct server");
//! # let server_evaluate_result = server.evaluate( //! # let server_evaluate_result = server.evaluate(
//! # &mut server_rng, //! # &mut server_rng,
@@ -336,13 +303,9 @@
//! //!
//! ``` //! ```
//! # #[cfg(feature = "ristretto255")] //! # #[cfg(feature = "ristretto255")]
//! # type Group = voprf::Ristretto255; //! # type CipherSuite = voprf::Ristretto255;
//! # #[cfg(feature = "ristretto255")] //! # #[cfg(not(feature = "ristretto255"))]
//! # type Hash = sha2::Sha512; //! # type CipherSuite = p256::NistP256;
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
//! # type Group = p256_::NistP256;
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
//! # type Hash = sha2::Sha256;
//! # use voprf::VerifiableClient; //! # use voprf::VerifiableClient;
//! # use rand::{rngs::OsRng, RngCore}; //! # use rand::{rngs::OsRng, RngCore};
//! # //! #
@@ -350,7 +313,7 @@
//! let mut client_states = vec![]; //! let mut client_states = vec![];
//! let mut client_messages = vec![]; //! let mut client_messages = vec![];
//! for _ in 0..10 { //! for _ in 0..10 {
//! let client_blind_result = VerifiableClient::<Group, Hash>::blind(b"input", &mut client_rng) //! let client_blind_result = VerifiableClient::<CipherSuite>::blind(b"input", &mut client_rng)
//! .expect("Unable to construct client"); //! .expect("Unable to construct client");
//! client_states.push(client_blind_result.state); //! client_states.push(client_blind_result.state);
//! client_messages.push(client_blind_result.message); //! client_messages.push(client_blind_result.message);
@@ -364,13 +327,9 @@
//! //!
//! ``` //! ```
//! # #[cfg(feature = "ristretto255")] //! # #[cfg(feature = "ristretto255")]
//! # type Group = voprf::Ristretto255; //! # type CipherSuite = voprf::Ristretto255;
//! # #[cfg(feature = "ristretto255")] //! # #[cfg(not(feature = "ristretto255"))]
//! # type Hash = sha2::Sha512; //! # type CipherSuite = p256::NistP256;
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
//! # type Group = p256_::NistP256;
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
//! # type Hash = sha2::Sha256;
//! # use voprf::{VerifiableServerBatchEvaluatePrepareResult, VerifiableServerBatchEvaluateFinishResult, VerifiableClient}; //! # use voprf::{VerifiableServerBatchEvaluatePrepareResult, VerifiableServerBatchEvaluateFinishResult, VerifiableClient};
//! # use rand::{rngs::OsRng, RngCore}; //! # use rand::{rngs::OsRng, RngCore};
//! # //! #
@@ -378,7 +337,7 @@
//! # let mut client_states = vec![]; //! # let mut client_states = vec![];
//! # let mut client_messages = vec![]; //! # let mut client_messages = vec![];
//! # for _ in 0..10 { //! # for _ in 0..10 {
//! # let client_blind_result = VerifiableClient::<Group, Hash>::blind( //! # let client_blind_result = VerifiableClient::<CipherSuite>::blind(
//! # b"input", //! # b"input",
//! # &mut client_rng, //! # &mut client_rng,
//! # ).expect("Unable to construct client"); //! # ).expect("Unable to construct client");
@@ -387,7 +346,7 @@
//! # } //! # }
//! # use voprf::VerifiableServer; //! # use voprf::VerifiableServer;
//! let mut server_rng = OsRng; //! let mut server_rng = OsRng;
//! # let server = VerifiableServer::<Group, Hash>::new(&mut server_rng) //! # let server = VerifiableServer::<CipherSuite>::new(&mut server_rng)
//! # .expect("Unable to construct server"); //! # .expect("Unable to construct server");
//! let VerifiableServerBatchEvaluatePrepareResult { //! let VerifiableServerBatchEvaluatePrepareResult {
//! prepared_evaluation_elements, //! prepared_evaluation_elements,
@@ -407,13 +366,9 @@
//! ``` //! ```
//! # #[cfg(feature = "alloc")] { //! # #[cfg(feature = "alloc")] {
//! # #[cfg(feature = "ristretto255")] //! # #[cfg(feature = "ristretto255")]
//! # type Group = voprf::Ristretto255; //! # type CipherSuite = voprf::Ristretto255;
//! # #[cfg(feature = "ristretto255")] //! # #[cfg(not(feature = "ristretto255"))]
//! # type Hash = sha2::Sha512; //! # type CipherSuite = p256::NistP256;
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
//! # type Group = p256_::NistP256;
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
//! # type Hash = sha2::Sha256;
//! # use voprf::{VerifiableServerBatchEvaluateResult, VerifiableClient}; //! # use voprf::{VerifiableServerBatchEvaluateResult, VerifiableClient};
//! # use rand::{rngs::OsRng, RngCore}; //! # use rand::{rngs::OsRng, RngCore};
//! # //! #
@@ -421,7 +376,7 @@
//! # let mut client_states = vec![]; //! # let mut client_states = vec![];
//! # let mut client_messages = vec![]; //! # let mut client_messages = vec![];
//! # for _ in 0..10 { //! # for _ in 0..10 {
//! # let client_blind_result = VerifiableClient::<Group, Hash>::blind( //! # let client_blind_result = VerifiableClient::<CipherSuite>::blind(
//! # b"input", //! # b"input",
//! # &mut client_rng, //! # &mut client_rng,
//! # ).expect("Unable to construct client"); //! # ).expect("Unable to construct client");
@@ -430,7 +385,7 @@
//! # } //! # }
//! # use voprf::VerifiableServer; //! # use voprf::VerifiableServer;
//! let mut server_rng = OsRng; //! let mut server_rng = OsRng;
//! # let server = VerifiableServer::<Group, Hash>::new(&mut server_rng) //! # let server = VerifiableServer::<CipherSuite>::new(&mut server_rng)
//! # .expect("Unable to construct server"); //! # .expect("Unable to construct server");
//! let VerifiableServerBatchEvaluateResult { messages, proof } = server //! let VerifiableServerBatchEvaluateResult { messages, proof } = server
//! .batch_evaluate(&mut server_rng, &client_messages, None) //! .batch_evaluate(&mut server_rng, &client_messages, None)
@@ -446,13 +401,9 @@
//! ``` //! ```
//! # #[cfg(feature = "alloc")] { //! # #[cfg(feature = "alloc")] {
//! # #[cfg(feature = "ristretto255")] //! # #[cfg(feature = "ristretto255")]
//! # type Group = voprf::Ristretto255; //! # type CipherSuite = voprf::Ristretto255;
//! # #[cfg(feature = "ristretto255")] //! # #[cfg(not(feature = "ristretto255"))]
//! # type Hash = sha2::Sha512; //! # type CipherSuite = p256::NistP256;
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
//! # type Group = p256_::NistP256;
//! # #[cfg(all(feature = "p256", not(feature = "ristretto255")))]
//! # type Hash = sha2::Sha256;
//! # use voprf::{VerifiableServerBatchEvaluateResult, VerifiableClient}; //! # use voprf::{VerifiableServerBatchEvaluateResult, VerifiableClient};
//! # use rand::{rngs::OsRng, RngCore}; //! # use rand::{rngs::OsRng, RngCore};
//! # //! #
@@ -460,7 +411,7 @@
//! # let mut client_states = vec![]; //! # let mut client_states = vec![];
//! # let mut client_messages = vec![]; //! # let mut client_messages = vec![];
//! # for _ in 0..10 { //! # for _ in 0..10 {
//! # let client_blind_result = VerifiableClient::<Group, Hash>::blind( //! # let client_blind_result = VerifiableClient::<CipherSuite>::blind(
//! # b"input", //! # b"input",
//! # &mut client_rng, //! # &mut client_rng,
//! # ).expect("Unable to construct client"); //! # ).expect("Unable to construct client");
@@ -469,7 +420,7 @@
//! # } //! # }
//! # use voprf::VerifiableServer; //! # use voprf::VerifiableServer;
//! # let mut server_rng = OsRng; //! # let mut server_rng = OsRng;
//! # let server = VerifiableServer::<Group, Hash>::new(&mut server_rng) //! # let server = VerifiableServer::<CipherSuite>::new(&mut server_rng)
//! # .expect("Unable to construct server"); //! # .expect("Unable to construct server");
//! # let VerifiableServerBatchEvaluateResult { messages, proof } = server //! # let VerifiableServerBatchEvaluateResult { messages, proof } = server
//! # .batch_evaluate(&mut server_rng, &client_messages, None) //! # .batch_evaluate(&mut server_rng, &client_messages, None)
@@ -507,11 +458,6 @@
//! - 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 [`NistP256`](p256_::NistP256) as the
//! underlying group for the [Group] choice and increases the MSRV to 1.56.
//! Note that this is currently an experimental feature ⚠️, and is not yet
//! ready for production use.
//!
//! - The `serde` feature, enabled by default, provides convenience functions //! - 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/).
//! //!
@@ -521,18 +467,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 `ristretto255-ciphersuite` features enables using [`Ristretto255`] as
//! a [`CipherSuite`].
//!
//! - The `ristretto255` feature enables using [`Ristretto255`] as the //! - The `ristretto255` feature enables using [`Ristretto255`] as the
//! underlying group for the [Group] choice. A backend feature, which are //! underlying group for the [Group] choice. A backend feature, which are
//! re-exported from [curve25519-dalek] and allow for selecting the //! re-exported from [curve25519-dalek] and allow for selecting the
//! corresponding backend for the curve arithmetic used, has to be selected, //! corresponding backend for the curve arithmetic used, has to be selected,
//! otherwise compilation will fail. The `ristretto255_u64` feature is //! otherwise compilation will fail. The `ristretto255-u64` feature is
//! included as the default. Other features are mapped as `ristretto255_u32`, //! included as the default. Other features are mapped as `ristretto255-u32`,
//! `ristretto255_fiat_u64` and `ristretto255_fiat_u32`. Any `ristretto255_*` //! `ristretto255-fiat-u64` and `ristretto255-fiat-u32`. Any `ristretto255-*`
//! backend feature will enable the `ristretto255` feature. //! backend feature will enable the `ristretto255` feature.
//! //!
//! - The `ristretto255_simd` feature is re-exported from [curve25519-dalek] and //! - The `ristretto255-simd` feature is re-exported from [curve25519-dalek] 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) //! [curve25519-dalek]: (https://doc.dalek.rs/curve25519_dalek/index.html#backends-and-features)
@@ -548,12 +497,11 @@ extern crate alloc;
#[cfg(feature = "std")] #[cfg(feature = "std")]
extern crate std; extern crate std;
#[macro_use] mod ciphersuite;
mod util;
#[macro_use]
mod serialization;
mod error; mod error;
mod group; mod group;
mod serialization;
mod util;
mod voprf; mod voprf;
#[cfg(test)] #[cfg(test)]
@@ -561,11 +509,15 @@ mod tests;
// Exports // Exports
#[cfg(feature = "ristretto255")] pub use crate::ciphersuite::CipherSuite;
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 = "ristretto255")]
pub use crate::group::Ristretto255;
pub use crate::serialization::{
BlindedElementLen, EvaluationElementLen, NonVerifiableClientLen, NonVerifiableServerLen,
ProofLen, VerifiableClientLen, VerifiableServerLen,
};
#[cfg(feature = "alloc")] #[cfg(feature = "alloc")]
pub use crate::voprf::VerifiableServerBatchEvaluateResult; pub use crate::voprf::VerifiableServerBatchEvaluateResult;
pub use crate::voprf::{ pub use crate::voprf::{
+107 -69
View File
@@ -8,18 +8,17 @@
//! Handles the serialization of each of the components used in the VOPRF //! Handles the serialization of each of the components used in the VOPRF
//! protocol //! protocol
use core::marker::PhantomData;
use core::ops::Add; use core::ops::Add;
use digest::core_api::BlockSizeUser; use digest::core_api::BlockSizeUser;
use digest::{Digest, FixedOutputReset}; use digest::OutputSizeUser;
use generic_array::sequence::Concat; use generic_array::sequence::Concat;
use generic_array::typenum::Sum; use generic_array::typenum::{IsLess, IsLessOrEqual, Sum, U256};
use generic_array::{ArrayLength, GenericArray}; use generic_array::{ArrayLength, GenericArray};
use crate::{ use crate::{
BlindedElement, Error, EvaluationElement, Group, NonVerifiableClient, NonVerifiableServer, BlindedElement, CipherSuite, Error, EvaluationElement, Group, NonVerifiableClient,
Proof, Result, VerifiableClient, VerifiableServer, NonVerifiableServer, Proof, Result, VerifiableClient, VerifiableServer,
}; };
////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////
@@ -27,154 +26,193 @@ use crate::{
// ==================================================== // // ==================================================== //
////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////
impl<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> NonVerifiableClient<G, H> { /// Length of [`NonVerifiableClient`] in bytes for serialization.
pub type NonVerifiableClientLen<CS> = <<CS as CipherSuite>::Group as Group>::ScalarLen;
impl<CS: CipherSuite> NonVerifiableClient<CS>
where
<CS::Hash as OutputSizeUser>::OutputSize:
IsLess<U256> + IsLessOrEqual<<CS::Hash as BlockSizeUser>::BlockSize>,
{
/// Serialization into bytes /// Serialization into bytes
pub fn serialize(&self) -> GenericArray<u8, G::ScalarLen> { pub fn serialize(&self) -> GenericArray<u8, NonVerifiableClientLen<CS>> {
G::serialize_scalar(self.blind) CS::Group::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::deserialize_scalar(&deserialize(&mut input)?)?; let blind = CS::Group::deserialize_scalar(&deserialize(&mut input)?)?;
Ok(Self { Ok(Self { blind })
blind,
hash: PhantomData,
})
} }
} }
impl<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> VerifiableClient<G, H> { /// Length of [`VerifiableClient`] in bytes for serialization.
pub type VerifiableClientLen<CS> = Sum<
<<CS as CipherSuite>::Group as Group>::ScalarLen,
<<CS as CipherSuite>::Group as Group>::ElemLen,
>;
impl<CS: CipherSuite> VerifiableClient<CS>
where
<CS::Hash as OutputSizeUser>::OutputSize:
IsLess<U256> + IsLessOrEqual<<CS::Hash as BlockSizeUser>::BlockSize>,
{
/// Serialization into bytes /// Serialization into bytes
pub fn serialize(&self) -> GenericArray<u8, Sum<G::ScalarLen, G::ElemLen>> pub fn serialize(&self) -> GenericArray<u8, VerifiableClientLen<CS>>
where where
G::ScalarLen: Add<G::ElemLen>, <CS::Group as Group>::ScalarLen: Add<<CS::Group as Group>::ElemLen>,
Sum<G::ScalarLen, G::ElemLen>: ArrayLength<u8>, VerifiableClientLen<CS>: ArrayLength<u8>,
{ {
G::serialize_scalar(self.blind).concat(G::serialize_elem(self.blinded_element)) <CS::Group as Group>::serialize_scalar(self.blind)
.concat(<CS::Group as Group>::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::deserialize_scalar(&deserialize(&mut input)?)?; let blind = CS::Group::deserialize_scalar(&deserialize(&mut input)?)?;
let blinded_element = G::deserialize_elem(&deserialize(&mut input)?)?; let blinded_element = CS::Group::deserialize_elem(&deserialize(&mut input)?)?;
Ok(Self { Ok(Self {
blind, blind,
blinded_element, blinded_element,
hash: PhantomData,
}) })
} }
} }
impl<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> NonVerifiableServer<G, H> { /// Length of [`NonVerifiableServer`] in bytes for serialization.
pub type NonVerifiableServerLen<CS> = <<CS as CipherSuite>::Group as Group>::ScalarLen;
impl<CS: CipherSuite> NonVerifiableServer<CS>
where
<CS::Hash as OutputSizeUser>::OutputSize:
IsLess<U256> + IsLessOrEqual<<CS::Hash as BlockSizeUser>::BlockSize>,
{
/// Serialization into bytes /// Serialization into bytes
pub fn serialize(&self) -> GenericArray<u8, G::ScalarLen> { pub fn serialize(&self) -> GenericArray<u8, NonVerifiableServerLen<CS>> {
G::serialize_scalar(self.sk) CS::Group::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::deserialize_scalar(&deserialize(&mut input)?)?; let sk = CS::Group::deserialize_scalar(&deserialize(&mut input)?)?;
Ok(Self { Ok(Self { sk })
sk,
hash: PhantomData,
})
} }
} }
impl<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> VerifiableServer<G, H> { /// Length of [`VerifiableServer`] in bytes for serialization.
pub type VerifiableServerLen<CS> = Sum<
<<CS as CipherSuite>::Group as Group>::ScalarLen,
<<CS as CipherSuite>::Group as Group>::ElemLen,
>;
impl<CS: CipherSuite> VerifiableServer<CS>
where
<CS::Hash as OutputSizeUser>::OutputSize:
IsLess<U256> + IsLessOrEqual<<CS::Hash as BlockSizeUser>::BlockSize>,
{
/// Serialization into bytes /// Serialization into bytes
pub fn serialize(&self) -> GenericArray<u8, Sum<G::ScalarLen, G::ElemLen>> pub fn serialize(&self) -> GenericArray<u8, VerifiableServerLen<CS>>
where where
G::ScalarLen: Add<G::ElemLen>, <CS::Group as Group>::ScalarLen: Add<<CS::Group as Group>::ElemLen>,
Sum<G::ScalarLen, G::ElemLen>: ArrayLength<u8>, VerifiableServerLen<CS>: ArrayLength<u8>,
{ {
G::serialize_scalar(self.sk).concat(G::serialize_elem(self.pk)) CS::Group::serialize_scalar(self.sk).concat(CS::Group::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::deserialize_scalar(&deserialize(&mut input)?)?; let sk = CS::Group::deserialize_scalar(&deserialize(&mut input)?)?;
let pk = G::deserialize_elem(&deserialize(&mut input)?)?; let pk = CS::Group::deserialize_elem(&deserialize(&mut input)?)?;
Ok(Self { Ok(Self { sk, pk })
sk,
pk,
hash: PhantomData,
})
} }
} }
impl<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> Proof<G, H> { /// Length of [`Proof`] in bytes for serialization.
pub type ProofLen<CS> = Sum<
<<CS as CipherSuite>::Group as Group>::ScalarLen,
<<CS as CipherSuite>::Group as Group>::ScalarLen,
>;
impl<CS: CipherSuite> Proof<CS>
where
<CS::Hash as OutputSizeUser>::OutputSize:
IsLess<U256> + IsLessOrEqual<<CS::Hash as BlockSizeUser>::BlockSize>,
{
/// Serialization into bytes /// Serialization into bytes
pub fn serialize(&self) -> GenericArray<u8, Sum<G::ScalarLen, G::ScalarLen>> pub fn serialize(&self) -> GenericArray<u8, ProofLen<CS>>
where where
G::ScalarLen: Add<G::ScalarLen>, <CS::Group as Group>::ScalarLen: Add<<CS::Group as Group>::ScalarLen>,
Sum<G::ScalarLen, G::ScalarLen>: ArrayLength<u8>, ProofLen<CS>: ArrayLength<u8>,
{ {
G::serialize_scalar(self.c_scalar).concat(G::serialize_scalar(self.s_scalar)) CS::Group::serialize_scalar(self.c_scalar)
.concat(CS::Group::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::deserialize_scalar(&deserialize(&mut input)?)?; let c_scalar = CS::Group::deserialize_scalar(&deserialize(&mut input)?)?;
let s_scalar = G::deserialize_scalar(&deserialize(&mut input)?)?; let s_scalar = CS::Group::deserialize_scalar(&deserialize(&mut input)?)?;
Ok(Proof { Ok(Proof { c_scalar, s_scalar })
c_scalar,
s_scalar,
hash: PhantomData,
})
} }
} }
impl<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> BlindedElement<G, H> { /// Length of [`BlindedElement`] in bytes for serialization.
pub type BlindedElementLen<CS> = <<CS as CipherSuite>::Group as Group>::ElemLen;
impl<CS: CipherSuite> BlindedElement<CS>
where
<CS::Hash as OutputSizeUser>::OutputSize:
IsLess<U256> + IsLessOrEqual<<CS::Hash as BlockSizeUser>::BlockSize>,
{
/// Serialization into bytes /// Serialization into bytes
pub fn serialize(&self) -> GenericArray<u8, G::ElemLen> { pub fn serialize(&self) -> GenericArray<u8, BlindedElementLen<CS>> {
G::serialize_elem(self.value) CS::Group::serialize_elem(self.0)
} }
/// 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::deserialize_elem(&deserialize(&mut input)?)?; let value = CS::Group::deserialize_elem(&deserialize(&mut input)?)?;
Ok(Self { Ok(Self(value))
value,
hash: PhantomData,
})
} }
} }
impl<G: Group, H: BlockSizeUser + Digest + FixedOutputReset> EvaluationElement<G, H> { /// Length of [`EvaluationElement`] in bytes for serialization.
pub type EvaluationElementLen<CS> = <<CS as CipherSuite>::Group as Group>::ElemLen;
impl<CS: CipherSuite> EvaluationElement<CS>
where
<CS::Hash as OutputSizeUser>::OutputSize:
IsLess<U256> + IsLessOrEqual<<CS::Hash as BlockSizeUser>::BlockSize>,
{
/// Serialization into bytes /// Serialization into bytes
pub fn serialize(&self) -> GenericArray<u8, G::ElemLen> { pub fn serialize(&self) -> GenericArray<u8, EvaluationElementLen<CS>> {
G::serialize_elem(self.value) CS::Group::serialize_elem(self.0)
} }
/// 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::deserialize_elem(&deserialize(&mut input)?)?; let value = CS::Group::deserialize_elem(&deserialize(&mut input)?)?;
Ok(Self { Ok(Self(value))
value,
hash: PhantomData,
})
} }
} }
+94 -84
View File
@@ -11,16 +11,16 @@ use alloc::vec::Vec;
use core::ops::Add; use core::ops::Add;
use digest::core_api::BlockSizeUser; use digest::core_api::BlockSizeUser;
use digest::{Digest, FixedOutputReset}; use digest::OutputSizeUser;
use generic_array::typenum::Sum; use generic_array::typenum::{IsLess, IsLessOrEqual, Sum, U256};
use generic_array::{ArrayLength, GenericArray}; use generic_array::{ArrayLength, GenericArray};
use json::JsonValue; use json::JsonValue;
use crate::tests::mock_rng::CycleRng; use crate::tests::mock_rng::CycleRng;
use crate::tests::parser::*; use crate::tests::parser::*;
use crate::{ use crate::{
BlindedElement, EvaluationElement, Group, NonVerifiableClient, NonVerifiableServer, Proof, BlindedElement, CipherSuite, EvaluationElement, Group, NonVerifiableClient,
Result, VerifiableClient, VerifiableServer, NonVerifiableServer, Proof, Result, VerifiableClient, VerifiableServer,
}; };
#[derive(Debug)] #[derive(Debug)]
@@ -85,13 +85,13 @@ macro_rules! json_to_test_vectors {
#[test] #[test]
fn test_vectors() -> Result<()> { fn test_vectors() -> Result<()> {
use p256::NistP256;
let rfc = json::parse(rfc_to_json(super::voprf_vectors::VECTORS).as_str()) let rfc = json::parse(rfc_to_json(super::voprf_vectors::VECTORS).as_str())
.expect("Could not parse json"); .expect("Could not parse json");
#[cfg(feature = "ristretto255")] #[cfg(feature = "ristretto255")]
{ {
use sha2::Sha512;
use crate::Ristretto255; use crate::Ristretto255;
let ristretto_base_tvs = json_to_test_vectors!( let ristretto_base_tvs = json_to_test_vectors!(
@@ -106,93 +106,94 @@ fn test_vectors() -> Result<()> {
String::from("Verifiable") String::from("Verifiable")
); );
test_base_seed_to_key::<Ristretto255, Sha512>(&ristretto_base_tvs)?; test_base_seed_to_key::<Ristretto255>(&ristretto_base_tvs)?;
test_base_blind::<Ristretto255, Sha512>(&ristretto_base_tvs)?; test_base_blind::<Ristretto255>(&ristretto_base_tvs)?;
test_base_evaluate::<Ristretto255, Sha512>(&ristretto_base_tvs)?; test_base_evaluate::<Ristretto255>(&ristretto_base_tvs)?;
test_base_finalize::<Ristretto255, Sha512>(&ristretto_base_tvs)?; test_base_finalize::<Ristretto255>(&ristretto_base_tvs)?;
test_verifiable_seed_to_key::<Ristretto255, Sha512>(&ristretto_verifiable_tvs)?; test_verifiable_seed_to_key::<Ristretto255>(&ristretto_verifiable_tvs)?;
test_verifiable_blind::<Ristretto255, Sha512>(&ristretto_verifiable_tvs)?; test_verifiable_blind::<Ristretto255>(&ristretto_verifiable_tvs)?;
test_verifiable_evaluate::<Ristretto255, Sha512>(&ristretto_verifiable_tvs)?; test_verifiable_evaluate::<Ristretto255>(&ristretto_verifiable_tvs)?;
test_verifiable_finalize::<Ristretto255, Sha512>(&ristretto_verifiable_tvs)?; test_verifiable_finalize::<Ristretto255>(&ristretto_verifiable_tvs)?;
} }
#[cfg(feature = "p256")] let p256base_tvs =
{ json_to_test_vectors!(rfc, String::from("P-256, SHA-256"), String::from("Base"));
use p256_::NistP256;
use sha2::Sha256;
let p256_base_tvs = let p256verifiable_tvs = json_to_test_vectors!(
json_to_test_vectors!(rfc, String::from("P-256, SHA-256"), String::from("Base")); rfc,
String::from("P-256, SHA-256"),
String::from("Verifiable")
);
let p256_verifiable_tvs = json_to_test_vectors!( test_base_seed_to_key::<NistP256>(&p256base_tvs)?;
rfc, test_base_blind::<NistP256>(&p256base_tvs)?;
String::from("P-256, SHA-256"), test_base_evaluate::<NistP256>(&p256base_tvs)?;
String::from("Verifiable") test_base_finalize::<NistP256>(&p256base_tvs)?;
);
test_base_seed_to_key::<NistP256, Sha256>(&p256_base_tvs)?; test_verifiable_seed_to_key::<NistP256>(&p256verifiable_tvs)?;
test_base_blind::<NistP256, Sha256>(&p256_base_tvs)?; test_verifiable_blind::<NistP256>(&p256verifiable_tvs)?;
test_base_evaluate::<NistP256, Sha256>(&p256_base_tvs)?; test_verifiable_evaluate::<NistP256>(&p256verifiable_tvs)?;
test_base_finalize::<NistP256, Sha256>(&p256_base_tvs)?; test_verifiable_finalize::<NistP256>(&p256verifiable_tvs)?;
test_verifiable_seed_to_key::<NistP256, Sha256>(&p256_verifiable_tvs)?;
test_verifiable_blind::<NistP256, Sha256>(&p256_verifiable_tvs)?;
test_verifiable_evaluate::<NistP256, Sha256>(&p256_verifiable_tvs)?;
test_verifiable_finalize::<NistP256, Sha256>(&p256_verifiable_tvs)?;
}
Ok(()) Ok(())
} }
fn test_base_seed_to_key<G: Group, H: BlockSizeUser + Digest + FixedOutputReset>( fn test_base_seed_to_key<CS: CipherSuite>(tvs: &[VOPRFTestVectorParameters]) -> Result<()>
tvs: &[VOPRFTestVectorParameters], where
) -> Result<()> { <CS::Hash as OutputSizeUser>::OutputSize:
IsLess<U256> + IsLessOrEqual<<CS::Hash as BlockSizeUser>::BlockSize>,
{
for parameters in tvs { for parameters in tvs {
let server = NonVerifiableServer::<G, H>::new_from_seed(&parameters.seed)?; let server = NonVerifiableServer::<CS>::new_from_seed(&parameters.seed)?;
assert_eq!( assert_eq!(
&parameters.sksm, &parameters.sksm,
&G::serialize_scalar(server.get_private_key()).to_vec() &CS::Group::serialize_scalar(server.get_private_key()).to_vec()
); );
} }
Ok(()) Ok(())
} }
fn test_verifiable_seed_to_key<G: Group, H: BlockSizeUser + Digest + FixedOutputReset>( fn test_verifiable_seed_to_key<CS: CipherSuite>(tvs: &[VOPRFTestVectorParameters]) -> Result<()>
tvs: &[VOPRFTestVectorParameters], where
) -> Result<()> { <CS::Hash as OutputSizeUser>::OutputSize:
IsLess<U256> + IsLessOrEqual<<CS::Hash as BlockSizeUser>::BlockSize>,
{
for parameters in tvs { for parameters in tvs {
let server = VerifiableServer::<G, H>::new_from_seed(&parameters.seed)?; let server = VerifiableServer::<CS>::new_from_seed(&parameters.seed)?;
assert_eq!( assert_eq!(
&parameters.sksm, &parameters.sksm,
&G::serialize_scalar(server.get_private_key()).to_vec() &CS::Group::serialize_scalar(server.get_private_key()).to_vec()
); );
assert_eq!( assert_eq!(
&parameters.pksm, &parameters.pksm,
G::serialize_elem(server.get_public_key()).as_slice() CS::Group::serialize_elem(server.get_public_key()).as_slice()
); );
} }
Ok(()) Ok(())
} }
// Tests input -> blind, blinded_element // Tests input -> blind, blinded_element
fn test_base_blind<G: Group, H: BlockSizeUser + Digest + FixedOutputReset>( fn test_base_blind<CS: CipherSuite>(tvs: &[VOPRFTestVectorParameters]) -> Result<()>
tvs: &[VOPRFTestVectorParameters], where
) -> Result<()> { <CS::Hash as OutputSizeUser>::OutputSize:
IsLess<U256> + IsLessOrEqual<<CS::Hash as BlockSizeUser>::BlockSize>,
{
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 = CS::Group::deserialize_scalar(&GenericArray::clone_from_slice(
G::deserialize_scalar(&GenericArray::clone_from_slice(&parameters.blind[i]))?; &parameters.blind[i],
let client_result = NonVerifiableClient::<G, H>::deterministic_blind_unchecked( ))?;
let client_result = NonVerifiableClient::<CS>::deterministic_blind_unchecked(
&parameters.input[i], &parameters.input[i],
blind, blind,
)?; )?;
assert_eq!( assert_eq!(
&parameters.blind[i], &parameters.blind[i],
&G::serialize_scalar(client_result.state.blind).to_vec() &CS::Group::serialize_scalar(client_result.state.blind).to_vec()
); );
assert_eq!( assert_eq!(
parameters.blinded_element[i].as_slice(), parameters.blinded_element[i].as_slice(),
@@ -204,21 +205,22 @@ fn test_base_blind<G: Group, H: BlockSizeUser + Digest + FixedOutputReset>(
} }
// Tests input -> blind, blinded_element // Tests input -> blind, blinded_element
fn test_verifiable_blind<G: Group, H: BlockSizeUser + Digest + FixedOutputReset>( fn test_verifiable_blind<CS: CipherSuite>(tvs: &[VOPRFTestVectorParameters]) -> Result<()>
tvs: &[VOPRFTestVectorParameters], where
) -> Result<()> { <CS::Hash as OutputSizeUser>::OutputSize:
IsLess<U256> + IsLessOrEqual<<CS::Hash as BlockSizeUser>::BlockSize>,
{
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 = CS::Group::deserialize_scalar(&GenericArray::clone_from_slice(
G::deserialize_scalar(&GenericArray::clone_from_slice(&parameters.blind[i]))?; &parameters.blind[i],
let client_blind_result = VerifiableClient::<G, H>::deterministic_blind_unchecked( ))?;
&parameters.input[i], let client_blind_result =
blind, VerifiableClient::<CS>::deterministic_blind_unchecked(&parameters.input[i], blind)?;
)?;
assert_eq!( assert_eq!(
&parameters.blind[i], &parameters.blind[i],
&G::serialize_scalar(client_blind_result.state.get_blind()).to_vec() &CS::Group::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(),
@@ -230,12 +232,14 @@ fn test_verifiable_blind<G: Group, H: BlockSizeUser + Digest + FixedOutputReset>
} }
// Tests sksm, blinded_element -> evaluation_element // Tests sksm, blinded_element -> evaluation_element
fn test_base_evaluate<G: Group, H: BlockSizeUser + Digest + FixedOutputReset>( fn test_base_evaluate<CS: CipherSuite>(tvs: &[VOPRFTestVectorParameters]) -> Result<()>
tvs: &[VOPRFTestVectorParameters], where
) -> Result<()> { <CS::Hash as OutputSizeUser>::OutputSize:
IsLess<U256> + IsLessOrEqual<<CS::Hash as BlockSizeUser>::BlockSize>,
{
for parameters in tvs { for parameters in tvs {
for i in 0..parameters.input.len() { for i in 0..parameters.input.len() {
let server = NonVerifiableServer::<G, H>::new_with_key(&parameters.sksm)?; let server = NonVerifiableServer::<CS>::new_with_key(&parameters.sksm)?;
let server_result = server.evaluate( let server_result = server.evaluate(
&BlindedElement::deserialize(&parameters.blinded_element[i])?, &BlindedElement::deserialize(&parameters.blinded_element[i])?,
Some(&parameters.info), Some(&parameters.info),
@@ -250,12 +254,12 @@ fn test_base_evaluate<G: Group, H: BlockSizeUser + Digest + FixedOutputReset>(
Ok(()) Ok(())
} }
fn test_verifiable_evaluate<G: Group, H: BlockSizeUser + Digest + FixedOutputReset>( fn test_verifiable_evaluate<CS: CipherSuite>(tvs: &[VOPRFTestVectorParameters]) -> Result<()>
tvs: &[VOPRFTestVectorParameters],
) -> Result<()>
where where
G::ScalarLen: Add<G::ScalarLen>, <CS::Hash as OutputSizeUser>::OutputSize:
Sum<G::ScalarLen, G::ScalarLen>: ArrayLength<u8>, IsLess<U256> + IsLessOrEqual<<CS::Hash as BlockSizeUser>::BlockSize>,
<CS::Group as Group>::ScalarLen: Add<<CS::Group as Group>::ScalarLen>,
Sum<<CS::Group as Group>::ScalarLen, <CS::Group as Group>::ScalarLen>: ArrayLength<u8>,
{ {
use crate::{ use crate::{
VerifiableServerBatchEvaluateFinishResult, VerifiableServerBatchEvaluatePrepareResult, VerifiableServerBatchEvaluateFinishResult, VerifiableServerBatchEvaluatePrepareResult,
@@ -263,7 +267,7 @@ where
for parameters in tvs { for parameters in tvs {
let mut rng = CycleRng::new(parameters.proof_random_scalar.clone()); let mut rng = CycleRng::new(parameters.proof_random_scalar.clone());
let server = VerifiableServer::<G, H>::new_with_key(&parameters.sksm)?; let server = VerifiableServer::<CS>::new_with_key(&parameters.sksm)?;
let mut blinded_elements = vec![]; let mut blinded_elements = vec![];
for blinded_element_bytes in &parameters.blinded_element { for blinded_element_bytes in &parameters.blinded_element {
@@ -294,12 +298,14 @@ where
} }
// Tests input, blind, evaluation_element -> output // Tests input, blind, evaluation_element -> output
fn test_base_finalize<G: Group, H: BlockSizeUser + Digest + FixedOutputReset>( fn test_base_finalize<CS: CipherSuite>(tvs: &[VOPRFTestVectorParameters]) -> Result<()>
tvs: &[VOPRFTestVectorParameters], where
) -> Result<()> { <CS::Hash as OutputSizeUser>::OutputSize:
IsLess<U256> + IsLessOrEqual<<CS::Hash as BlockSizeUser>::BlockSize>,
{
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::deserialize_scalar( let client = NonVerifiableClient::<CS>::from_blind(CS::Group::deserialize_scalar(
&GenericArray::clone_from_slice(&parameters.blind[i]), &GenericArray::clone_from_slice(&parameters.blind[i]),
)?); )?);
@@ -315,15 +321,19 @@ fn test_base_finalize<G: Group, H: BlockSizeUser + Digest + FixedOutputReset>(
Ok(()) Ok(())
} }
fn test_verifiable_finalize<G: Group, H: BlockSizeUser + Digest + FixedOutputReset>( fn test_verifiable_finalize<CS: CipherSuite>(tvs: &[VOPRFTestVectorParameters]) -> Result<()>
tvs: &[VOPRFTestVectorParameters], where
) -> Result<()> { <CS::Hash as OutputSizeUser>::OutputSize:
IsLess<U256> + IsLessOrEqual<<CS::Hash as BlockSizeUser>::BlockSize>,
{
for parameters in tvs { for parameters in tvs {
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::<CS>::from_blind_and_element(
G::deserialize_scalar(&GenericArray::clone_from_slice(&parameters.blind[i]))?, CS::Group::deserialize_scalar(&GenericArray::clone_from_slice(
G::deserialize_elem(&GenericArray::clone_from_slice( &parameters.blind[i],
))?,
CS::Group::deserialize_elem(&GenericArray::clone_from_slice(
&parameters.blinded_element[i], &parameters.blinded_element[i],
))?, ))?,
); );
@@ -341,7 +351,7 @@ fn test_verifiable_finalize<G: Group, H: BlockSizeUser + Digest + FixedOutputRes
&clients, &clients,
&messages, &messages,
&Proof::deserialize(&parameters.proof)?, &Proof::deserialize(&parameters.proof)?,
G::deserialize_elem(GenericArray::from_slice(&parameters.pksm))?, CS::Group::deserialize_elem(GenericArray::from_slice(&parameters.pksm))?,
Some(&parameters.info), Some(&parameters.info),
)?; )?;
+3 -5
View File
@@ -40,12 +40,10 @@ mod unit_tests {
($item:ident, $bytes:ident) => { ($item:ident, $bytes:ident) => {
#[cfg(feature = "ristretto255")] #[cfg(feature = "ristretto255")]
{ {
let _ = $item::<crate::Ristretto255, sha2::Sha512>::deserialize(&$bytes[..]); let _ = $item::<crate::Ristretto255>::deserialize(&$bytes[..]);
}
#[cfg(feature = "p256")]
{
let _ = $item::<p256_::NistP256, sha2::Sha256>::deserialize(&$bytes[..]);
} }
let _ = $item::<p256::NistP256>::deserialize(&$bytes[..]);
}; };
} }
+513 -462
View File
File diff suppressed because it is too large Load Diff