Skip to content

Commit

Permalink
ECC: Better encapsulate Curve25519 base point multiplication.
Browse files Browse the repository at this point in the history
Combine some `unsafe` blocks and create a more logical interface.
  • Loading branch information
briansmith committed Oct 2, 2023
1 parent 52582ad commit c4a6ec8
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 15 deletions.
14 changes: 2 additions & 12 deletions src/ec/curve25519/ed25519/signing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -176,10 +176,7 @@ impl Ed25519KeyPair {
let private_scalar =
MaskedScalar::from_bytes_masked(private_scalar.try_into().unwrap()).into();

let mut a = ExtPoint::new_at_infinity();
unsafe {
x25519_ge_scalarmult_base(&mut a, &private_scalar);
}
let a = ExtPoint::from_scalarmult_base_consttime(&private_scalar);

Self {
private_scalar,
Expand Down Expand Up @@ -210,10 +207,7 @@ impl Ed25519KeyPair {
};
let nonce = Scalar::from_sha512_digest_reduced(nonce);

let mut r = ExtPoint::new_at_infinity();
unsafe {
x25519_ge_scalarmult_base(&mut r, &nonce);
}
let r = ExtPoint::from_scalarmult_base_consttime(&nonce);
signature_r.copy_from_slice(&r.into_encoded_point());
let hram_digest = eddsa_digest(signature_r, self.public_key.as_ref(), msg);
let hram = Scalar::from_sha512_digest_reduced(hram_digest);
Expand Down Expand Up @@ -263,10 +257,6 @@ fn unwrap_pkcs8(
Ok((private_key, public_key))
}

prefixed_extern! {
fn x25519_ge_scalarmult_base(h: &mut ExtPoint, a: &Scalar);
}

type Prefix = [u8; PREFIX_LEN];
const PREFIX_LEN: usize = digest::SHA512_OUTPUT_LEN - SCALAR_LEN;

Expand Down
19 changes: 16 additions & 3 deletions src/ec/curve25519/ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,17 +73,30 @@ pub struct ExtPoint {
}

impl ExtPoint {
pub fn new_at_infinity() -> Self {
Self {
// Returns the result of multiplying the base point by the scalar in constant time.
pub fn from_scalarmult_base_consttime(scalar: &Scalar) -> Self {
let mut r = Self {
x: Elem::zero(),
y: Elem::zero(),
z: Elem::zero(),
t: Elem::zero(),
};
prefixed_extern! {
fn x25519_ge_scalarmult_base(h: &mut ExtPoint, a: &Scalar);
}
unsafe {
x25519_ge_scalarmult_base(&mut r, scalar);
}
r
}

pub fn from_encoded_point_vartime(encoded: &EncodedPoint) -> Result<Self, error::Unspecified> {
let mut point = Self::new_at_infinity();
let mut point = Self {
x: Elem::zero(),
y: Elem::zero(),
z: Elem::zero(),
t: Elem::zero(),
};

Result::from(unsafe { x25519_ge_frombytes_vartime(&mut point, encoded) }).map(|()| point)
}
Expand Down

0 comments on commit c4a6ec8

Please sign in to comment.