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

Update secp256k1 and p256. Remove rand_legacy #181

Open
wants to merge 5 commits into
base: master
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
9 changes: 4 additions & 5 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ num-traits = "0.2"
num-integer = "0.1"
pairing-plus = "0.19"
rand = "0.7"
rand_legacy = { package = "rand", version = "0.6" }
serde = { version = "1.0", features = ["derive"] }
serde_bytes = "0.11"
serde_derive = "1.0"
Expand All @@ -42,19 +41,19 @@ rust-gmp-kzen = { version = "0.5", features = ["serde_support"], optional = true
num-bigint = { version = "0.4", features = ["serde"], optional = true }

[dependencies.secp256k1]
version = "0.20"
version = "0.27.0"
features = ["serde", "rand-std", "global-context"]

[dependencies.p256]
version = "0.11.1"
version = "0.13.2"
features = ["ecdsa", "ecdsa-core"]

[dev-dependencies]
serde_test = "1.0"
serde_json = "1"
paste = "1.0.2"
proptest = "0.10"
proptest-derive = "0.2"
proptest = "1.2.0"
proptest-derive = "0.3.0"
blake2 = "0.9"

[features]
Expand Down
13 changes: 7 additions & 6 deletions src/elliptic/curves/p256.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,22 @@

use std::convert::TryFrom;

use generic_array::GenericArray;
use p256::elliptic_curve::group::ff::PrimeField;
use p256::elliptic_curve::group::prime::PrimeCurveAffine;
use p256::elliptic_curve::ops::Reduce;
use p256::elliptic_curve::sec1::{FromEncodedPoint, ToEncodedPoint};
use p256::elliptic_curve::Field;
use p256::{AffinePoint, EncodedPoint, FieldBytes, ProjectivePoint, Scalar};

use generic_array::GenericArray;
use rand::{thread_rng, Rng};
use serde::{Deserialize, Serialize};
use zeroize::Zeroize;

use super::traits::{ECPoint, ECScalar};
use crate::arithmetic::traits::*;
use crate::elliptic::curves::{Curve, DeserializationError, NotOnCurve, PointCoords};
use crate::BigInt;

use super::traits::{ECPoint, ECScalar};

lazy_static::lazy_static! {
static ref GROUP_ORDER: BigInt = BigInt::from_bytes(&GROUP_ORDER_BYTES);

Expand Down Expand Up @@ -129,7 +128,9 @@ impl ECScalar for Secp256r1Scalar {

Secp256r1Scalar {
purpose: "from_bigint",
fe: Scalar::from_be_bytes_reduced(GenericArray::from(n_reduced)).into(),
fe: Scalar::from_repr(GenericArray::from(n_reduced))
.unwrap()
.into(),
}
}

Expand Down Expand Up @@ -419,7 +420,7 @@ mod tests {
assert_eq!(
&GE::from_coords(
&base_point2.x_coord().unwrap(),
&base_point2.y_coord().unwrap()
&base_point2.y_coord().unwrap(),
)
.unwrap(),
base_point2
Expand Down
38 changes: 27 additions & 11 deletions src/elliptic/curves/secp256_k1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ use generic_array::GenericArray;
use secp256k1::constants::{
self, GENERATOR_X, GENERATOR_Y, SECRET_KEY_SIZE, UNCOMPRESSED_PUBLIC_KEY_SIZE,
};
use secp256k1::{PublicKey, SecretKey, SECP256K1};
use secp256k1::ffi::CPtr;
use secp256k1::{PublicKey, Scalar, SecretKey, SECP256K1};
use serde::{Deserialize, Serialize};
use zeroize::{Zeroize, Zeroizing};

Expand Down Expand Up @@ -79,6 +80,7 @@ const BASE_POINT2_Y: [u8; 32] = [
/// SK wraps secp256k1::SecretKey and implements Zeroize to it
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct SK(pub SecretKey);

/// PK wraps secp256k1::PublicKey and implements Zeroize to it
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub struct PK(pub PublicKey);
Expand All @@ -90,6 +92,7 @@ impl ops::Deref for SK {
&self.0
}
}

impl ops::DerefMut for SK {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
Expand All @@ -103,6 +106,7 @@ impl ops::Deref for PK {
&self.0
}
}

impl ops::DerefMut for PK {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
Expand All @@ -111,7 +115,7 @@ impl ops::DerefMut for PK {

impl Zeroize for SK {
fn zeroize(&mut self) {
let sk = self.0.as_mut_ptr();
let sk = self.0.as_mut_c_ptr();
let sk_bytes = unsafe { std::slice::from_raw_parts_mut(sk, 32) };
sk_bytes.zeroize()
}
Expand All @@ -120,7 +124,7 @@ impl Zeroize for SK {
impl Zeroize for PK {
fn zeroize(&mut self) {
let zeroed = unsafe { secp256k1::ffi::PublicKey::new() };
unsafe { ptr::write_volatile(self.0.as_mut_ptr(), zeroed) };
unsafe { ptr::write_volatile(self.0.as_mut_c_ptr(), zeroed) };
atomic::compiler_fence(atomic::Ordering::SeqCst);
}
}
Expand All @@ -145,6 +149,7 @@ pub struct Secp256k1Scalar {
/// `fe` might be None — special case for scalar being zero
fe: zeroize::Zeroizing<Option<SK>>,
}

#[derive(Clone, Debug, Copy)]
pub struct Secp256k1Point {
#[allow(dead_code)]
Expand All @@ -161,7 +166,7 @@ impl ECScalar for Secp256k1Scalar {
type ScalarLength = typenum::U32;

fn random() -> Secp256k1Scalar {
let sk = SK(SecretKey::new(&mut rand_legacy::thread_rng()));
let sk = SK(SecretKey::new(&mut secp256k1::rand::thread_rng()));
Secp256k1Scalar {
purpose: "random",
fe: Zeroizing::new(Some(sk)),
Expand Down Expand Up @@ -233,7 +238,14 @@ impl ECScalar for Secp256k1Scalar {
(left, None) => left.clone(),
(Some(left), Some(right)) => {
let mut res = left.clone();
res.add_assign(&right.0[..]).ok().map(|_| res) // right might be the negation of left.
if let Ok(add) =
res.add_tweak(&Scalar::from_be_bytes(right.secret_bytes()).unwrap())
{
res.0 = add;
Some(res)
} else {
None // right might be the negation of left.
}
}
};

Expand All @@ -248,8 +260,8 @@ impl ECScalar for Secp256k1Scalar {
(None, _) | (_, None) => None,
(Some(left), Some(right)) => {
let mut res = left.clone();
res.0
.mul_assign(&right.0[..])
res.0 = res
.mul_tweak(&Scalar::from_be_bytes(right.secret_bytes()).unwrap())
.expect("Can't fail as it's a valid secret");
Some(res)
}
Expand All @@ -272,7 +284,7 @@ impl ECScalar for Secp256k1Scalar {

fn neg(&self) -> Self {
let fe = self.fe.deref().clone().map(|mut fe| {
fe.negate_assign();
fe.0 = fe.negate();
fe
});
Secp256k1Scalar {
Expand Down Expand Up @@ -471,7 +483,7 @@ impl ECPoint for Secp256k1Point {

fn neg_point(&self) -> Secp256k1Point {
let ge = self.ge.map(|mut ge| {
ge.0.negate_assign(SECP256K1);
ge.0 = ge.negate(SECP256K1);
ge
});
Secp256k1Point { purpose: "neg", ge }
Expand All @@ -483,7 +495,11 @@ impl ECPoint for Secp256k1Point {
self.ge = None;
}
(Some(ge), Some(fe)) => {
ge.0.mul_assign(SECP256K1, &fe.0[..])
ge.0 = ge
.mul_tweak(
SECP256K1,
&Scalar::from_be_bytes(fe.secret_bytes()).unwrap(),
)
.expect("Can't fail as it's a valid secret");
}
};
Expand Down Expand Up @@ -592,7 +608,7 @@ mod test {
assert_eq!(
&GE::from_coords(
&base_point2.x_coord().unwrap(),
&base_point2.y_coord().unwrap()
&base_point2.y_coord().unwrap(),
)
.unwrap(),
base_point2
Expand Down