1#![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
80pub use elliptic_curve::{self, sec1::EncodedPoint, weierstrass::Curve};
82
83pub 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
108pub type SignatureSize<C> = <FieldSize<C> as Add>::Output;
110
111pub type SignatureBytes<C> = GenericArray<u8, SignatureSize<C>>;
113
114#[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 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 #[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 #[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 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 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 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
288pub trait NormalizeLow: Sized {
293 fn normalize_low(&self) -> (Self, bool);
300}