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

Encodable curve #1

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
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
3 changes: 2 additions & 1 deletion curve25519-dalek/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ digest = { version = "0.10", default-features = false, optional = true }
subtle = { version = "2.6.0", default-features = false, features = ["const-generics"]}
serde = { version = "1.0", default-features = false, optional = true, features = ["derive"] }
zeroize = { version = "1", default-features = false, optional = true }
elliptic-curve = { version = "0.14.0-rc.1", features = ["serde", "arithmetic"] }

[target.'cfg(target_arch = "x86_64")'.dependencies]
cpufeatures = "0.2.6"
Expand All @@ -62,7 +63,7 @@ cpufeatures = "0.2.6"
fiat-crypto = { version = "0.2.1", default-features = false }

[features]
default = ["alloc", "precomputed-tables", "zeroize"]
default = ["alloc", "precomputed-tables", "group"]
alloc = ["zeroize?/alloc"]
precomputed-tables = []
legacy_compatibility = []
Expand Down
145 changes: 145 additions & 0 deletions curve25519-dalek/src/encodable_curve.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
// -*- mode: rust; -*-
//
// This file is part of curve25519-dalek fork by Arcium.
//! Module for common traits.

use core::ops::Not;
use core::ops::ShrAssign;

use elliptic_curve::array::Array;
use elliptic_curve::bigint::ArrayEncoding;
use elliptic_curve::bigint::U256;
use elliptic_curve::consts::U32;
use elliptic_curve::ops::Invert;
use elliptic_curve::ops::MulByGenerator;
use elliptic_curve::scalar::FromUintUnchecked;
use elliptic_curve::scalar::IsHigh;
use elliptic_curve::Curve;
use elliptic_curve::Field;
use elliptic_curve::FieldBytes;
use elliptic_curve::FieldBytesEncoding;
use elliptic_curve::ScalarPrimitive;
use subtle::Choice;
use subtle::CtOption;

use crate::constants::BASEPOINT_ORDER_PRIVATE;
use crate::EdwardsPoint;
use crate::Scalar;

// Empty struct for the curve
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, PartialOrd, Ord)]
pub struct Dalek {}

impl Curve for Dalek {
type FieldBytesSize = U32;
type Uint = U256;
const ORDER: Self::Uint = U256::from_le_slice(BASEPOINT_ORDER_PRIVATE.as_bytes());
}

// Impls for EdwardsPoint
impl MulByGenerator for EdwardsPoint {}

// Impls for Scalar
impl AsRef<Scalar> for Scalar {
fn as_ref(&self) -> &Scalar {
self
}
}

// NOTE: ScalarPrimitive is big endian. Dalek uses little endian
impl From<ScalarPrimitive<Dalek>> for Scalar {
fn from(value: ScalarPrimitive<Dalek>) -> Self {
Scalar::from_bytes_mod_order(value.to_uint().to_le_bytes())
}
}

impl FromUintUnchecked for Scalar {
// CHECK! Is the 4 correct?
type Uint = elliptic_curve::bigint::Uint<4>;
fn from_uint_unchecked(uint: Self::Uint) -> Self {
Scalar {
bytes: uint.to_le_bytes(),
}
}
}

impl Into<FieldBytes<Dalek>> for Scalar {
fn into(self) -> FieldBytes<Dalek> {
U256::encode_field_bytes(&U256::from_le_slice(&self.bytes))
}
}

impl Into<ScalarPrimitive<Dalek>> for Scalar {
fn into(self) -> ScalarPrimitive<Dalek> {
ScalarPrimitive::new(U256::from_le_slice(&self.bytes)).unwrap()
}
}

impl Into<U256> for Scalar {
fn into(self) -> U256 {
U256::from_le_slice(&self.bytes)
}
}

impl Into<U256> for &mut Scalar {
fn into(self) -> U256 {
U256::from_le_slice(&self.bytes)
}
}

impl Invert for Scalar {
type Output = CtOption<Self>;
fn invert(&self) -> Self::Output {
Field::invert(self)
}
}

impl IsHigh for Scalar {
//FIXME: Can we do better?
mdgrs marked this conversation as resolved.
Show resolved Hide resolved
fn is_high(&self) -> Choice {
let t = self.double().is_canonical();
Choice::not(t)
}
}

impl PartialOrd for Scalar {
fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
for (s, o) in self.bits_le().rev().zip(other.bits_le().rev()) {
match (s, o) {
(true, false) => return Some(core::cmp::Ordering::Greater),
(false, true) => return Some(core::cmp::Ordering::Less),
_ => (),
};
}
return Some(core::cmp::Ordering::Equal);
}
}

