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

Implement recoverable signatures for ECDSA-Secp256k1 #408

Merged
merged 2 commits into from
Mar 14, 2023
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
3 changes: 3 additions & 0 deletions src/ecdsa/secp256k1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,8 @@ pub use k256::Secp256k1;
/// ECDSA/secp256k1 signature (fixed-size)
pub type Signature = super::Signature<Secp256k1>;

/// ECDSA/secp256k1 signature recovery id (ala Ethereum)
pub type RecoveryId = ecdsa::RecoveryId;

/// ECDSA/secp256k1 signer
pub type Signer = super::Signer<Secp256k1>;
80 changes: 62 additions & 18 deletions src/ecdsa/signer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use signature::{digest::Digest, hazmat::PrehashSigner, DigestSigner, Error, Keyp
use std::ops::Add;

#[cfg(feature = "secp256k1")]
use super::Secp256k1;
use super::{secp256k1::RecoveryId, Secp256k1};

/// ECDSA signature provider for yubihsm-client
#[derive(signature::Signer)]
Expand Down Expand Up @@ -70,6 +70,22 @@ where
}
}

impl<C> Signer<C>
where
C: CurveAlgorithm + CurveArithmetic + PointCompression + PrimeCurve,
FieldBytesSize<C>: sec1::ModulusSize,
SignatureSize<C>: ArrayLength<u8>,
ecdsa::der::MaxSize<C>: ArrayLength<u8>,
<FieldBytesSize<C> as Add>::Output: Add<ecdsa::der::MaxOverhead> + ArrayLength<u8>,
{
fn sign_prehash_ecdsa(&self, prehash: &[u8]) -> Result<Signature<C>, Error> {
self.client
.sign_ecdsa_prehash_raw(self.signing_key_id, prehash)
.map_err(Error::from_source)
.and_then(|der| Signature::from_der(&der))
}
}

impl<C> AsRef<VerifyingKey<C>> for Signer<C>
where
C: CurveAlgorithm + CurveArithmetic + PointCompression + PrimeCurve,
Expand Down Expand Up @@ -101,19 +117,10 @@ where
type VerifyingKey = VerifyingKey<C>;
}

impl<C> PrehashSigner<Signature<C>> for Signer<C>
where
C: CurveAlgorithm + CurveArithmetic + PointCompression + PrimeCurve,
FieldBytesSize<C>: sec1::ModulusSize,
SignatureSize<C>: ArrayLength<u8>,
ecdsa::der::MaxSize<C>: ArrayLength<u8>,
<FieldBytesSize<C> as Add>::Output: Add<ecdsa::der::MaxOverhead> + ArrayLength<u8>,
{
fn sign_prehash(&self, prehash: &[u8]) -> Result<Signature<C>, Error> {
self.client
.sign_ecdsa_prehash_raw(self.signing_key_id, prehash)
.map_err(Error::from_source)
.and_then(|der| Signature::from_der(&der))
impl PrehashSigner<Signature<NistP256>> for Signer<NistP256> {
/// Compute a fixed-size P-256 ECDSA signature of a digest output.
fn sign_prehash(&self, prehash: &[u8]) -> Result<Signature<NistP256>, Error> {
self.sign_prehash_ecdsa(prehash)
}
}

Expand All @@ -127,6 +134,13 @@ where
}
}

impl PrehashSigner<Signature<NistP384>> for Signer<NistP384> {
/// Compute a fixed-size P-384 ECDSA signature of a digest output.
fn sign_prehash(&self, prehash: &[u8]) -> Result<Signature<NistP384>, Error> {
self.sign_prehash_ecdsa(prehash)
}
}

impl<D> DigestSigner<D, Signature<NistP384>> for Signer<NistP384>
where
D: Digest<OutputSize = U32> + Default,
Expand All @@ -137,17 +151,47 @@ where
}
}

