Skip to main content

ecdsa/
lib.rs

1//! Elliptic Curve Digital Signature Algorithm (ECDSA) as specified in
2//! [FIPS 186-4] (Digital Signature Standard)
3//!
4//! ## About
5//!
6//! This crate provides generic ECDSA support which can be used in the
7//! following ways:
8//!
9//! - Generic implementation of ECDSA usable with the following crates:
10//!   - [`k256`] (secp256k1)
11//!   - [`p256`] (NIST P-256)
12//! - ECDSA signature types alone which can be used to provide interoperability
13//!   between other crates that provide an ECDSA implementation:
14//!   - [`p384`] (NIST P-384)
15//!
16//! Any crates which provide an implementation of ECDSA for a particular
17//! elliptic curve can leverage the types from this crate, along with the
18//! [`k256`], [`p256`], and/or [`p384`] crates to expose ECDSA functionality in
19//! a generic, interoperable way by leveraging the [`Signature`] type with in
20//! conjunction with the [`signature::Signer`] and [`signature::Verifier`]
21//! traits.
22//!
23//! For example, the [`ring-compat`] crate implements the [`signature::Signer`]
24//! and [`signature::Verifier`] traits in conjunction with the
25//! [`p256::ecdsa::Signature`] and [`p384::ecdsa::Signature`] types to
26//! wrap the ECDSA implementations from [*ring*] in a generic, interoperable
27//! API.
28//!
29//! ## Minimum Supported Rust Version
30//!
31//! Rust **1.51** or higher.
32//!
33//! Minimum supported Rust version may be changed in the future, but it will be
34//! accompanied with a minor version bump.
35//!
36//! [FIPS 186-4]: https://csrc.nist.gov/publications/detail/fips/186/4/final
37//! [`k256`]: https://docs.rs/k256
38//! [`p256`]: https://docs.rs/p256
39//! [`p256::ecdsa::Signature`]: https://docs.rs/p256/latest/p256/ecdsa/type.Signature.html
40//! [`p384`]: https://docs.rs/p384
41//! [`p384::ecdsa::Signature`]: https://docs.rs/p384/latest/p384/ecdsa/type.Signature.html
42//! [`ring-compat`]: https://docs.rs/ring-compat
43//! [*ring*]: https://docs.rs/ring
44
45#![no_std]
46#![cfg_attr(docsrs, feature(doc_cfg))]
47#![forbid(unsafe_code, clippy::unwrap_used)]
48#![warn(missing_docs, rust_2018_idioms)]
49#![doc(
50    html_logo_url = "https://raw.githubusercontent.com/RustCrypto/media/8f1a9894/logo.svg",
51    html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/media/8f1a9894/logo.svg",
52    html_root_url = "https://docs.rs/ecdsa/0.12.4"
53)]
54
55#[cfg(feature = "alloc")]
56extern crate alloc;
57
58#[cfg(feature = "der")]
59#[cfg_attr(docsrs, doc(cfg(feature = "der")))]
60pub mod der;
61
62#[cfg(feature = "dev")]
63#[cfg_attr(docsrs, doc(cfg(feature = "dev")))]
64pub mod dev;
65
66#[cfg(feature = "hazmat")]
67#[cfg_attr(docsrs, doc(cfg(feature = "hazmat")))]
68pub mod hazmat;
69
70#[cfg(feature = "sign")]
71#[cfg_attr(docsrs, doc(cfg(feature = "sign")))]
72pub mod rfc6979;
73
74#[cfg(feature = "sign")]
75mod sign;
76
77#[cfg(feature = "verify")]
78mod verify;
79
80// Re-export the `elliptic-curve` crate (and select types)
81pub use elliptic_curve::{self, sec1::EncodedPoint, weierstrass::Curve};
82
83// Re-export the `signature` crate (and select types)
84pub use signature::{self, Error, Result};
85
86#[cfg(feature = "sign")]
87#[cfg_attr(docsrs, doc(cfg(feature = "sign")))]
88pub use sign::SigningKey;
89
90#[cfg(feature = "verify")]
91#[cfg_attr(docsrs, doc(cfg(feature = "verify")))]
92pub use verify::VerifyingKey;
93
94use core::{
95    convert::TryFrom,
96    fmt::{self, Debug},
97    ops::Add,
98};
99use elliptic_curve::{
100    bigint::Encoding as _,
101    generic_array::{sequence::Concat, typenum::Unsigned, ArrayLength, GenericArray},
102    FieldBytes, FieldSize, ScalarBytes,
103};
104
105#[cfg(feature = "arithmetic")]
106use elliptic_curve::{group::ff::PrimeField, NonZeroScalar, ProjectiveArithmetic, Scalar};
107
108/// Size of a fixed sized signature for the given elliptic curve.
109pub type SignatureSize<C> = <FieldSize<C> as Add>::Output;
110
111/// Fixed-size byte array containing an ECDSA signature
112pub type SignatureBytes<C> = GenericArray<u8, SignatureSize<C>>;
113
114/// ECDSA signature (fixed-size). Generic over elliptic curve types.
115///
116/// Serialized as fixed-sized big endian scalar values with no added framing:
117///
118/// - `r`: field element size for the given curve, big-endian
119/// - `s`: field element size for the given curve, big-endian
120///
121/// For example, in a curve with a 256-bit modulus like NIST P-256 or
122/// secp256k1, `r` and `s` will both be 32-bytes, resulting in a signature
123/// with a total of 64-bytes.
124///
125/// ASN.1 DER-encoded signatures also supported via the
126/// [`Signature::from_der`] and [`Signature::to_der`] methods.
127#[derive(Clone, Eq, PartialEq)]
128pub struct Signature<C: Curve>
129where
130    SignatureSize<C>: ArrayLength<u8>,
131{
132    bytes: SignatureBytes<C>,
133}
134
135impl<C> Signature<C>
136where
137    C: Curve,
138    SignatureSize<C>: ArrayLength<u8>,
139{
140    /// Create a [`Signature`] from the serialized `r` and `s` scalar values
141    /// which comprise the signature.
142    pub fn from_scalars(r: impl Into<FieldBytes<C>>, s: impl Into<FieldBytes<C>>) -> Result<Self> {
143        Self::try_from(r.into().concat(s.into()).as_slice())
144    }
145
146    /// Parse a signature from ASN.1 DER
147    #[cfg(feature = "der")]
148    #[cfg_attr(docsrs, doc(cfg(feature = "der")))]
149    pub fn from_der(bytes: &[u8]) -> Result<Self>
150    where
151        der::MaxSize<C>: ArrayLength<u8>,
152        <FieldSize<C> as Add>::Output: Add<der::MaxOverhead> + ArrayLength<u8>,
153    {
154        der::Signature::<C>::try_from(bytes).and_then(Self::try_from)
155    }
156
157    /// Serialize this signature as ASN.1 DER
158    #[cfg(feature = "der")]
159    #[cfg_attr(docsrs, doc(cfg(feature = "der")))]
160    pub fn to_der(&self) -> der::Signature<C>
161    where
162        der::MaxSize<C>: ArrayLength<u8>,
163        <FieldSize<C> as Add>::Output: Add<der::MaxOverhead> + ArrayLength<u8>,
164    {
165        let (r, s) = self.bytes.split_at(C::UInt::BYTE_SIZE);
166        der::Signature::from_scalar_bytes(r, s).expect("DER encoding error")
167    }
168}
169
170#[cfg(feature = "arithmetic")]
171#[cfg_attr(docsrs, doc(cfg(feature = "arithmetic")))]
172impl<C> Signature<C>
173where
174    C: Curve + ProjectiveArithmetic,
175    SignatureSize<C>: ArrayLength<u8>,
176{
177    /// Get the `r` component of this signature
178    pub fn r(&self) -> NonZeroScalar<C> {
179        let r_bytes = GenericArray::clone_from_slice(&self.bytes[..C::UInt::BYTE_SIZE]);
180        NonZeroScalar::from_repr(r_bytes)
181            .unwrap_or_else(|| unreachable!("r-component ensured valid in constructor"))
182    }
183
184    /// Get the `s` component of this signature
185    pub fn s(&self) -> NonZeroScalar<C> {
186        let s_bytes = GenericArray::clone_from_slice(&self.bytes[C::UInt::BYTE_SIZE..]);
187        NonZeroScalar::from_repr(s_bytes)
188            .unwrap_or_else(|| unreachable!("r-component ensured valid in constructor"))
189    }
190
191    /// Normalize signature into "low S" form as described in
192    /// [BIP 0062: Dealing with Malleability][1].
193    ///
194    /// [1]: https://github.com/bitcoin/bips/blob/master/bip-0062.mediawiki
195    pub fn normalize_s(&mut self) -> Result<bool>
196    where
197        Scalar<C>: NormalizeLow,
198    {
199        let s_bytes = GenericArray::from_mut_slice(&mut self.bytes[C::UInt::BYTE_SIZE..]);
200        Scalar::<C>::from_repr(s_bytes.clone())
201            .map(|s| {
202                let (s_low, was_high) = s.normalize_low();
203
204                if was_high {
205                    s_bytes.copy_from_slice(&s_low.to_repr());
206                }
207
208                was_high
209            })
210            .ok_or_else(Error::new)
211    }
212}
213
214impl<C> signature::Signature for Signature<C>
215where
216    C: Curve,
217    SignatureSize<C>: ArrayLength<u8>,
218{
219    fn from_bytes(bytes: &[u8]) -> Result<Self> {
220        Self::try_from(bytes)
221    }
222}
223
224impl<C> AsRef<[u8]> for Signature<C>
225where
226    C: Curve,
227    SignatureSize<C>: ArrayLength<u8>,
228{
229    fn as_ref(&self) -> &[u8] {
230        self.bytes.as_slice()
231    }
232}
233
234impl<C> Copy for Signature<C>
235where
236    C: Curve,
237    SignatureSize<C>: ArrayLength<u8>,
238    <SignatureSize<C> as ArrayLength<u8>>::ArrayType: Copy,
239{
240}
241
242impl<C> Debug for Signature<C>
243where
244    C: Curve,
245    SignatureSize<C>: ArrayLength<u8>,
246{
247    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
248        write!(
249            f,
250            "ecdsa::Signature<{:?}>({:?})",
251            C::default(),
252            self.as_ref()
253        )
254    }
255}
256
257impl<C> TryFrom<&[u8]> for Signature<C>
258where
259    C: Curve,
260    SignatureSize<C>: ArrayLength<u8>,
261{
262    type Error = Error;
263
264    fn try_from(bytes: &[u8]) -> Result<Self> {
265        if bytes.len() != <SignatureSize<C>>::to_usize() {
266            return Err(Error::new());
267        }
268
269        for scalar in bytes.chunks_exact(C::UInt::BYTE_SIZE) {
270            if scalar.iter().all(|&byte| byte == 0) {
271                return Err(Error::new());
272            }
273
274            if ScalarBytes::<C>::new(GenericArray::clone_from_slice(scalar))
275                .is_none()
276                .into()
277            {
278                return Err(Error::new());
279            }
280        }
281
282        Ok(Self {
283            bytes: GenericArray::clone_from_slice(bytes),
284        })
285    }
286}
287
288/// Normalize a scalar (i.e. ECDSA S) to the lower half the field, as described
289/// in [BIP 0062: Dealing with Malleability][1].
290///
291/// [1]: https://github.com/bitcoin/bips/blob/master/bip-0062.mediawiki
292pub trait NormalizeLow: Sized {
293    /// Normalize scalar to the lower half of the field (i.e. negate it if it's
294    /// larger than half the curve's order).
295    /// Returns a tuple with the new scalar and a boolean indicating whether the given scalar
296    /// was in the higher half.
297    ///
298    /// May be implemented to work in variable time.
299    fn normalize_low(&self) -> (Self, bool);
300}