Skip to content
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
2 changes: 1 addition & 1 deletion elliptic-curve/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,10 @@ alloc = ["der/alloc", "sec1/alloc", "zeroize/alloc"] # todo: use weak activation
arithmetic = ["ff", "group"]
bits = ["arithmetic", "ff/bits"]
dev = ["arithmetic", "hex-literal", "pem", "pkcs8"]
hash2curve = ["digest", "ff", "group"]
ecdh = ["arithmetic"]
hazmat = []
jwk = ["alloc", "base64ct/alloc", "serde", "serde_json", "zeroize/alloc"]
osswu = ["ff"]
pem = ["alloc", "arithmetic", "pem-rfc7468/alloc", "pkcs8", "sec1/pem"]
pkcs8 = ["sec1/pkcs8"]
std = ["alloc", "rand_core/std"]
Expand Down
14 changes: 14 additions & 0 deletions elliptic-curve/src/hash2curve.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/// Traits for handling hash to curve
mod group_digest;
/// Traits for mapping an isogeny to another curve
/// <https://datatracker.ietf.org/doc/draft-irtf-cfrg-hash-to-curve>
mod isogeny;
/// Traits for mapping field elements to points on the curve
mod map2curve;
/// Optimized simplified Shallue-van de Woestijne-Ulas methods
mod osswu;

pub use group_digest::*;
pub use isogeny::*;
pub use map2curve::*;
pub use osswu::*;
69 changes: 69 additions & 0 deletions elliptic-curve/src/hash2curve/group_digest.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
use super::MapToCurve;
use crate::hash2field::{hash_to_field, ExpandMsg, FromOkm};
use group::cofactor::CofactorGroup;

/// Adds hashing arbitrary byte sequences to a valid group element
pub trait GroupDigest {
/// The field element representation for a group value with multiple elements
type FieldElement: FromOkm + Default + Copy;
/// The resulting group element
type Output: CofactorGroup<Subgroup = Self::Output>
+ MapToCurve<FieldElement = Self::FieldElement, Output = Self::Output>;

/// Computes the hash to curve routine according to
/// <https://www.ietf.org/archive/id/draft-irtf-cfrg-hash-to-curve-13.html>
/// which says
/// Uniform encoding from byte strings to points in G.
/// That is, the distribution of its output is statistically close
/// to uniform in G.
/// This function is suitable for most applications requiring a random
/// oracle returning points in G assuming a cryptographically secure
/// hash function is used.
///
/// Examples
///
/// Using a fixed size hash function
///
/// ```ignore
/// let pt = ProjectivePoint::hash_from_bytes::<hash2field::ExpandMsgXmd<sha2::Sha256>>(b"test data", b"CURVE_XMD:SHA-256_SSWU_RO_");
/// ```
///
/// Using an extendable output function
///
/// ```ignore
/// let pt = ProjectivePoint::hash_from_bytes::<hash2field::ExpandMsgXof<sha3::Shake256>>(b"test data", b"CURVE_XOF:SHAKE-256_SSWU_RO_");
/// ```
///
fn hash_from_bytes<X: ExpandMsg>(msg: &[u8], dst: &'static [u8]) -> Self::Output {
let mut u = [Self::FieldElement::default(), Self::FieldElement::default()];
hash_to_field::<X, _>(msg, dst, &mut u);
let q0 = Self::Output::map_to_curve(u[0]);
let q1 = Self::Output::map_to_curve(u[1]);
// Ideally we could add and then clear cofactor once
// thus saving a call but the field elements may not
// add properly due to the underlying implementation
// which could result in an incorrect subgroup.
// This is caused curve coefficients being different than
// what is usually implemented.
// FieldElement expects the `a` and `b` to be the original values
// isogenies are different with curves like k256 and bls12-381.
// This problem doesn't manifest for curves with no isogeny like p256.
// For k256 and p256 clear_cofactor doesn't do anything anyway so it will be a no-op.
q0.clear_cofactor() + q1.clear_cofactor()
}

/// Computes the encode to curve routine according to
/// <https://www.ietf.org/archive/id/draft-irtf-cfrg-hash-to-curve-13.html>
/// which says
/// Nonuniform encoding from byte strings to
/// points in G. That is, the distribution of its output is not
/// uniformly random in G: the set of possible outputs of
/// encode_to_curve is only a fraction of the points in G, and some
/// points in this set are more likely to be output than others.
fn encode_from_bytes<X: ExpandMsg>(msg: &[u8], dst: &'static [u8]) -> Self::Output {
let mut u = [Self::FieldElement::default()];
hash_to_field::<X, _>(msg, dst, &mut u);
let q0 = Self::Output::map_to_curve(u[0]);
q0.clear_cofactor()
}
}
53 changes: 53 additions & 0 deletions elliptic-curve/src/hash2curve/isogeny.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
use core::ops::{AddAssign, Mul};
use ff::Field;
use generic_array::{typenum::Unsigned, ArrayLength, GenericArray};