#[cfg(feature = "secp256k1")]
impl PrehashSigner<Signature<Secp256k1>> for Signer<Secp256k1> {
fn sign_prehash(&self, prehash: &[u8]) -> Result<Signature<Secp256k1>, Error> {
let signature = self.sign_prehash_ecdsa(prehash)?;
// Low-S normalize per BIP 0062: Dealing with Malleability:
// <https://github.com/bitcoin/bips/blob/master/bip-0062.mediawiki>
Ok(signature.normalize_s().unwrap_or(signature))
}
}

#[cfg(feature = "secp256k1")]
impl PrehashSigner<(Signature<Secp256k1>, RecoveryId)> for Signer<Secp256k1> {
/// Compute a fixed-size secp256k1 ECDSA signature of a digest output along with the recovery
/// ID.
fn sign_prehash(&self, prehash: &[u8]) -> Result<(Signature<Secp256k1>, RecoveryId), Error> {
let signature = self.sign_prehash(prehash)?;
let recovery_id =
RecoveryId::trial_recovery_from_prehash(&self.verifying_key, prehash, &signature)?;
Ok((signature, recovery_id))
}
}

#[cfg(feature = "secp256k1")]
impl<D> DigestSigner<D, Signature<Secp256k1>> for Signer<Secp256k1>
where
D: Digest<OutputSize = U32> + Default,
{
/// Compute a fixed-size secp256k1 ECDSA signature of the given digest
fn try_sign_digest(&self, digest: D) -> Result<Signature<Secp256k1>, Error> {
let signature = self.sign_prehash(&digest.finalize())?;
self.sign_prehash(&digest.finalize())
}
}

// Low-S normalize per BIP 0062: Dealing with Malleability:
// <https://github.com/bitcoin/bips/blob/master/bip-0062.mediawiki>
Ok(signature.normalize_s().unwrap_or(signature))
#[cfg(feature = "secp256k1")]
impl<D> DigestSigner<D, (Signature<Secp256k1>, RecoveryId)> for Signer<Secp256k1>
where
D: Digest<OutputSize = U32> + Default,
{
/// Compute a fixed-size secp256k1 ECDSA signature of the given digest along with the recovery
/// ID.
fn try_sign_digest(&self, digest: D) -> Result<(Signature<Secp256k1>, RecoveryId), Error> {
self.sign_prehash(&digest.finalize())
}
}
30 changes: 29 additions & 1 deletion tests/ecdsa/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@ use ::ecdsa::{
sec1::{self, FromEncodedPoint, ToEncodedPoint},
AffinePoint, CurveArithmetic, FieldBytesSize, PrimeCurve,
},
signature::Verifier,
signature::{
digest::Digest,
Verifier, {DigestSigner, DigestVerifier},
},
};
use yubihsm::{
asymmetric::signature::Signer as _,
Expand Down Expand Up @@ -79,3 +82,28 @@ fn ecdsa_secp256k1_sign_test() {
let signature: ecdsa::Signature<Secp256k1> = signer.sign(TEST_MESSAGE);
assert!(verify_key.verify(TEST_MESSAGE, &signature).is_ok());
}

#[cfg(feature = "secp256k1")]
#[test]
fn ecdsa_secp256k1_sign_recover_test() {
use k256::{ecdsa::VerifyingKey, PublicKey};

let signer = create_signer::<Secp256k1>(203);
let verify_key = VerifyingKey::from_encoded_point(&signer.public_key()).unwrap();

let digest = sha2::Sha256::new_with_prefix(TEST_MESSAGE);

let (signature, recovery_id) = signer.try_sign_digest(digest.clone()).unwrap();

assert!(verify_key.verify(TEST_MESSAGE, &signature).is_ok());

let recovered_key =
VerifyingKey::recover_from_digest(digest.clone(), &signature, recovery_id).unwrap();
recovered_key
.verify_digest(digest.clone(), &signature)
.unwrap();

let recovered_pk = PublicKey::from(recovered_key);
let signer_pk = PublicKey::from_encoded_point(signer.public_key()).unwrap();
assert_eq!(&recovered_pk, &signer_pk);
}