Skip to content
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
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

38 changes: 37 additions & 1 deletion ecdsa/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ use core::{
fmt::{self, Debug},
ops::Add,
};
use elliptic_curve::ElementBytes;
use elliptic_curve::{Arithmetic, ElementBytes, FromBytes};
use generic_array::{typenum::Unsigned, ArrayLength, GenericArray};

/// Size of a fixed sized signature for the given elliptic curve.
Expand Down Expand Up @@ -139,6 +139,32 @@ where
}
}

impl<C> Signature<C>
where
C: Curve + Arithmetic,
C::Scalar: NormalizeLow<C>,
SignatureSize<C>: ArrayLength<u8>,
{
/// Normalize signature into "low S" form as described in
/// [BIP 0062: Dealing with Malleability][1].
///
/// [1]: https://github.com/bitcoin/bips/blob/master/bip-0062.mediawiki
pub fn normalize_s(&mut self) -> Result<(), Error> {
let s_bytes = GenericArray::from_mut_slice(&mut self.bytes[C::ElementSize::to_usize()..]);
let s_option = C::Scalar::from_bytes(s_bytes);

// Not constant time, but we're operating on public values
if s_option.is_some().into() {
let mut s = s_option.unwrap();
s.normalize_low();
s_bytes.copy_from_slice(&s.into());
Ok(())
} else {
Err(Error::new())
}
}
}

impl<C: Curve> signature::Signature for Signature<C>
where
SignatureSize<C>: ArrayLength<u8>,
Expand Down Expand Up @@ -206,3 +232,13 @@ where
Signature { bytes }
}
}

/// Normalize a scalar (i.e. ECDSA S) to the lower half the field, as described
/// in [BIP 0062: Dealing with Malleability][1].
///
/// [1]: https://github.com/bitcoin/bips/blob/master/bip-0062.mediawiki
pub trait NormalizeLow<C: Curve> {
/// Normalize scalar to the lower half of the field (i.e. negate it if it's
/// larger than half the curve's order)
fn normalize_low(&mut self);
}