Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Constant-time scalar sampling & hash-to-scalar #55

Merged
merged 10 commits into from
Feb 25, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
713 changes: 409 additions & 304 deletions Cargo.lock

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ is an elliptic point on secp256k1 curve.
## Exposed API

Limited API is exposed: elliptic point arithmetic (points addition, negation, multiplying at scalar), scalar
arithmetic (addition, multiplication, inverse modulo prime group order), and encode/decode to bytes represenstation.
arithmetic (addition, multiplication, inverse modulo prime group order), and encode/decode to bytes representation.

Hash to curve, hash to scalar primitives, accessing affine coordinates of points are available for some curves through
`FromHash` and other traits.
Expand Down
26 changes: 26 additions & 0 deletions docs/nonzero_scalar_random.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
Generates random non-zero scalar

# Guarantees
1. Uniform distribution \
Output scalar is uniformly distributed (given that provided PRNG outputs uniformly
distributed bytes), with possible negligible bias respective to curve target security
level
2. Constant-time \
Random generation algorithm does not branch on input randomness, and in particular,
it does not use rejection-sampling strategy (might not be the case with negligible
probability respective to the curve target security level[^1])
3. Reproducible \
When random generation algorithm is given the same PRNG with the same seed, it always
outputs the same scalar on all platforms

If you don't need constant-time/reproducibility properties, you can use [`random_vartime`](
Self::random_vartime) instead which is typically faster.

[^1]: we use rejection-sampling strategy in case if a zero scalar is generated, however,
probability of that happening is negligible

# Panics
Panics if randomness source returned 100 zero scalars in a row. It happens with negligible
probability, e.g. for secp256k1 curve it's about $2^{-25600}$, which practically means that
randomness source is broken.

16 changes: 16 additions & 0 deletions docs/nonzero_scalar_random_vartime.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
Generates random non-zero scalar using variable time algorithm

# Guarantees
1. Uniform distribution \
Output scalar is uniformly distributed (given that provided PRNG outputs uniformly
distributed bytes), with possible negligible bias respective to curve target security
level

Unlike [`random`](Self::random) method, this one **is not** constant-time nor reproducible, but
often it's faster.

# Panics
Panics if randomness source returned 100 zero scalars in a row. It happens with negligible
probability, e.g. for secp256k1 curve it's about $2^{-25600}$, which practically means that
randomness source is broken.

