1use crate::{Error, Result};
4use core::{
5 convert::{TryFrom, TryInto},
6 fmt,
7 ops::{Add, Range},
8};
9use der::{asn1::UIntBytes, Decodable};
10use elliptic_curve::{
11 bigint::Encoding as _,
12 consts::U9,
13 generic_array::{ArrayLength, GenericArray},
14 weierstrass::Curve,
15 FieldSize,
16};
17
18#[cfg(feature = "alloc")]
19use alloc::boxed::Box;
20
21pub type MaxOverhead = U9;
36
37pub type MaxSize<C> = <<FieldSize<C> as Add>::Output as Add<MaxOverhead>>::Output;
39
40type SignatureBytes<C> = GenericArray<u8, MaxSize<C>>;
42
43pub struct Signature<C>
47where
48 C: Curve,
49 MaxSize<C>: ArrayLength<u8>,
50 <FieldSize<C> as Add>::Output: Add<MaxOverhead> + ArrayLength<u8>,
51{
52 bytes: SignatureBytes<C>,
54
55 r_range: Range<usize>,
57
58 s_range: Range<usize>,
60}
61
62impl<C> signature::Signature for Signature<C>
63where
64 C: Curve,
65 MaxSize<C>: ArrayLength<u8>,
66 <FieldSize<C> as Add>::Output: Add<MaxOverhead> + ArrayLength<u8>,
67{
68 fn from_bytes(bytes: &[u8]) -> Result<Self> {
70 bytes.try_into()
71 }
72}
73
74#[allow(clippy::len_without_is_empty)]
75impl<C> Signature<C>
76where
77 C: Curve,
78 MaxSize<C>: ArrayLength<u8>,
79 <FieldSize<C> as Add>::Output: Add<MaxOverhead> + ArrayLength<u8>,
80{
81 pub fn len(&self) -> usize {
83 self.s_range.end
84 }
85
86 pub fn as_bytes(&self) -> &[u8] {
88 &self.bytes.as_slice()[..self.len()]
89 }
90
91 #[cfg(feature = "alloc")]
93 pub fn to_bytes(&self) -> Box<[u8]> {
94 self.as_bytes().to_vec().into_boxed_slice()
95 }
96
97 pub(crate) fn from_scalar_bytes(r: &[u8], s: &[u8]) -> der::Result<Self> {
99 let mut bytes = SignatureBytes::<C>::default();
100 let mut encoder = der::Encoder::new(&mut bytes);
101 encoder.message(&[&UIntBytes::new(r)?, &UIntBytes::new(s)?])?;
102
103 let sig = encoder.finish()?;
104 sig.try_into().map_err(|_| der::Tag::Sequence.value_error())
105 }
106
107 pub(crate) fn r(&self) -> &[u8] {
109 &self.bytes[self.r_range.clone()]
110 }
111
112 pub(crate) fn s(&self) -> &[u8] {
114 &self.bytes[self.s_range.clone()]
115 }
116}
117
118impl<C> AsRef<[u8]> for Signature<C>
119where
120 C: Curve,
121 MaxSize<C>: ArrayLength<u8>,
122 <FieldSize<C> as Add>::Output: Add<MaxOverhead> + ArrayLength<u8>,
123{
124 fn as_ref(&self) -> &[u8] {
125 self.as_bytes()
126 }
127}
128
129impl<C> fmt::Debug for Signature<C>
130where
131 C: Curve,
132 MaxSize<C>: ArrayLength<u8>,
133 <FieldSize<C> as Add>::Output: Add<MaxOverhead> + ArrayLength<u8>,
134{
135 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
136 f.debug_struct("asn1::Signature")
137 .field("r", &self.r())
138 .field("s", &self.s())
139 .finish()
140 }
141}
142
143impl<C> TryFrom<&[u8]> for Signature<C>
144where
145 C: Curve,
146 MaxSize<C>: ArrayLength<u8>,
147 <FieldSize<C> as Add>::Output: Add<MaxOverhead> + ArrayLength<u8>,
148{
149 type Error = Error;
150
151 fn try_from(input: &[u8]) -> Result<Self> {
152 let (r, s) = der::Decoder::new(input)
153 .sequence(|decoder| Ok((UIntBytes::decode(decoder)?, UIntBytes::decode(decoder)?)))
154 .map_err(|_| Error::new())?;
155
156 if r.as_bytes().len() > C::UInt::BYTE_SIZE || s.as_bytes().len() > C::UInt::BYTE_SIZE {
157 return Err(Error::new());
158 }
159
160 let r_range = find_scalar_range(input, r.as_bytes())?;
161 let s_range = find_scalar_range(input, s.as_bytes())?;
162
163 if s_range.end != input.len() {
164 return Err(Error::new());
165 }
166
167 let mut bytes = SignatureBytes::<C>::default();
168 bytes[..s_range.end].copy_from_slice(input);
169
170 Ok(Signature {
171 bytes,
172 r_range,
173 s_range,
174 })
175 }
176}
177
178impl<C> TryFrom<Signature<C>> for super::Signature<C>
179where
180 C: Curve,
181 MaxSize<C>: ArrayLength<u8>,
182 <FieldSize<C> as Add>::Output: Add<MaxOverhead> + ArrayLength<u8>,
183{
184 type Error = Error;
185
186 fn try_from(sig: Signature<C>) -> Result<super::Signature<C>> {
187 let mut bytes = super::SignatureBytes::<C>::default();
188 let r_begin = C::UInt::BYTE_SIZE.saturating_sub(sig.r().len());
189 let s_begin = bytes.len().saturating_sub(sig.s().len());
190 bytes[r_begin..C::UInt::BYTE_SIZE].copy_from_slice(sig.r());
191 bytes[s_begin..].copy_from_slice(sig.s());
192 Self::try_from(bytes.as_slice())
193 }
194}
195
196fn find_scalar_range(outer: &[u8], inner: &[u8]) -> Result<Range<usize>> {
198 let outer_start = outer.as_ptr() as usize;
199 let inner_start = inner.as_ptr() as usize;
200 let start = inner_start
201 .checked_sub(outer_start)
202 .ok_or_else(Error::new)?;
203 let end = start.checked_add(inner.len()).ok_or_else(Error::new)?;
204 Ok(Range { start, end })
205}
206
207#[cfg(all(feature = "digest", feature = "hazmat"))]
208impl<C> signature::PrehashSignature for Signature<C>
209where
210 C: Curve + crate::hazmat::DigestPrimitive,
211 MaxSize<C>: ArrayLength<u8>,
212 <FieldSize<C> as Add>::Output: Add<MaxOverhead> + ArrayLength<u8>,
213{
214 type Digest = C::Digest;
215}
216
217#[cfg(all(test, feature = "arithmetic"))]
218mod tests {
219 use elliptic_curve::dev::MockCurve;
220 use signature::Signature as _;
221
222 type Signature = crate::Signature<MockCurve>;
223
224 const EXAMPLE_SIGNATURE: [u8; 64] = [
225 0xf3, 0xac, 0x80, 0x61, 0xb5, 0x14, 0x79, 0x5b, 0x88, 0x43, 0xe3, 0xd6, 0x62, 0x95, 0x27,
226 0xed, 0x2a, 0xfd, 0x6b, 0x1f, 0x6a, 0x55, 0x5a, 0x7a, 0xca, 0xbb, 0x5e, 0x6f, 0x79, 0xc8,
227 0xc2, 0xac, 0x8b, 0xf7, 0x78, 0x19, 0xca, 0x5, 0xa6, 0xb2, 0x78, 0x6c, 0x76, 0x26, 0x2b,
228 0xf7, 0x37, 0x1c, 0xef, 0x97, 0xb2, 0x18, 0xe9, 0x6f, 0x17, 0x5a, 0x3c, 0xcd, 0xda, 0x2a,
229 0xcc, 0x5, 0x89, 0x3,
230 ];
231
232 #[test]
233 fn test_fixed_to_asn1_signature_roundtrip() {
234 let signature1 = Signature::from_bytes(&EXAMPLE_SIGNATURE).unwrap();
235
236 let asn1_signature = signature1.to_der();
238 let signature2 = Signature::from_der(asn1_signature.as_ref()).unwrap();
239
240 assert_eq!(signature1, signature2);
241 }
242
243 #[test]
244 fn test_asn1_too_short_signature() {
245 assert!(Signature::from_der(&[]).is_err());
246 assert!(Signature::from_der(&[der::Tag::Sequence.into()]).is_err());
247 assert!(Signature::from_der(&[der::Tag::Sequence.into(), 0x00]).is_err());
248 assert!(Signature::from_der(&[
249 der::Tag::Sequence.into(),
250 0x03,
251 der::Tag::Integer.into(),
252 0x01,
253 0x01
254 ])
255 .is_err());
256 }
257
258 #[test]
259 fn test_asn1_non_der_signature() {
260 assert!(Signature::from_der(&[
262 der::Tag::Sequence.into(),
263 0x06, der::Tag::Integer.into(),
265 0x01, 0x01, der::Tag::Integer.into(),
268 0x01, 0x01, ])
271 .is_ok());
272
273 assert!(Signature::from_der(&[
277 der::Tag::Sequence.into(),
278 0x81, 0x06, der::Tag::Integer.into(),
281 0x01, 0x01, der::Tag::Integer.into(),
284 0x01, 0x01, ])
287 .is_err());
288 }
289}