impl ShrAssign<usize> for Scalar {
fn shr_assign(&mut self, rhs: usize) {
let temp = Into::<U256>::into(self.clone())
.shr_vartime(rhs as u32)
.to_le_bytes();
*self = Scalar::from_bytes_mod_order(temp);
}
}

impl elliptic_curve::ops::Reduce<U256> for Scalar {
type Bytes = Array<u8, U32>;
fn reduce(n: U256) -> Self {
Self::from_bytes_mod_order(n.to_le_bytes())
}
fn reduce_bytes(bytes: &Self::Bytes) -> Self {
Self::from_bytes_mod_order(bytes.0)
}
}

impl FieldBytesEncoding<Dalek> for U256 {
fn decode_field_bytes(field_bytes: &FieldBytes<Dalek>) -> Self {
U256::from_be_byte_array(*field_bytes)
}

fn encode_field_bytes(&self) -> FieldBytes<Dalek> {
self.to_be_byte_array()
}
}
3 changes: 3 additions & 0 deletions curve25519-dalek/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,9 @@ pub mod constants;
// External (and internal) traits.
pub mod traits;

// Implementations for the Dalek structure
pub mod encodable_curve;

//------------------------------------------------------------------------
// curve25519-dalek internal modules
//------------------------------------------------------------------------
Expand Down
43 changes: 35 additions & 8 deletions curve25519-dalek/src/scalar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1131,7 +1131,7 @@ impl Scalar {

/// Check whether this `Scalar` is the canonical representative mod \\(\ell\\). This is not
/// public because any `Scalar` that is publicly observed is reduced, by scalar invariant #2.
fn is_canonical(&self) -> Choice {
pub(crate) fn is_canonical(&self) -> Choice {
self.ct_eq(&self.reduce())
}
}
Expand Down Expand Up @@ -1251,21 +1251,44 @@ impl Field for Scalar {
}
}

use elliptic_curve::consts::U32;

#[cfg(feature = "group")]
impl PrimeField for Scalar {
type Repr = [u8; 32];
type Repr = elliptic_curve::array::Array<u8, U32>;

fn from_repr(repr: Self::Repr) -> CtOption<Self> {
Self::from_canonical_bytes(repr)
Self::from_canonical_bytes(repr.0)
}

fn from_repr_vartime(repr: Self::Repr) -> Option<Self> {
let r: elliptic_curve::array::Array<
u8,
digest::typenum::UInt<
digest::typenum::UInt<
digest::typenum::UInt<
digest::typenum::UInt<
digest::typenum::UInt<
digest::typenum::UInt<digest::typenum::UTerm, digest::consts::B1>,
digest::consts::B0,
>,
digest::consts::B0,
>,
digest::consts::B0,
>,
digest::consts::B0,
>,
digest::consts::B0,
>,
Comment on lines +1267 to +1282
Copy link

@n-lebel n-lebel Nov 14, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can use typenum::consts::U32 instead of writing everything with bits like here. For large values that aren't in typenum::consts, you can use the typenum-consts crate.

> = repr;
let t: [u8; 32] = r.0;

// Check that the high bit is not set
if (repr[31] >> 7) != 0u8 {
if (t[31] >> 7) != 0u8 {
return None;
}

let candidate = Scalar { bytes: repr };
let candidate = Scalar { bytes: t };

if candidate == candidate.reduce() {
Some(candidate)
Expand All @@ -1275,7 +1298,9 @@ impl PrimeField for Scalar {
}

fn to_repr(&self) -> Self::Repr {
self.to_bytes()
//FIXME Unwrap alert
elliptic_curve::array::Array::try_from(self.to_bytes())
.expect("Could not convert bytes to Array")
}

fn is_odd(&self) -> Choice {
Expand Down Expand Up @@ -1995,11 +2020,13 @@ pub(crate) mod test {
// We should get back either the positive or negative root.
assert!([X, -X].contains(&x_sq.sqrt().unwrap()));

let res = elliptic_curve::array::Array::try_from([0xff; 32]).unwrap();

assert_eq!(Scalar::from_repr_vartime(X.to_repr()), Some(X));
assert_eq!(Scalar::from_repr_vartime([0xff; 32]), None);
assert_eq!(Scalar::from_repr_vartime(res), None);

assert_eq!(Scalar::from_repr(X.to_repr()).unwrap(), X);
assert!(bool::from(Scalar::from_repr([0xff; 32]).is_none()));
assert!(bool::from(Scalar::from_repr(res).is_none()));
}

#[test]
Expand Down
1 change: 1 addition & 0 deletions rust-toolchain
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
1.81