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

secp256k: wrap keys and add high-level functions to manage them. #13

Open
wants to merge 4 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
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ serde_json = "1.0"
hmac = "0.8.0"
sha2 = "0.9.0"
ed25519-dalek = { version = "1.0.0-pre.3", optional = true }
secp256k1 = { version = "0.17.2", optional = true }
secp256k1 = { version = "0.17.2", features = ["rand"], optional = true }

# Private dependencies (not exposed in the public API).
smallvec = "1.4.0"
Expand Down
2 changes: 1 addition & 1 deletion src/alg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,5 @@ pub use self::eddsa_dalek::Ed25519;
#[cfg(feature = "exonum-crypto")]
pub use self::eddsa_sodium::Ed25519;
#[cfg(feature = "secp256k1")]
pub use self::es256k::Es256k;
pub use self::es256k::*;
pub use self::hmacs::*;
72 changes: 67 additions & 5 deletions src/alg/es256k.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use rand_core::{CryptoRng, RngCore};
use secp256k1::{All, Message, PublicKey, Secp256k1, SecretKey, Signature};
use sha2::{
digest::{generic_array::typenum::U32, Digest},
Sha256,
};

use std::{borrow::Cow, marker::PhantomData};

use crate::{Algorithm, AlgorithmSignature};
Expand All @@ -18,6 +18,50 @@ impl AlgorithmSignature for Signature {
}
}

/// A verification key.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub struct Es256kVerifyingKey(PublicKey);

impl AsRef<PublicKey> for Es256kVerifyingKey {
fn as_ref(&self) -> &PublicKey {
&self.0
}
}

impl Es256kVerifyingKey {
/// Create a verification key from a slice.
pub fn from_slice(raw: &[u8]) -> anyhow::Result<Es256kVerifyingKey> {
Ok(Es256kVerifyingKey(PublicKey::from_slice(raw)?))
}

/// Return the key as raw bytes.
pub fn as_bytes(&self) -> Cow<[u8]> {
Cow::Owned(self.as_ref().serialize().to_vec())
}
}

/// A signing key.
#[derive(Debug)]
pub struct Es256kSigningKey(SecretKey);

impl AsRef<SecretKey> for Es256kSigningKey {
fn as_ref(&self) -> &SecretKey {
&self.0
}
}

impl Es256kSigningKey {
/// Create a signing key from a slice.
pub fn from_slice(raw: &[u8]) -> anyhow::Result<Es256kSigningKey> {
Ok(Es256kSigningKey(SecretKey::from_slice(raw)?))
}

/// Convert a signing key to a verification key.
pub fn to_verifying_key(&self) -> PublicKey {
PublicKey::from_secret_key(&Secp256k1::new(), &self.0)
}
}

/// Algorithm implementing elliptic curve digital signatures (ECDSA) on the secp256k1 curve.
///
/// The algorithm does not fix the choice of the message digest algorithm; instead,
Expand Down Expand Up @@ -63,8 +107,8 @@ impl<D> Algorithm for Es256k<D>
where
D: Digest<OutputSize = U32> + Default,
{
type SigningKey = SecretKey;
type VerifyingKey = PublicKey;
type SigningKey = Es256kSigningKey;
type VerifyingKey = Es256kVerifyingKey;
type Signature = Signature;

fn name(&self) -> Cow<'static, str> {
Expand All @@ -77,7 +121,7 @@ where
let message = Message::from_slice(&digest.finalize())
.expect("failed to convert message to the correct form");

self.context.sign(&message, signing_key)
self.context.sign(&message, signing_key.as_ref())
}

fn verify_signature(
Expand All @@ -92,7 +136,25 @@ where
.expect("failed to convert message to the correct form");

self.context
.verify(&message, signature, verifying_key)
.verify(&message, signature, verifying_key.as_ref())
.is_ok()
}
}

impl Es256k {
/// Generate a new key pair.
pub fn generate<R: CryptoRng + RngCore>(
&self,
rng: &mut R,
) -> (Es256kSigningKey, Es256kVerifyingKey) {
let signing_key = loop {
let mut bytes: [u8; secp256k1::constants::SECRET_KEY_SIZE];
rng.fill_bytes(&mut bytes);
Copy link
Contributor Author

Choose a reason for hiding this comment

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

clippy bug 🤷

if let Ok(key) = SecretKey::from_slice(&bytes) {
break Es256kSigningKey(key);
}
};
let verifying_key = Es256kVerifyingKey(signing_key.to_verifying_key());
(signing_key, verifying_key)
}
}
18 changes: 3 additions & 15 deletions tests/algorithms.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,8 +112,6 @@ fn es256k_reference() {
//! Generated using https://github.com/uport-project/did-jwt based on the unit tests
//! in the repository.

use secp256k1::PublicKey;

const TOKEN: &str = "eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NksifQ.\
eyJpYXQiOjE1NjE4MTQ3ODgsImJsYSI6ImJsYSIsImlzcyI6ImRpZDp1cG9\
ydDoyblF0aVFHNkNnbTFHWVRCYWFLQWdyNzZ1WTdpU2V4VWtxWCJ9.\
Expand All @@ -123,7 +121,7 @@ fn es256k_reference() {
const KEY_HEX: &str = "04fdd57adec3d438ea237fe46b33ee1e016eda6b585c3e27ea66686c2ea5358479\
46393f8145252eea68afe67e287b3ed9b31685ba6c3b00060a73b9b1242d68f7";

let public_key = PublicKey::from_slice(&hex::decode(KEY_HEX).unwrap()).unwrap();
let public_key = Es256kVerifyingKey::from_slice(&hex::decode(KEY_HEX).unwrap()).unwrap();
let es256k: Es256k = Default::default();
let token = UntrustedToken::try_from(TOKEN).unwrap();
assert_eq!(token.algorithm(), "ES256K");
Expand Down Expand Up @@ -340,18 +338,8 @@ fn ed25519_algorithm() {
#[cfg(feature = "secp256k1")]
#[test]
fn es256k_algorithm() {
use rand::Rng;
use secp256k1::{PublicKey, Secp256k1, SecretKey};

let mut rng = thread_rng();
let signing_key = loop {
let bytes: [u8; 32] = rng.gen();
if let Ok(key) = SecretKey::from_slice(&bytes) {
break key;
}
};
let context = Secp256k1::new();
let verifying_key = PublicKey::from_secret_key(&context, &signing_key);
let es256k: Es256k<sha2::Sha256> = Es256k::new(context);
let es256k: Es256k<_> = Es256k::default();
let (signing_key, verifying_key) = es256k.generate(&mut rng);
test_algorithm(&es256k, &signing_key, &verifying_key);
}