1use crate::{Algorithm, EcdsaCurve, Error, Result, public::EcdsaPublicKey};
4use core::fmt;
5use ctutils::{Choice, CtEq};
6use encoding::{CheckedSum, Decode, Decoder, Encode, Reader, Writer};
7use sec1::consts::{U32, U48, U66};
8use zeroize::Zeroize;
9
10#[cfg(feature = "rand_core")]
11use rand_core::CryptoRng;
12
13#[cfg(all(
14 feature = "rand_core",
15 any(feature = "p256", feature = "p384", feature = "p521")
16))]
17use cipher::cipher::common::Generate;
18
19#[derive(Clone)]
21pub struct EcdsaPrivateKey<const SIZE: usize> {
22 bytes: [u8; SIZE],
24}
25
26impl<const SIZE: usize> EcdsaPrivateKey<SIZE> {
27 pub const MIN_SIZE: usize = 24;
30
31 #[must_use]
33 pub fn as_slice(&self) -> &[u8] {
34 self.bytes.as_ref()
35 }
36
37 #[must_use]
39 pub fn into_bytes(self) -> [u8; SIZE] {
40 self.bytes
41 }
42
43 fn needs_leading_zero(&self) -> bool {
45 self.bytes[0] >= 0x80
46 }
47}
48
49impl<const SIZE: usize> Decode for EcdsaPrivateKey<SIZE> {
50 type Error = Error;
51
52 fn decode(reader: &mut Decoder<impl Reader>) -> Result<Self> {
53 reader.read_prefixed(|reader| {
54 match reader.remaining_len().checked_sub(1) {
56 Some(len) if len <= SIZE => (),
57 _ => return Err(encoding::Error::Length.into()),
58 }
59
60 let mut first = u8::decode(reader)?;
61 if first >= 0x80 {
62 return Err(Error::FormatEncoding);
63 }
64
65 while first == 0 {
67 if reader.is_finished() {
68 return Err(encoding::Error::Length.into());
69 }
70 first = u8::decode(reader)?;
71 }
72
73 let len = reader
74 .remaining_len()
75 .checked_add(1)
76 .ok_or(encoding::Error::Length)?;
77
78 if len < Self::MIN_SIZE || len > SIZE {
79 return Err(encoding::Error::Length.into());
80 }
81
82 let leading_zeros = SIZE.checked_sub(len).ok_or(encoding::Error::Length)?;
85
86 let mut bytes = [0u8; SIZE];
87 let (first_byte, remaining) = bytes[leading_zeros..]
88 .split_first_mut()
89 .ok_or(encoding::Error::Length)?;
90
91 *first_byte = first;
92 reader.read(remaining)?;
93 Ok(Self { bytes })
94 })
95 }
96}
97
98impl<const SIZE: usize> Encode for EcdsaPrivateKey<SIZE> {
99 fn encoded_len(&self) -> encoding::Result<usize> {
100 [4, self.needs_leading_zero().into(), SIZE].checked_sum()
101 }
102
103 fn encode(&self, writer: &mut impl Writer) -> encoding::Result<()> {
104 [self.needs_leading_zero().into(), SIZE]
105 .checked_sum()?
106 .encode(writer)?;
107
108 if self.needs_leading_zero() {
109 writer.write(&[0])?;
110 }
111
112 writer.write(&self.bytes)?;
113 Ok(())
114 }
115}
116
117impl<const SIZE: usize> From<[u8; SIZE]> for EcdsaPrivateKey<SIZE> {
118 fn from(bytes: [u8; SIZE]) -> Self {
119 Self { bytes }
120 }
121}
122
123impl<const SIZE: usize> AsRef<[u8; SIZE]> for EcdsaPrivateKey<SIZE> {
124 fn as_ref(&self) -> &[u8; SIZE] {
125 &self.bytes
126 }
127}
128
129impl<const SIZE: usize> CtEq for EcdsaPrivateKey<SIZE> {
130 fn ct_eq(&self, other: &Self) -> Choice {
131 self.as_ref().ct_eq(other.as_ref())
132 }
133}
134
135impl<const SIZE: usize> PartialEq for EcdsaPrivateKey<SIZE> {
136 fn eq(&self, other: &Self) -> bool {
137 self.ct_eq(other).into()
138 }
139}
140
141impl<const SIZE: usize> Eq for EcdsaPrivateKey<SIZE> {}
142
143impl<const SIZE: usize> fmt::Debug for EcdsaPrivateKey<SIZE> {
144 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
145 f.debug_struct("EcdsaPrivateKey").finish_non_exhaustive()
146 }
147}
148
149impl<const SIZE: usize> fmt::LowerHex for EcdsaPrivateKey<SIZE> {
150 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
151 for byte in self.as_ref() {
152 write!(f, "{byte:02x}")?;
153 }
154 Ok(())
155 }
156}
157
158impl<const SIZE: usize> fmt::UpperHex for EcdsaPrivateKey<SIZE> {
159 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
160 for byte in self.as_ref() {
161 write!(f, "{byte:02X}")?;
162 }
163 Ok(())
164 }
165}
166
167impl<const SIZE: usize> Drop for EcdsaPrivateKey<SIZE> {
168 fn drop(&mut self) {
169 self.bytes.zeroize();
170 }
171}
172
173#[cfg(feature = "p256")]
174impl From<p256::SecretKey> for EcdsaPrivateKey<32> {
175 fn from(sk: p256::SecretKey) -> EcdsaPrivateKey<32> {
176 EcdsaPrivateKey {
177 bytes: sk.to_bytes().into(),
178 }
179 }
180}
181
182#[cfg(feature = "p384")]
183impl From<p384::SecretKey> for EcdsaPrivateKey<48> {
184 fn from(sk: p384::SecretKey) -> EcdsaPrivateKey<48> {
185 EcdsaPrivateKey {
186 bytes: sk.to_bytes().into(),
187 }
188 }
189}
190
191#[cfg(feature = "p521")]
192impl From<p521::SecretKey> for EcdsaPrivateKey<66> {
193 fn from(sk: p521::SecretKey) -> EcdsaPrivateKey<66> {
194 let mut bytes = [0u8; 66];
196 bytes.copy_from_slice(&sk.to_bytes());
197 EcdsaPrivateKey { bytes }
198 }
199}
200
201#[derive(Clone, Debug)]
203pub enum EcdsaKeypair {
204 NistP256 {
206 public: sec1::EncodedPoint<U32>,
208
209 private: EcdsaPrivateKey<32>,
211 },
212
213 NistP384 {
215 public: sec1::EncodedPoint<U48>,
217
218 private: EcdsaPrivateKey<48>,
220 },
221
222 NistP521 {
224 public: sec1::EncodedPoint<U66>,
226
227 private: EcdsaPrivateKey<66>,
229 },
230}
231
232impl EcdsaKeypair {
233 #[cfg(feature = "rand_core")]
239 #[allow(unused_variables)]
240 pub fn random<R: CryptoRng + ?Sized>(rng: &mut R, curve: EcdsaCurve) -> Result<Self> {
241 match curve {
242 #[cfg(feature = "p256")]
243 EcdsaCurve::NistP256 => {
244 let private = p256::SecretKey::generate_from_rng(rng);
245 let public = private.public_key();
246 Ok(EcdsaKeypair::NistP256 {
247 private: private.into(),
248 public: public.into(),
249 })
250 }
251 #[cfg(feature = "p384")]
252 EcdsaCurve::NistP384 => {
253 let private = p384::SecretKey::generate_from_rng(rng);
254 let public = private.public_key();
255 Ok(EcdsaKeypair::NistP384 {
256 private: private.into(),
257 public: public.into(),
258 })
259 }
260 #[cfg(feature = "p521")]
261 EcdsaCurve::NistP521 => {
262 let private = p521::SecretKey::generate_from_rng(rng);
263 let public = private.public_key();
264 Ok(EcdsaKeypair::NistP521 {
265 private: private.into(),
266 public: public.into(),
267 })
268 }
269 #[cfg(not(all(feature = "p256", feature = "p384", feature = "p521")))]
270 _ => Err(Error::AlgorithmUnsupported {
271 algorithm: curve.into(),
272 }),
273 }
274 }
275
276 #[must_use]
278 pub fn algorithm(&self) -> Algorithm {
279 Algorithm::Ecdsa {
280 curve: self.curve(),
281 }
282 }
283
284 #[must_use]
286 pub fn curve(&self) -> EcdsaCurve {
287 match self {
288 Self::NistP256 { .. } => EcdsaCurve::NistP256,
289 Self::NistP384 { .. } => EcdsaCurve::NistP384,
290 Self::NistP521 { .. } => EcdsaCurve::NistP521,
291 }
292 }
293
294 #[must_use]
296 pub fn public_key_bytes(&self) -> &[u8] {
297 match self {
298 Self::NistP256 { public, .. } => public.as_ref(),
299 Self::NistP384 { public, .. } => public.as_ref(),
300 Self::NistP521 { public, .. } => public.as_ref(),
301 }
302 }
303
304 #[must_use]
306 pub fn private_key_bytes(&self) -> &[u8] {
307 match self {
308 Self::NistP256 { private, .. } => private.as_ref(),
309 Self::NistP384 { private, .. } => private.as_ref(),
310 Self::NistP521 { private, .. } => private.as_ref(),
311 }
312 }
313}
314
315impl CtEq for EcdsaKeypair {
316 fn ct_eq(&self, other: &Self) -> Choice {
317 let public_eq = Choice::from(u8::from(
318 EcdsaPublicKey::from(self) == EcdsaPublicKey::from(other),
319 ));
320
321 let private_key_a = match self {
322 Self::NistP256 { private, .. } => private.as_slice(),
323 Self::NistP384 { private, .. } => private.as_slice(),
324 Self::NistP521 { private, .. } => private.as_slice(),
325 };
326
327 let private_key_b = match other {
328 Self::NistP256 { private, .. } => private.as_slice(),
329 Self::NistP384 { private, .. } => private.as_slice(),
330 Self::NistP521 { private, .. } => private.as_slice(),
331 };
332
333 public_eq & private_key_a.ct_eq(private_key_b)
334 }
335}
336
337impl Eq for EcdsaKeypair {}
338
339impl PartialEq for EcdsaKeypair {
340 fn eq(&self, other: &Self) -> bool {
341 self.ct_eq(other).into()
342 }
343}
344
345impl Decode for EcdsaKeypair {
346 type Error = Error;
347
348 fn decode(reader: &mut Decoder<impl Reader>) -> Result<Self> {
349 match EcdsaPublicKey::decode(reader)? {
350 EcdsaPublicKey::NistP256(public) => {
351 let private = EcdsaPrivateKey::<32>::decode(reader)?;
352 Ok(Self::NistP256 { public, private })
353 }
354 EcdsaPublicKey::NistP384(public) => {
355 let private = EcdsaPrivateKey::<48>::decode(reader)?;
356 Ok(Self::NistP384 { public, private })
357 }
358 EcdsaPublicKey::NistP521(public) => {
359 let private = EcdsaPrivateKey::<66>::decode(reader)?;
360 Ok(Self::NistP521 { public, private })
361 }
362 }
363 }
364}
365
366impl Encode for EcdsaKeypair {
367 fn encoded_len(&self) -> encoding::Result<usize> {
368 let public_len = EcdsaPublicKey::from(self).encoded_len()?;
369
370 let private_len = match self {
371 Self::NistP256 { private, .. } => private.encoded_len()?,
372 Self::NistP384 { private, .. } => private.encoded_len()?,
373 Self::NistP521 { private, .. } => private.encoded_len()?,
374 };
375
376 [public_len, private_len].checked_sum()
377 }
378
379 fn encode(&self, writer: &mut impl Writer) -> encoding::Result<()> {
380 EcdsaPublicKey::from(self).encode(writer)?;
381
382 match self {
383 Self::NistP256 { private, .. } => private.encode(writer)?,
384 Self::NistP384 { private, .. } => private.encode(writer)?,
385 Self::NistP521 { private, .. } => private.encode(writer)?,
386 }
387
388 Ok(())
389 }
390}
391
392impl From<EcdsaKeypair> for EcdsaPublicKey {
393 fn from(keypair: EcdsaKeypair) -> EcdsaPublicKey {
394 EcdsaPublicKey::from(&keypair)
395 }
396}
397
398impl From<&EcdsaKeypair> for EcdsaPublicKey {
399 fn from(keypair: &EcdsaKeypair) -> EcdsaPublicKey {
400 match keypair {
401 EcdsaKeypair::NistP256 { public, .. } => EcdsaPublicKey::NistP256(*public),
402 EcdsaKeypair::NistP384 { public, .. } => EcdsaPublicKey::NistP384(*public),
403 EcdsaKeypair::NistP521 { public, .. } => EcdsaPublicKey::NistP521(*public),
404 }
405 }
406}