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:
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
@@ -7,17 +7,15 @@
|
||||
|
||||
//! Defines the Group trait to specify the underlying prime order group
|
||||
|
||||
#[cfg(any(feature = "ristretto255", feature = "p256",))]
|
||||
mod expand;
|
||||
#[cfg(feature = "p256")]
|
||||
mod p256;
|
||||
mod elliptic_curve;
|
||||
#[cfg(feature = "ristretto255")]
|
||||
mod ristretto;
|
||||
|
||||
use core::ops::{Add, Mul, Sub};
|
||||
|
||||
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 rand_core::{CryptoRng, RngCore};
|
||||
#[cfg(feature = "ristretto255")]
|
||||
@@ -26,7 +24,7 @@ use subtle::ConstantTimeEq;
|
||||
use zeroize::Zeroize;
|
||||
|
||||
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_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
|
||||
/// subgroup is noted additively — as in the draft RFC — in this trait.
|
||||
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
|
||||
type Elem: Copy
|
||||
+ Sized
|
||||
+ ConstantTimeEq
|
||||
+ 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
|
||||
type ElemLen: ArrayLength<u8> + 'static;
|
||||
|
||||
/// The type of base field scalars
|
||||
type Scalar: Zeroize
|
||||
type Scalar: ConstantTimeEq
|
||||
+ Copy
|
||||
+ ConstantTimeEq
|
||||
+ Zeroize
|
||||
+ 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
|
||||
type ScalarLen: ArrayLength<u8> + 'static;
|
||||
|
||||
/// transforms a password and domain separation tag (DST) into a curve point
|
||||
fn hash_to_curve<H: BlockSizeUser + Digest + FixedOutputReset>(
|
||||
msg: &[&[u8]],
|
||||
mode: Mode,
|
||||
) -> Result<Self::Elem>;
|
||||
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>;
|
||||
|
||||
/// Hashes a slice of pseudo-random bytes to a scalar
|
||||
fn hash_to_scalar<H: BlockSizeUser + Digest + FixedOutputReset>(
|
||||
input: &[&[u8]],
|
||||
mode: Mode,
|
||||
) -> Result<Self::Scalar>;
|
||||
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>;
|
||||
|
||||
/// Get the base point for the group
|
||||
fn base_elem() -> Self::Elem;
|
||||
|
||||
@@ -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
@@ -5,31 +5,37 @@
|
||||
// License, Version 2.0 found in the LICENSE-APACHE file in the root directory
|
||||
// of this source tree.
|
||||
|
||||
use core::convert::TryInto;
|
||||
|
||||
use curve25519_dalek::constants::RISTRETTO_BASEPOINT_POINT;
|
||||
use curve25519_dalek::ristretto::{CompressedRistretto, RistrettoPoint};
|
||||
use curve25519_dalek::scalar::Scalar;
|
||||
use curve25519_dalek::traits::Identity;
|
||||
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::typenum::{U32, U64};
|
||||
use generic_array::typenum::{IsLess, IsLessOrEqual, U256, U32, U64};
|
||||
use generic_array::GenericArray;
|
||||
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::{Error, Result};
|
||||
use crate::{CipherSuite, Error, Result};
|
||||
|
||||
/// [`Group`] implementation for 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(feature = "ristretto255")]
|
||||
impl Group for Ristretto255 {
|
||||
const SUITE_ID: u16 = 0x0001;
|
||||
|
||||
type Elem = RistrettoPoint;
|
||||
|
||||
type ElemLen = U32;
|
||||
@@ -40,35 +46,38 @@ impl Group for Ristretto255 {
|
||||
|
||||
// Implements the `hash_to_ristretto255()` function from
|
||||
// https://www.ietf.org/archive/id/draft-irtf-cfrg-hash-to-curve-10.txt
|
||||
fn hash_to_curve<H: BlockSizeUser + Digest + FixedOutputReset>(
|
||||
msg: &[&[u8]],
|
||||
mode: Mode,
|
||||
) -> Result<Self::Elem> {
|
||||
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::<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()))
|
||||
}
|
||||
|
||||
// Implements the `HashToScalar()` function from
|
||||
// https://www.ietf.org/archive/id/draft-irtf-cfrg-voprf-07.html#section-4.1
|
||||
fn hash_to_scalar<'a, H: BlockSizeUser + Digest + FixedOutputReset>(
|
||||
input: &[&[u8]],
|
||||
mode: Mode,
|
||||
) -> Result<Self::Scalar> {
|
||||
fn hash_to_scalar<'a, 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::<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(
|
||||
uniform_bytes
|
||||
.as_slice()
|
||||
.try_into()
|
||||
.map_err(|_| Error::HashToCurveError)?,
|
||||
))
|
||||
Ok(Scalar::from_bytes_mod_order_wide(&uniform_bytes.into()))
|
||||
}
|
||||
|
||||
fn base_elem() -> Self::Elem {
|
||||
|
||||
+4
-7
@@ -14,6 +14,8 @@ use crate::{Error, Group, Result};
|
||||
|
||||
#[test]
|
||||
fn test_group_properties() -> Result<()> {
|
||||
use p256::NistP256;
|
||||
|
||||
#[cfg(feature = "ristretto255")]
|
||||
{
|
||||
use crate::Ristretto255;
|
||||
@@ -22,13 +24,8 @@ fn test_group_properties() -> Result<()> {
|
||||
test_zero_scalar_error::<Ristretto255>()?;
|
||||
}
|
||||
|
||||
#[cfg(feature = "p256")]
|
||||
{
|
||||
use p256_::NistP256;
|
||||
|
||||
test_identity_element_error::<NistP256>()?;
|
||||
test_zero_scalar_error::<NistP256>()?;
|
||||
}
|
||||
test_identity_element_error::<NistP256>()?;
|
||||
test_zero_scalar_error::<NistP256>()?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user