/// The coefficients for mapping from one isogenous curve to another
pub struct IsogenyCoefficients<F: Field + AddAssign + Mul<Output = F>> {
/// The coefficients for the x numerator
pub xnum: &'static [F],
/// The coefficients for the x denominator
pub xden: &'static [F],
/// The coefficients for the y numerator
pub ynum: &'static [F],
/// The coefficients for the x denominator
pub yden: &'static [F],
}

/// The Isogeny methods to map to another curve
pub trait Isogeny: Field + AddAssign + Mul<Output = Self> {
/// The maximum number of coefficients
type Degree: ArrayLength<Self>;
/// The isogeny coefficients
const COEFFICIENTS: IsogenyCoefficients<Self>;

/// Map from the isogeny points to the main curve
fn isogeny(x: Self, y: Self) -> (Self, Self) {
let mut xs = GenericArray::<Self, Self::Degree>::default();
xs[0] = Self::one();
xs[1] = x;
xs[2] = x.square();
for i in 3..Self::Degree::to_usize() {
xs[i] = xs[i - 1] * x;
}
let x_num = Self::compute_iso(&xs, Self::COEFFICIENTS.xnum);
let x_den = Self::compute_iso(&xs, Self::COEFFICIENTS.xden)
.invert()
.unwrap();
let y_num = Self::compute_iso(&xs, Self::COEFFICIENTS.ynum) * y;
let y_den = Self::compute_iso(&xs, Self::COEFFICIENTS.yden)
.invert()
.unwrap();

(x_num * x_den, y_num * y_den)
}

/// Compute the ISO transform
fn compute_iso(xxs: &[Self], k: &[Self]) -> Self {
let mut xx = Self::zero();
for (xi, ki) in xxs.iter().zip(k.iter()) {
xx += *xi * ki;
}
xx
}
}
12 changes: 12 additions & 0 deletions elliptic-curve/src/hash2curve/map2curve.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/// Trait for converting field elements into a point
/// via a mapping method like Simplified Shallue-van de Woestijne-Ulas
/// or Elligator
pub trait MapToCurve {
/// The input values representing x and y
type FieldElement;
/// The output point
type Output;

/// Map a field element into a point
fn map_to_curve(u: Self::FieldElement) -> Self::Output;
}
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,7 @@ pub trait OsswuMap: Field + Sgn0 {
let mut tv2 = tv3.square(); // tv3^2
let mut xd = tv2 + tv3; // tv3^2 + tv3
let x1n = Self::PARAMS.map_b * (xd + Self::one()); // B * (xd + 1)
let a_neg = -Self::PARAMS.map_a;
xd *= a_neg; // -A * xd
xd *= -Self::PARAMS.map_a; // -A * xd

let tv = Self::PARAMS.z * Self::PARAMS.map_a;
xd.conditional_assign(&tv, xd.is_zero());
Expand Down
30 changes: 15 additions & 15 deletions elliptic-curve/src/hash2field.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,32 +2,32 @@ mod expand_msg;
mod expand_msg_xmd;
mod expand_msg_xof;

use core::convert::TryFrom;
pub use expand_msg::*;
pub use expand_msg_xmd::*;
pub use expand_msg_xof::*;
use generic_array::{typenum::Unsigned, ArrayLength, GenericArray};

/// The trait for helping to convert to a scalar
pub trait FromOkm<const L: usize>: Sized {
pub trait FromOkm {
/// The number of bytes needed to convert to a scalar
type Length: ArrayLength<u8>;

/// Convert a byte sequence into a scalar
fn from_okm(data: &[u8; L]) -> Self;
fn from_okm(data: &GenericArray<u8, Self::Length>) -> Self;
}

/// Convert an arbitrary byte sequence according to
/// <https://tools.ietf.org/html/draft-irtf-cfrg-hash-to-curve-11#section-5.3>
pub fn hash_to_field<E, T, const L: usize, const COUNT: usize, const OUT: usize>(
data: &[u8],
domain: &[u8],
) -> [T; COUNT]
pub fn hash_to_field<E, T>(data: &[u8], domain: &'static [u8], out: &mut [T])
where
E: ExpandMsg<OUT>,
T: FromOkm<L> + Default + Copy,
E: ExpandMsg,
T: FromOkm + Default,
{
let random_bytes = E::expand_message(data, domain);
let mut out = [T::default(); COUNT];
for i in 0..COUNT {
let u = <[u8; L]>::try_from(&random_bytes[(L * i)..L * (i + 1)]).expect("not enough bytes");
out[i] = T::from_okm(&u);
let len_in_bytes = T::Length::to_usize() * out.len();
let mut tmp = GenericArray::<u8, <T as FromOkm>::Length>::default();
let mut expander = E::expand_message(data, domain, len_in_bytes);
for o in out.iter_mut() {
expander.fill_bytes(&mut tmp);
*o = T::from_okm(&tmp);
}
out
}
75 changes: 72 additions & 3 deletions elliptic-curve/src/hash2field/expand_msg.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,74 @@
use digest::{Digest, ExtendableOutputDirty, Update, XofReader};
use generic_array::{ArrayLength, GenericArray};

/// Salt when the DST is too long
const OVERSIZE_DST_SALT: &[u8] = b"H2C-OVERSIZE-DST-";
/// Maximum domain separation tag length
const MAX_DST_LEN: usize = 255;

/// Trait for types implementing expand_message interface for hash_to_field
pub trait ExpandMsg<const OUT: usize> {
/// Expands `msg` to the required number of bytes in `buf`
fn expand_message(msg: &[u8], dst: &[u8]) -> [u8; OUT];
pub trait ExpandMsg {
/// Expands `msg` to the required number of bytes
/// Returns an expander that can be used to call `read` until enough
/// bytes have been consumed
fn expand_message(msg: &[u8], dst: &'static [u8], len_in_bytes: usize) -> Self;

/// Fill the array with the expanded bytes
fn fill_bytes(&mut self, okm: &mut [u8]);
}

/// The domain separation tag
///
/// Implements [section 5.4.3 of `draft-irtf-cfrg-hash-to-curve-13`][dst].
///
/// [dst]: https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-13#section-5.4.3
pub(crate) enum Domain<L: ArrayLength<u8>> {
/// > 255
Hashed(GenericArray<u8, L>),
/// <= 255
Array(&'static [u8]),
}

impl<L: ArrayLength<u8>> Domain<L> {
pub fn xof<X>(dst: &'static [u8]) -> Self
where
X: Default + ExtendableOutputDirty + Update,
{
if dst.len() > MAX_DST_LEN {
let mut data = GenericArray::<u8, L>::default();
X::default()
.chain(OVERSIZE_DST_SALT)
.chain(dst)
.finalize_xof_dirty()
.read(&mut data);
Self::Hashed(data)
} else {
Self::Array(dst)
}
}

pub fn xmd<X>(dst: &'static [u8]) -> Self
where
X: Digest<OutputSize = L>,
{
if dst.len() > MAX_DST_LEN {
Self::Hashed(X::new().chain(OVERSIZE_DST_SALT).chain(dst).finalize())
} else {
Self::Array(dst)
}
}

pub fn data(&self) -> &[u8] {
match self {
Self::Hashed(d) => &d[..],
Self::Array(d) => *d,
}
}

pub fn len(&self) -> usize {
match self {
Self::Hashed(_) => L::to_usize(),
Self::Array(d) => d.len(),
}
}
}
Loading