6 changes: 6 additions & 0 deletions generic-ec-core/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
## v0.3.0
* Rename `Samplable` trait into `FromUniformBytes` and change it so it
accepts a uniform byte array instead of `impl RngCore` [#55]

[#55]: https://github.com/LFDT-Lockness/generic-ec/pull/55

## v0.2.3
* Add `NoInvalidPoints` trait [#50]

Expand Down
4 changes: 2 additions & 2 deletions generic-ec-core/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "generic-ec-core"
version = "0.2.3"
version = "0.3.0"
edition = "2021"
license = "MIT OR Apache-2.0"
repository = "https://github.com/LFDT-Lockness/generic-ec"
Expand All @@ -11,8 +11,8 @@ description = "Core traits of `generic-ec` crate"
[dependencies]
generic-array.workspace = true
subtle.workspace = true
rand_core.workspace = true
zeroize.workspace = true
rand_core.workspace = true
serde = { workspace = true, features = ["derive"], optional = true }

[features]
Expand Down
60 changes: 54 additions & 6 deletions generic-ec-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ use core::fmt::Debug;
use core::hash::Hash;

use generic_array::{ArrayLength, GenericArray};
use rand_core::RngCore;
use subtle::{Choice, ConditionallySelectable, ConstantTimeEq, CtOption};
use zeroize::Zeroize;

Expand Down Expand Up @@ -51,7 +50,8 @@ pub trait Curve: Debug + Copy + Eq + Ord + Hash + Default + Sync + Send + 'stati
+ Invertible
+ Zero
+ One
+ Samplable
+ FromUniformBytes
+ SamplableVartime
+ Zeroize
+ Copy
+ Eq
Expand Down Expand Up @@ -128,10 +128,58 @@ pub trait One {
fn is_one(x: &Self) -> Choice;
}

/// Type can be uniformely sampled from source of randomness
pub trait Samplable {
/// Uniformely samples a random value of `Self`
fn random<R: RngCore>(rng: &mut R) -> Self;
/// Uniform instance of the type can be derived from uniformly distributed byte array
pub trait FromUniformBytes {
/// Byte array that can be converted into instance of `Self` via [`FromUniformBytes::from_uniform_bytes`]
type Bytes: ByteArray;

/// Maps uniformly distributed bytes array to uniformly distributed instance of `Self`.
///
/// Instead of taking a source of randomness directly, this implementation takes a byte array, that was
/// populated from the source of randomness, and outputs a random element.
///
/// ## Guarantees
/// When `bytes` are uniformly distributed, output distribution must be indistinguishable from uniform,
/// with bias respective to the security level of the curve, meaning that any instance of the type can
/// appear with equal probability.
///
/// Implementation is reproducible: the same input `bytes` give the same output on all platforms.
///
/// Implementation is constant-time: there's no branching on the input.
///
/// ## Implementation details
/// This trait is required to be implemented for scalars. It's recommended to take approach described in
/// "5. Hashing to Finite Field" of [RFC9380]:
///
/// 1. Take a uniform bytestring of `L` bytes, where
/// ```text
/// L = ceil((ceil(log2(q)) + k) / 8)
/// ```
///
/// `q` is prime (sub)group order, and `k` is target security level in bits
/// 2. Interpret the bytestring as big-endian/little-endian encoding of the integer, and reduce it modulo `q`
///
/// The output is then guaranteed to have a bias at most 2^-k.
///
/// [RFC9380]: https://www.rfc-editor.org/rfc/rfc9380.html#name-hashing-to-a-finite-field
fn from_uniform_bytes(bytes: &Self::Bytes) -> Self;
}

/// Samples a uniform instance of the type from source of randomness
pub trait SamplableVartime {
/// Samples a uniform instance of the type from source of randomness
///
/// ## Guarantees
/// If output of provided PRNG is uniform, then the output of this function is uniformly
/// distributed (with bias respective to the security level of the curve), meaning that
/// any instance of the type can appear with equal probability.
///
/// Implementation **is not** reproducible: it may lead to different results on different
/// platform and/or instances of the program even if the same `rng` is used with the same
/// seed.
///
/// Implementation **is not** constant-time: it likely uses reject-sample strategy.
fn random_vartime(rng: &mut impl rand_core::RngCore) -> Self;
}

/// Checks whether the point is on curve
Expand Down
5 changes: 5 additions & 0 deletions generic-ec-curves/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
## v0.3.0
* Update `generic-ec-core` to v0.3 [#55]

[#55]: https://github.com/LFDT-Lockness/generic-ec/pull/55

## v0.2.4
* Implement `NoInvalidPoints` for prime order curves [#50]

Expand Down
4 changes: 2 additions & 2 deletions generic-ec-curves/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "generic-ec-curves"
version = "0.2.4"
version = "0.3.0"
edition = "2021"
license = "MIT OR Apache-2.0"
description = "Elliptic curves for `generic-ec` crate"
Expand All @@ -9,7 +9,7 @@ repository = "https://github.com/LFDT-Lockness/generic-ec"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
generic-ec-core = { version = "0.2.3", path = "../generic-ec-core", default-features = false }
generic-ec-core = { version = "0.3.0", path = "../generic-ec-core", default-features = false }

subtle.workspace = true
rand_core.workspace = true
Expand Down
26 changes: 16 additions & 10 deletions generic-ec-curves/benches/curves.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ fn bench_curve<E: Curve>(
});
g.bench_function("[k]P", |b| {
b.iter_batched(
|| (E::Scalar::random(rng), random_point::<E>(rng)),
|| (random_scalar::<E>(rng), random_point::<E>(rng)),
|(k, p)| E::Scalar::mul(&k, &p),
criterion::BatchSize::SmallInput,
);
Expand Down Expand Up @@ -81,53 +81,53 @@ fn bench_curve<E: Curve>(

g.bench_function("a+b", |b| {
b.iter_batched(
|| (E::Scalar::random(rng), E::Scalar::random(rng)),
|| (random_scalar::<E>(rng), random_scalar::<E>(rng)),
|(a, b)| E::Scalar::add(&a, &b),
criterion::BatchSize::SmallInput,
);
});
g.bench_function("a*b", |b| {
b.iter_batched(
|| (E::Scalar::random(rng), E::Scalar::random(rng)),
|| (random_scalar::<E>(rng), random_scalar::<E>(rng)),
|(a, b)| E::Scalar::mul(&a, &b),
criterion::BatchSize::SmallInput,
);
});
g.bench_function("inv(a)", |b| {
b.iter_batched(
|| E::Scalar::random(rng),
|| random_scalar::<E>(rng),
|a| E::Scalar::invert(&a),
criterion::BatchSize::SmallInput,
);
});
g.bench_function("RandomScalar", |b| {
b.iter(|| E::Scalar::random(rng));
b.iter(|| random_scalar::<E>(rng));
});

g.bench_function("EncodeScalarBE", |b| {
b.iter_batched(
|| E::Scalar::random(rng),
|| random_scalar::<E>(rng),
|a| a.to_be_bytes(),
criterion::BatchSize::SmallInput,
);
});
g.bench_function("EncodeScalarLE", |b| {
b.iter_batched(
|| E::Scalar::random(rng),
|| random_scalar::<E>(rng),
|a| a.to_le_bytes(),
criterion::BatchSize::SmallInput,
);
});
g.bench_function("DecodeScalarBE", |b| {
b.iter_batched(
|| E::Scalar::random(rng).to_be_bytes(),
|| random_scalar::<E>(rng).to_be_bytes(),
|bytes| E::Scalar::from_be_bytes_exact(&bytes).unwrap(),
criterion::BatchSize::SmallInput,
);
});
g.bench_function("DecodeScalarLE", |b| {
b.iter_batched(
|| E::Scalar::random(rng).to_le_bytes(),
|| random_scalar::<E>(rng).to_le_bytes(),
|bytes| E::Scalar::from_le_bytes_exact(&bytes).unwrap(),
criterion::BatchSize::SmallInput,
);
Expand Down Expand Up @@ -167,6 +167,12 @@ fn bench_curve<E: Curve>(
}
}

fn random_scalar<E: Curve>(rng: &mut impl rand_core::RngCore) -> E::Scalar {
let mut bytes = <<E::Scalar as FromUniformBytes>::Bytes as ByteArray>::zeroes();
rng.fill_bytes(bytes.as_mut());
<E::Scalar as FromUniformBytes>::from_uniform_bytes(&bytes)
}

fn bench_bytes_reduction<E: Curve, const N: usize>(
c: &mut criterion::Criterion,
rng: &mut rand_dev::DevRng,
Expand Down Expand Up @@ -199,6 +205,6 @@ fn bench_bytes_reduction<E: Curve, const N: usize>(
}

fn random_point<E: Curve>(rng: &mut rand_dev::DevRng) -> E::Point {
let scalar = E::Scalar::random(rng);
let scalar = random_scalar::<E>(rng);
E::Scalar::mul(&scalar, &CurveGenerator)
}
18 changes: 16 additions & 2 deletions generic-ec-curves/src/ed25519.rs
Original file line number Diff line number Diff line change
Expand Up @@ -220,8 +220,22 @@ impl generic_ec_core::One for Scalar {
}
}

impl generic_ec_core::Samplable for Scalar {
fn random<R: rand_core::RngCore>(rng: &mut R) -> Self {
impl generic_ec_core::FromUniformBytes for Scalar {
/// 48 bytes
///
/// `L = ceil((ceil(log2(q)) + k) / 8) = ceil((256 + 128) / 8) = 48` bytes are enough to
/// guarantee the uniform distribution
type Bytes = [u8; 48];

fn from_uniform_bytes(bytes: &Self::Bytes) -> Self {
let mut bytes_le = [0u8; 64];
bytes_le[..48].copy_from_slice(bytes);
Self(curve25519::Scalar::from_bytes_mod_order_wide(&bytes_le))
}
}

impl generic_ec_core::SamplableVartime for Scalar {
fn random_vartime(rng: &mut impl rand_core::RngCore) -> Self {
// Having crypto rng for scalar generation is not a hard requirement,
// as in some cases it isn't needed. However, `curve25519` lib asks for
// it, so we'll trick it
Expand Down
5 changes: 3 additions & 2 deletions generic-ec-curves/src/rust_crypto/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ use elliptic_curve::ops::Reduce;
use elliptic_curve::sec1::{FromEncodedPoint, ModulusSize, ToEncodedPoint};
use elliptic_curve::{CurveArithmetic, FieldBytesSize, ScalarPrimitive};
use generic_ec_core::{
CompressedEncoding, Curve, IntegerEncoding, NoInvalidPoints, UncompressedEncoding,
CompressedEncoding, Curve, FromUniformBytes, IntegerEncoding, NoInvalidPoints,
UncompressedEncoding,
};
use subtle::{ConditionallySelectable, ConstantTimeEq};
use zeroize::{DefaultIsZeroes, Zeroize};
Expand Down Expand Up @@ -88,7 +89,7 @@ where
for<'a> &'a C::ProjectivePoint: Mul<&'a C::Scalar, Output = C::ProjectivePoint>,
C::Scalar:
Reduce<C::Uint> + Eq + ConstantTimeEq + ConditionallySelectable + DefaultIsZeroes + Unpin,
RustCryptoScalar<C>: scalar::BytesModOrder,
RustCryptoScalar<C>: scalar::BytesModOrder + FromUniformBytes,
for<'a> ScalarPrimitive<C>: From<&'a C::Scalar>,
FieldBytesSize<C>: ModulusSize,
X: 'static,
Expand Down
49 changes: 43 additions & 6 deletions generic-ec-curves/src/rust_crypto/scalar.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use core::ops::Mul;

use elliptic_curve::bigint::{ArrayEncoding, ByteArray, U256, U512};
use elliptic_curve::{Curve, CurveArithmetic, Field, Group, PrimeField, ScalarPrimitive};
use elliptic_curve::{Curve, CurveArithmetic, Field, Group, ScalarPrimitive};
use generic_ec_core::{
Additive, CurveGenerator, IntegerEncoding, Invertible, Multiplicative, One, Reduce, Samplable,
Zero,
Additive, CurveGenerator, FromUniformBytes, IntegerEncoding, Invertible, Multiplicative, One,
Reduce, SamplableVartime, Zero,
};
use subtle::{Choice, ConditionallySelectable, ConstantTimeEq, CtOption};
use zeroize::DefaultIsZeroes;
Expand Down Expand Up @@ -84,10 +84,47 @@ impl<E: CurveArithmetic> One for RustCryptoScalar<E> {
}
}

impl<E: CurveArithmetic> Samplable for RustCryptoScalar<E> {
fn random<R: rand_core::RngCore>(rng: &mut R) -> Self {
let mut bytes: <E::Scalar as PrimeField>::Repr = Default::default();
#[cfg(feature = "secp256k1")]
impl FromUniformBytes for RustCryptoScalar<k256::Secp256k1> {
/// 48 bytes
///
/// `L = ceil((ceil(log2(q)) + k) / 8) = ceil((256 + 128) / 8) = 48` bytes are enough to
/// guarantee the uniform distribution
type Bytes = [u8; 48];
fn from_uniform_bytes(bytes: &Self::Bytes) -> Self {
let mut bytes_be = [0u8; 64];
bytes_be[64 - 48..].copy_from_slice(bytes);
<Self as Reduce<64>>::from_be_array_mod_order(&bytes_be)
}
}
#[cfg(feature = "secp256r1")]
impl FromUniformBytes for RustCryptoScalar<p256::NistP256> {
/// 48 bytes
///
/// `L = ceil((ceil(log2(q)) + k) / 8) = ceil((256 + 128) / 8) = 48` bytes are enough to
/// guarantee the uniform distribution
type Bytes = [u8; 48];
fn from_uniform_bytes(bytes: &Self::Bytes) -> Self {
BytesModOrder::from_be_bytes_mod_order(bytes)
}
}
#[cfg(feature = "stark")]
impl FromUniformBytes for RustCryptoScalar<stark_curve::StarkCurve> {
/// 48 bytes
///
/// `L = ceil((ceil(log2(q)) + k) / 8) = ceil((256 + 128) / 8) = 48` bytes are enough to
/// guarantee the uniform distribution
type Bytes = [u8; 48];
fn from_uniform_bytes(bytes: &Self::Bytes) -> Self {
BytesModOrder::from_be_bytes_mod_order(bytes)
}
}

impl<E: CurveArithmetic> SamplableVartime for RustCryptoScalar<E> {
fn random_vartime(rng: &mut impl rand_core::RngCore) -> Self {
use elliptic_curve::PrimeField;

let mut bytes: <E::Scalar as PrimeField>::Repr = Default::default();
loop {
rng.fill_bytes(bytes.as_mut());

Expand Down
5 changes: 5 additions & 0 deletions generic-ec-zkp/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
## v0.5.0
* Update `generic_ec` dep to v0.5 [#55]

[#55]: https://github.com/LFDT-Lockness/generic-ec/pull/55

## v0.4.4
* Add `dlog_eq` proof [#54]

Expand Down
Loading