Debian Codegraph @

third_party/rust/mls-rs-crypto-nss/src/ec.rs

raw
1 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 // Copyright by contributors to this project.
3 // SPDX-License-Identifier: (Apache-2.0 OR MIT)
4
5 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
6 // SPDX-License-Identifier: Apache-2.0
7
8 use nss_gk_api::{PrivateKey, PublicKey};
9
10 use alloc::vec::Vec;
11 use mls_rs_crypto_traits::Curve;
12
13 #[cfg(feature = "std")]
14 use std::array::TryFromSliceError;
15
16 #[cfg(not(feature = "std"))]
17 use core::array::TryFromSliceError;
18 use core::fmt::{self, Debug};
19
20 use crate::Hash;
21
22 #[derive(Debug, Clone)]
23 pub enum EcPublicKey {
24 X25519(nss_gk_api::PublicKey),
25 Ed25519(nss_gk_api::PublicKey),
26 P256(nss_gk_api::PublicKey),
27 }
28
29 #[derive(Clone)]
30 pub enum EcPrivateKey {
31 X25519(nss_gk_api::PrivateKey),
32 Ed25519(nss_gk_api::PrivateKey),
33 P256(nss_gk_api::PrivateKey),
34 }
35
36 #[derive(Debug)]
37 #[cfg_attr(feature = "std", derive(thiserror::Error))]
38 pub enum EcError {
39 #[cfg_attr(feature = "std", error("unsupported curve type"))]
40 UnsupportedCurve,
41 #[cfg_attr(feature = "std", error("invalid public key data"))]
42 EcKeyInvalidKeyData,
43 #[cfg_attr(feature = "std", error("ec key is not a signature key"))]
44 EcKeyNotSignature,
45 #[cfg_attr(feature = "std", error(transparent))]
46 TryFromSliceError(TryFromSliceError),
47 #[cfg_attr(feature = "std", error("rand error: {0:?}"))]
48 RandCoreError(rand_core::Error),
49 #[cfg_attr(feature = "std", error("ecdh key type mismatch"))]
50 EcdhKeyTypeMismatch,
51 #[cfg_attr(feature = "std", error("ec key is not an ecdh key"))]
52 EcKeyNotEcdh,
53 #[cfg_attr(feature = "std", error("general nss failure"))]
54 GeneralFailure,
55 }
56
57 // Constants
58 pub const DER_SEQUENCE: u8 = 0x30;
59 pub const DER_INTEGER: u8 = 0x02;
60 pub const DER_BITSTRING: u8 = 0x03;
61 pub const DER_OCTETSTRING: u8 = 0x04;
62
63 impl From<rand_core::Error> for EcError {
64 fn from(value: rand_core::Error) -> Self {
65 EcError::RandCoreError(value)
66 }
67 }
68
69 impl From<TryFromSliceError> for EcError {
70 fn from(e: TryFromSliceError) -> Self {
71 EcError::TryFromSliceError(e)
72 }
73 }
74
75 impl core::fmt::Debug for EcPrivateKey {
76 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
77 match self {
78 Self::X25519(_) => f.write_str("X25519 Secret Key"),
79 Self::Ed25519(_) => f.write_str("Ed25519 Secret Key"),
80 Self::P256(_) => f.write_str("P256 Secret Key"),
81 }
82 }
83 }
84
85 fn private_key_len(curve: Curve) -> usize {
86 match curve {
87 Curve::P256 => 0x20 as usize,
88 Curve::Ed25519 | Curve::X25519 => 0x20 as usize,
89 _ => 0 as usize,
90 }
91 }
92
93 fn public_key_len(curve: Curve) -> usize {
94 match curve {
95 Curve::P256 => 0x41 as usize,
96 Curve::Ed25519 | Curve::X25519 => 32 as usize,
97 _ => 0 as usize,
98 }
99 }
100
101 fn max_size_ecdsa_part(curve: Curve) -> Result<usize, EcError> {
102 // Currently supporting only ECDSA_P256
103 match curve {
104 Curve::P256 => return Ok(0x20),
105 _ => return Err(EcError::EcKeyInvalidKeyData),
106 }
107 }
108
109 fn build_spki_from_raw_public_key(key: Vec<u8>, curve: Curve) -> Result<Vec<u8>, EcError> {
110 let mut lh = {
111 match curve {
112 Curve::P256 => vec![
113 DER_SEQUENCE,
114 0x59, // length
115 DER_SEQUENCE,
116 0x13, // length of the curve ID
117 0x06,
118 0x07,
119 0x2a,
120 0x86,
121 0x48,
122 0xce,
123 0x3d,
124 0x02,
125 0x01,
126 0x06, // curve identifier
127 0x08,
128 0x2a,
129 0x86,
130 0x48,
131 0xce,
132 0x3d,
133 0x03,
134 0x01,
135 0x07,
136 DER_BITSTRING,
137 0x42, // length
138 0x00,
139 ],
140 Curve::Ed25519 => vec![
141 DER_SEQUENCE,
142 0x2a, //length
143 DER_SEQUENCE,
144 0x5, // length of the curve ID
145 0x6,
146 0x3,
147 0x2b,
148 0x65,
149 0x70, // curve identifier
150 DER_BITSTRING,
151 0x21,
152 0x0,
153 ],
154 Curve::X25519 => vec![
155 DER_SEQUENCE,
156 0x2a, // length of the signature
157 DER_SEQUENCE,
158 0x5, // length of the curve ID
159 0x6,
160 0x3,
161 0x2b,
162 0x65,
163 0x6e, // curve identifier
164 DER_BITSTRING,
165 0x21, // length
166 0x0,
167 ],
168 _ => return Err(EcError::UnsupportedCurve),
169 }
170 };
171
172 let mut key = key.clone();
173
174 // Not supported
175 if public_key_len(curve) == 0 {
176 return Err(EcError::EcKeyInvalidKeyData);
177 }
178
179 // if the key length is bigger than the expected -> wrong key
180 if key.len() > public_key_len(curve) {
181 // checking if the first two bytes are the encoding
182 if key[0] != DER_OCTETSTRING
183 && key[1] as usize != public_key_len(curve)
184 && key.len() != public_key_len(curve) + 2
185 {
186 return Err(EcError::EcKeyInvalidKeyData);
187 } else {
188 let (_, key) = key.split_at(2);
189 return build_spki_from_raw_public_key(key.to_vec(), curve);
190 }
191 }
192
193 // if the key length is shorted than expected -> extend the key
194 if key.len() < public_key_len(curve) {
195 let mut zeros = vec![0 as u8; public_key_len(curve) - key.len()];
196 zeros.append(&mut key);
197 lh.append(&mut zeros);
198 } else {
199 lh.append(&mut key);
200 }
201
202 Ok(lh)
203 }
204
205 pub fn pub_key_from_uncompressed(bytes: Vec<u8>, curve: Curve) -> Result<EcPublicKey, EcError> {
206 let z = build_spki_from_raw_public_key(bytes, curve).unwrap();
207 match curve {
208 Curve::P256 => match nss_gk_api::ec::import_ec_public_key_from_spki(&z) {
209 Ok(key) => return Ok(EcPublicKey::P256(key)),
210 Err(_) => return Err(EcError::EcKeyInvalidKeyData),
211 },
212 Curve::Ed25519 => match nss_gk_api::ec::import_ec_public_key_from_spki(&z) {
213 Ok(key) => return Ok(EcPublicKey::Ed25519(key)),
214 Err(_) => return Err(EcError::EcKeyInvalidKeyData),
215 },
216 Curve::X25519 => match nss_gk_api::ec::import_ec_public_key_from_spki(&z) {
217 Ok(key) => return Ok(EcPublicKey::X25519(key)),
218 Err(_) => return Err(EcError::EcKeyInvalidKeyData),
219 },
220 _ => Err(EcError::UnsupportedCurve),
221 }
222 }
223
224 pub fn pub_key_to_uncompressed(key: EcPublicKey) -> Result<Vec<u8>, EcError> {
225 match key {
226 EcPublicKey::Ed25519(key) | EcPublicKey::X25519(key) => {
227 let k0 = key.key_data_alt().unwrap();
228 Ok(k0.to_vec())
229 }
230
231 EcPublicKey::P256(key) => {
232 let k0 = key.key_data_alt().unwrap();
233 if k0.len() == public_key_len(Curve::P256) {
234 return Ok(k0.to_vec());
235 };
236
237 // The key is encoded
238
239 if k0[0] != DER_OCTETSTRING {
240 return Err(EcError::EcKeyInvalidKeyData);
241 }
242 if k0[1] as usize != public_key_len(Curve::P256) {
243 return Err(EcError::EcKeyInvalidKeyData);
244 }
245
246 let (_, key) = k0.split_at(2);
247 Ok(key.to_vec())
248 }
249 }
250 }
251
252 pub fn generate_private_key(curve: Curve) -> Result<EcPrivateKey, EcError> {
253 let key_pair = nss_gk_api::ec::ecdh_keygen(nss_gk_api::ec::EcCurve::P256).unwrap();
254 match curve {
255 Curve::P256 => return Ok(EcPrivateKey::P256(key_pair.private)),
256 Curve::X25519 => return Ok(EcPrivateKey::X25519(key_pair.private)),
257 Curve::Ed25519 => return Ok(EcPrivateKey::Ed25519(key_pair.private)),
258 _ => Err(EcError::UnsupportedCurve),
259 }
260 }
261
262 // I think that instead of raw bytes, we should use pkcs8/spki
263 #[allow(dead_code)]
264 pub fn private_key_from_pkcs8(bytes: &[u8], curve: Curve) -> Result<EcPrivateKey, EcError> {
265 let private_key = nss_gk_api::ec::import_ec_private_key_pkcs8(bytes).unwrap();
266 match curve {
267 Curve::P256 => return Ok(EcPrivateKey::P256(private_key)),
268 Curve::Ed25519 => return Ok(EcPrivateKey::Ed25519(private_key)),
269 Curve::X25519 => return Ok(EcPrivateKey::X25519(private_key)),
270 _ => Err(EcError::UnsupportedCurve),
271 }
272 }
273
274 #[allow(dead_code)]
275 pub fn private_key_to_pkcs8(key: EcPrivateKey) -> Result<Vec<u8>, EcError> {
276 match key {
277 EcPrivateKey::P256(key) | EcPrivateKey::Ed25519(key) | EcPrivateKey::X25519(key) => {
278 match nss_gk_api::ec::export_ec_private_key_pkcs8(key) {
279 Ok(key) => return Ok(key),
280 Err(_) => return Err(EcError::EcKeyInvalidKeyData),
281 }
282 }
283 }
284 }
285
286 fn build_pkcs8_from_raw_private_key(key: Vec<u8>, curve: Curve) -> Result<Vec<u8>, EcError> {
287 let mut lh = {
288 match curve {
289 Curve::P256 => vec![
290 DER_SEQUENCE,
291 0x41, // length
292 DER_INTEGER,
293 0x1,
294 0x0, // Key type
295 DER_SEQUENCE,
296 0x13,
297 0x6,
298 0x7,
299 0x2a,
300 0x86,
301 0x48,
302 0xce,
303 0x3d,
304 0x2,
305 0x1,
306 0x6,
307 0x8,
308 0x2a,
309 0x86,
310 0x48,
311 0xce,
312 0x3d,
313 0x3,
314 0x1,
315 0x7, // Curve
316 // See P256 encoding
317 0x4,
318 0x27,
319 0x30,
320 0x25,
321 0x2,
322 0x1,
323 0x1,
324 0x4,
325 0x20,
326 ],
327 Curve::Ed25519 => vec![
328 DER_SEQUENCE,
329 0x2e,
330 DER_INTEGER,
331 0x01,
332 0x00, // Key type
333 DER_SEQUENCE,
334 0x05,
335 0x06,
336 0x03,
337 0x2b,
338 0x65,
339 0x70, //Curve
340 DER_OCTETSTRING,
341 0x22,
342 DER_OCTETSTRING,
343 0x20,
344 ],
345 Curve::X25519 => vec![
346 DER_SEQUENCE,
347 0x2e,
348 DER_INTEGER,
349 0x01,
350 0x00, // Key type
351 DER_SEQUENCE,
352 0x05,
353 0x06,
354 0x03,
355 0x2b,
356 0x65,
357 0x6e, // Curve
358 DER_OCTETSTRING,
359 0x22,
360 DER_OCTETSTRING,
361 0x20,
362 ],
363 _ => return Err(EcError::UnsupportedCurve),
364 }
365 };
366
367 let mut key = key.clone();
368
369 if private_key_len(curve) == 0 {
370 return Err(EcError::EcKeyInvalidKeyData);
371 }
372
373 // if the key length is bigger than the expected -> wrong key
374 if key.len() > private_key_len(curve) {
375 return Err(EcError::EcKeyInvalidKeyData);
376 }
377
378 // if the key length is shorted than expected -> extend the key
379 if key.len() < private_key_len(curve) {
380 let mut zeros = vec![0 as u8; private_key_len(curve) - key.len()];
381 zeros.append(&mut key);
382 lh.append(&mut zeros);
383 } else {
384 lh.append(&mut key);
385 }
386
387 Ok(lh)
388 }
389
390 fn private_key_from_bytes_helper(bytes: Vec<u8>, curve: Curve) -> Vec<u8> {
391 if is_secret_key_contains_public_key(bytes.clone(), curve) {
392 let (test, _) = bytes.split_at(private_key_len(curve));
393 return test.to_vec();
394 }
395 return bytes;
396 }
397
398 pub fn private_key_from_bytes(bytes: Vec<u8>, curve: Curve) -> Result<EcPrivateKey, EcError> {
399 let private_key = private_key_from_bytes_helper(bytes, curve);
400 let private_key_pkcs8 = build_pkcs8_from_raw_private_key(private_key, curve).unwrap();
401 let private_key_imported =
402 nss_gk_api::ec::import_ec_private_key_pkcs8(&private_key_pkcs8).unwrap();
403 match curve {
404 Curve::P256 => Ok(EcPrivateKey::P256(private_key_imported)),
405 Curve::Ed25519 => Ok(EcPrivateKey::Ed25519(private_key_imported)),
406 Curve::X25519 => Ok(EcPrivateKey::X25519(private_key_imported)),
407 _ => Err(EcError::UnsupportedCurve),
408 }
409 }
410
411 pub fn private_key_to_bytes(key: EcPrivateKey) -> Result<Vec<u8>, EcError> {
412 match key {
413 EcPrivateKey::Ed25519(key) | EcPrivateKey::P256(key) | EcPrivateKey::X25519(key) => {
414 Ok(key.key_data().unwrap())
415 }
416 }
417 }
418
419 pub fn private_key_to_public(private_key: &EcPrivateKey) -> Result<EcPublicKey, EcError> {
420 match private_key {
421 EcPrivateKey::X25519(key) => Ok(EcPublicKey::X25519(
422 nss_gk_api::ec::convert_to_public(key.clone()).unwrap(),
423 )),
424 EcPrivateKey::Ed25519(key) => Ok(EcPublicKey::Ed25519(
425 nss_gk_api::ec::convert_to_public(key.clone()).unwrap(),
426 )),
427 EcPrivateKey::P256(key) => Ok(EcPublicKey::P256(
428 nss_gk_api::ec::convert_to_public(key.clone()).unwrap(),
429 )),
430 }
431 }
432
433 pub fn private_key_ecdh(
434 private_key: &EcPrivateKey,
435 remote_public: &EcPublicKey,
436 ) -> Result<Vec<u8>, EcError> {
437 let shared_secret = match private_key {
438 EcPrivateKey::X25519(private_key) => match remote_public {
439 EcPublicKey::X25519(public) => {
440 let r = nss_gk_api::ec::ecdh(private_key.clone(), public.clone()).unwrap();
441 Ok(r)
442 }
443 _ => Err(EcError::EcdhKeyTypeMismatch),
444 },
445 EcPrivateKey::Ed25519(_) => Err(EcError::EcKeyNotEcdh),
446 EcPrivateKey::P256(private_key) => match remote_public {
447 EcPublicKey::P256(public) => {
448 let r = nss_gk_api::ec::ecdh(private_key.clone(), public.clone()).unwrap();
449 Ok(r)
450 }
451 _ => Err(EcError::EcdhKeyTypeMismatch),
452 },
453 }?;
454
455 Ok(shared_secret)
456 }
457
458 pub fn sign_p256(private_key: PrivateKey, data: &[u8]) -> Result<Vec<u8>, EcError> {
459 let mut hashed_data = Hash::hash(&Hash::Sha256, data);
460 let signature = nss_gk_api::ec::sign_ecdsa(private_key, hashed_data.as_mut()).unwrap();
461 Ok(signature)
462 }
463
464 // Removes not needed zeros/ expands the signature until the required length if required
465 // This function could be easily extended to P384/etc if changed the input to also a curve
466 // And providing this curve to the each length functions
467
468 fn format_ecdsa_p256(buffer: &[u8]) -> Result<Vec<u8>, EcError> {
469 if buffer.len() > max_size_ecdsa_part(Curve::P256).unwrap() + 1 {
470 return Err(EcError::EcKeyInvalidKeyData);
471 }
472
473 // Correct size, no modification needed
474 if buffer.len() == max_size_ecdsa_part(Curve::P256).unwrap() {
475 return Ok(buffer.to_vec());
476 }
477
478 // It's possible that the buffer was padded (for one byte) with 0
479 // In this case the first byte should be equal to 0
480 if buffer.len() == max_size_ecdsa_part(Curve::P256).unwrap() + 1 {
481 if buffer[0] != 0x00 {
482 return Err(EcError::EcKeyInvalidKeyData);
483 }
484
485 if buffer[1] < 0b1000000 {
486 return Err(EcError::EcKeyInvalidKeyData);
487 }
488
489 // Removing the zero if found
490 let (_, rest) = buffer.split_at(1);
491 return Ok(rest.to_vec());
492 }
493
494 // If the signature is shorter, we extend it with 0 until get_max_size_ecdsa_part
495 let mut buffer = buffer.to_vec();
496 let mut zeros = vec![0 as u8; max_size_ecdsa_part(Curve::P256).unwrap() - buffer.len()];
497 zeros.append(&mut buffer);
498 Ok(zeros)
499 }
500
501 // ECDSA signature is packed the following way
502 // Signature ::= SEQUENCE {
503 // r INTEGER,
504 // s INTEGER,
505 // }
506
507 fn parse_ecdsa_p256(signature: &[u8]) -> Result<Vec<u8>, EcError> {
508 let signature_vec = signature.to_vec();
509 if signature[0] != DER_SEQUENCE {
510 // Not a correct encoding
511 return Err(EcError::EcKeyInvalidKeyData);
512 }
513
514 // the first byte is the length of the rest of the buffer
515 let len_buffer = signature[1];
516 if (len_buffer + 2) as usize != signature.len() {
517 // Wrong length
518 return Err(EcError::EcKeyInvalidKeyData);
519 }
520
521 if signature[2] != DER_INTEGER {
522 // Both R and S are integers
523 return Err(EcError::EcKeyInvalidKeyData);
524 }
525
526 let len_r = signature[3];
527 // R could be padded with 0x0 at the start if the most significant
528 // bit of the signature is 1.
529 if len_r as usize > max_size_ecdsa_part(Curve::P256).unwrap() + 1 {
530 return Err(EcError::EcKeyInvalidKeyData);
531 }
532
533 // Dividing the signature into introduction (Sequence; Len; Integer; Len)
534 // and the rest
535 // Intro is already checked for correctness
536 let (_, rs) = signature_vec.split_at(4);
537
538 // Reading len_r bytes of signature
539 // It will divide the buffer into R and the rest
540 let skip_until_r = 3;
541 let (r, intro_s) = rs.split_at(len_r as usize);
542
543 // The first byte after R is the type identifier of the next element
544 // For ecdsa, it should be integer
545 if signature[(skip_until_r + len_r + 1) as usize] != DER_INTEGER {
546 return Err(EcError::EcKeyInvalidKeyData);
547 }
548
549 // The next byte is the length
550 let len_s = signature_vec[(skip_until_r + len_r + 2) as usize];
551
552 if len_s as usize > max_size_ecdsa_part(Curve::P256).unwrap() + 1 {
553 return Err(EcError::EcKeyInvalidKeyData);
554 }
555
556 // Now the intro_s buffer consists of Type identifier and its length (2)
557 // Intro buffer is already checked
558 // The rest is the S part of the signature
559 let (_, s) = intro_s.split_at(2);
560
561 // Formatting R and S (removing padded zeros, extending the size if necessary)
562 let mut r = format_ecdsa_p256(r).unwrap();
563 let s = format_ecdsa_p256(s).unwrap();
564
565 // Concatenation of R and S
566 r.extend(s);
567
568 Ok(r)
569 }
570
571 pub fn verify_p256_(
572 public_key: PublicKey,
573 signature: Vec<u8>,
574 data: &[u8],
575 ) -> Result<bool, EcError> {
576 let mut hashed_data = Hash::hash(&Hash::Sha256, data);
577 let result =
578 nss_gk_api::ec::verify_ecdsa(public_key, hashed_data.as_mut(), &signature).unwrap();
579 Ok(result)
580 }
581
582 pub fn verify_p256(public_key: PublicKey, signature: &[u8], data: &[u8]) -> Result<bool, EcError> {
583 if signature.len() != max_size_ecdsa_part(Curve::P256).unwrap() * 2 {
584 let signature = parse_ecdsa_p256(signature).unwrap();
585 return verify_p256_(public_key, signature, data);
586 }
587
588 return verify_p256_(public_key, signature.to_vec(), data);
589 }
590
591 pub fn sign_ed25519(private_key: PrivateKey, data: &[u8]) -> Result<Vec<u8>, EcError> {
592 let signature = nss_gk_api::ec::sign_eddsa(private_key, &data).unwrap();
593 Ok(signature)
594 }
595
596 #[allow(dead_code)]
597 fn encode_ecdsa_p256(signature: Vec<u8>) -> Result<Vec<u8>, EcError> {
598 if signature.len() != max_size_ecdsa_part(Curve::P256).unwrap() * 2 {
599 return Err(EcError::EcKeyInvalidKeyData);
600 }
601
602 let (r, s) = signature.split_at(max_size_ecdsa_part(Curve::P256).unwrap());
603 let mut signature = vec![DER_SEQUENCE];
604
605 let r_len = max_size_ecdsa_part(Curve::P256).unwrap() + {
606 if r[0] < 0b10000000 {
607 0
608 } else {
609 1
610 }
611 };
612 let s_len = max_size_ecdsa_part(Curve::P256).unwrap() + {
613 if s[0] < 0b10000000 {
614 0
615 } else {
616 1
617 }
618 };
619
620 signature.push((4 + r_len + s_len) as u8);
621 signature.push(DER_INTEGER);
622 signature.push(r_len as u8);
623 if r[0] >= 0b10000000 {
624 signature.push(0);
625 }
626
627 signature.append(&mut r.to_vec());
628
629 signature.push(DER_INTEGER);
630 signature.push(s_len as u8);
631 if s[0] >= 0b10000000 {
632 signature.push(0);
633 }
634
635 signature.append(&mut s.to_vec());
636 Ok(signature)
637 }
638
639 pub fn verify_ed25519(
640 public_key: PublicKey,
641 signature: &[u8],
642 data: &[u8],
643 ) -> Result<bool, EcError> {
644 let result = nss_gk_api::ec::verify_eddsa(public_key, &data, signature).unwrap();
645 Ok(result)
646 }
647
648 pub fn generate_keypair(curve: Curve) -> Result<KeyPair, EcError> {
649 match curve {
650 Curve::P256 => {
651 let key = nss_gk_api::ec::ecdh_keygen(nss_gk_api::ec::EcCurve::P256).unwrap();
652 let secret: Vec<u8> = private_key_to_bytes(EcPrivateKey::P256(key.private))?;
653 let public: Vec<u8> = pub_key_to_uncompressed(EcPublicKey::P256(key.public))?;
654 return Ok(KeyPair { public, secret });
655 }
656 Curve::Ed25519 => {
657 let key = nss_gk_api::ec::ecdh_keygen(nss_gk_api::ec::EcCurve::Ed25519).unwrap();
658 let secret: Vec<u8> = private_key_to_bytes(EcPrivateKey::Ed25519(key.private))?;
659 let public: Vec<u8> = pub_key_to_uncompressed(EcPublicKey::Ed25519(key.public))?;
660 return Ok(KeyPair { public, secret });
661 }
662 Curve::X25519 => {
663 let key = nss_gk_api::ec::ecdh_keygen(nss_gk_api::ec::EcCurve::X25519).unwrap();
664 let secret: Vec<u8> = private_key_to_bytes(EcPrivateKey::X25519(key.private))?;
665 let public: Vec<u8> = pub_key_to_uncompressed(EcPublicKey::X25519(key.public))?;
666 return Ok(KeyPair { public, secret });
667 }
668 _ => {
669 let secret = generate_private_key(curve)?;
670 let public = private_key_to_public(&secret)?;
671 let secret = private_key_to_bytes(secret)?;
672 let public = pub_key_to_uncompressed(public)?;
673 Ok(KeyPair { public, secret })
674 }
675 }
676 }
677
678 #[derive(Clone, Default)]
679 pub struct KeyPair {
680 pub public: Vec<u8>,
681 pub secret: Vec<u8>,
682 }
683
684 impl Debug for KeyPair {
685 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
686 f.debug_struct("KeyPair")
687 .field("public", &mls_rs_core::debug::pretty_bytes(&self.public))
688 .field("secret", &mls_rs_core::debug::pretty_bytes(&self.secret))
689 .finish()
690 }
691 }
692
693 fn is_secret_key_contains_public_key(secret_key: Vec<u8>, curve: Curve) -> bool {
694 let private_key_len = private_key_len(curve);
695 let public_key_len = public_key_len(curve);
696 if secret_key.len() == private_key_len + public_key_len {
697 return true;
698 }
699 return false;
700 }
701
702 pub fn private_key_bytes_to_public(secret_key: Vec<u8>, curve: Curve) -> Result<Vec<u8>, EcError> {
703 if !is_secret_key_contains_public_key(secret_key.clone(), curve) {
704 let secret_key = private_key_from_bytes(secret_key.clone(), curve)?;
705 let public_key = private_key_to_public(&secret_key)?;
706 pub_key_to_uncompressed(public_key)
707 } else {
708 let (_, public_key) = secret_key.split_at(private_key_len(curve));
709 Ok(public_key.to_vec())
710 }
711 }
712
713 #[cfg(test)]
714 pub(crate) mod test_utils {
715 use serde::Deserialize;
716
717 use super::Curve;
718
719 use alloc::vec::Vec;
720
721 #[derive(Deserialize)]
722 pub(crate) struct TestKeys {
723 #[serde(with = "hex::serde")]
724 p256: Vec<u8>,
725 #[serde(with = "hex::serde")]
726 x25519: Vec<u8>,
727 #[serde(with = "hex::serde")]
728 ed25519: Vec<u8>,
729 }
730
731 impl TestKeys {
732 pub(crate) fn get_key_from_curve(&self, curve: Curve) -> Vec<u8> {
733 match curve {
734 Curve::P256 => self.p256.clone(),
735 Curve::X25519 => self.x25519.clone(),
736 Curve::Ed25519 => self.ed25519.clone(),
737 _ => Vec::new(),
738 }
739 }
740 }
741
742 pub(crate) fn get_test_public_keys() -> TestKeys {
743 let test_case_file = include_str!("../test_data/test_public_keys.json");
744 serde_json::from_str(test_case_file).unwrap()
745 }
746
747 pub(crate) fn get_test_secret_keys() -> TestKeys {
748 let test_case_file = include_str!("../test_data/test_private_keys.json");
749 serde_json::from_str(test_case_file).unwrap()
750 }
751
752 pub fn is_curve_25519(curve: Curve) -> bool {
753 curve == Curve::X25519 || curve == Curve::Ed25519
754 }
755
756 #[allow(dead_code)]
757 pub fn byte_equal(curve: Curve, other: Curve) -> bool {
758 if curve == other {
759 return true;
760 }
761
762 if is_curve_25519(curve) && is_curve_25519(other) {
763 return true;
764 }
765
766 false
767 }
768 }
769
770 #[cfg(test)]
771 mod tests {
772 use assert_matches::assert_matches;
773
774 use super::{
775 generate_keypair, generate_private_key, private_key_bytes_to_public,
776 private_key_from_bytes, private_key_from_pkcs8, private_key_to_bytes, private_key_to_pkcs8,
777 pub_key_from_uncompressed, pub_key_to_uncompressed, sign_ed25519, sign_p256,
778 test_utils::{get_test_public_keys, get_test_secret_keys},
779 verify_ed25519, verify_p256, Curve, EcPublicKey,
780 };
781
782 const SUPPORTED_CURVES: [Curve; 3] = [Curve::Ed25519, Curve::P256, Curve::X25519];
783
784 #[test]
785 fn private_key_can_be_generated() {
786 SUPPORTED_CURVES.iter().copied().for_each(|curve| {
787 let one_key = generate_private_key(curve)
788 .unwrap_or_else(|e| panic!("Failed to generate private key for {curve:?} : {e:?}"));
789
790 let another_key = generate_private_key(curve)
791 .unwrap_or_else(|e| panic!("Failed to generate private key for {curve:?} : {e:?}"));
792
793 assert_ne!(
794 private_key_to_bytes(one_key).unwrap(),
795 private_key_to_bytes(another_key).unwrap(),
796 "Same key generated twice for {curve:?}"
797 );
798 });
799 }
800
801 #[test]
802 fn key_pair_can_be_generated() {
803 SUPPORTED_CURVES.iter().copied().for_each(|curve| {
804 assert_matches!(
805 generate_keypair(curve),
806 Ok(_),
807 "Failed to generate key pair for {curve:?}"
808 );
809 });
810 }
811
812 #[test]
813 fn private_key_can_be_imported_and_exported() {
814 SUPPORTED_CURVES.iter().copied().for_each(|curve| {
815 let key_bytes = get_test_secret_keys().get_key_from_curve(curve);
816
817 let imported_key = private_key_from_bytes(key_bytes.clone(), curve)
818 .unwrap_or_else(|e| panic!("Failed to import private key for {curve:?} : {e:?}"));
819
820 let exported_bytes = private_key_to_bytes(imported_key)
821 .unwrap_or_else(|e| panic!("Failed to export private key for {curve:?} : {e:?}"));
822
823 assert_eq!(exported_bytes, key_bytes);
824 });
825 }
826
827 #[test]
828 fn private_key_pkcs8_can_be_imported_and_exported() {
829 SUPPORTED_CURVES.iter().copied().for_each(|curve| {
830 let key = generate_private_key(curve)
831 .unwrap_or_else(|e| panic!("Failed to generate private key for {curve:?} : {e:?}"));
832
833 let exported_bytes = private_key_to_pkcs8(key)
834 .unwrap_or_else(|e| panic!("Failed to export private key for {curve:?} : {e:?}"));
835
836 let imported_key = private_key_from_pkcs8(&exported_bytes, curve)
837 .unwrap_or_else(|e| panic!("Failed to import private key for {curve:?} : {e:?}"));
838
839 let exported_bytes_2 = private_key_to_pkcs8(imported_key)
840 .unwrap_or_else(|e| panic!("Failed to export private key for {curve:?} : {e:?}"));
841
842 assert_eq!(exported_bytes_2, exported_bytes);
843 });
844 }
845
846 #[test]
847 fn public_key_can_be_imported_and_exported() {
848 SUPPORTED_CURVES.iter().copied().for_each(|curve| {
849 let key_bytes = get_test_public_keys().get_key_from_curve(curve);
850
851 let imported_key = pub_key_from_uncompressed(key_bytes.clone(), curve)
852 .unwrap_or_else(|e| panic!("Failed to import public key for {curve:?} : {e:?}"));
853
854 let exported_bytes = pub_key_to_uncompressed(imported_key)
855 .unwrap_or_else(|e| panic!("Failed to export public key for {curve:?} : {e:?}"));
856
857 assert_eq!(exported_bytes, key_bytes);
858 });
859 }
860
861 #[test]
862 fn secret_to_public() {
863 let test_public_keys = get_test_public_keys();
864 let test_secret_keys = get_test_secret_keys();
865
866 for curve in SUPPORTED_CURVES.iter().copied() {
867 let secret_key = test_secret_keys.get_key_from_curve(curve);
868 let public_key = private_key_bytes_to_public(secret_key, curve).unwrap();
869 let expected_public_key = test_public_keys.get_key_from_curve(curve);
870 assert_eq!(public_key, expected_public_key);
871 }
872 }
873
874 // #[test]
875 // fn mismatched_curve_import() {
876 // for curve in SUPPORTED_CURVES.iter().copied() {
877 // for other_curve in SUPPORTED_CURVES
878 // .iter()
879 // .copied()
880 // .filter(|c| !byte_equal(*c, curve))
881 // {
882 // let public_key = get_test_public_keys().get_key_from_curve(curve);
883 // let res = pub_key_from_uncompressed(public_key, other_curve);
884
885 // assert!(res.is_err());
886 // }
887 // }
888 // }
889
890 // TODO: discuss if we need this test
891 // TODO: if yes, we need to introduce secure cmp
892
893 // #[test]
894 // fn test_order_range_enforcement() {
895 // let p256_order =
896 // hex::decode("ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551")
897 // .unwrap();
898
899 // // Keys must be <= to order
900 // let p256_res = private_key_from_bytes(p256_order, Curve::P256);
901 // assert_matches!(p256_res, Err(EcError::EcKeyInvalidKeyData));
902
903 // let nist_curves = [Curve::P256];
904
905 // // Keys must not be 0
906 // for curve in nist_curves {
907 // assert_matches!(
908 // private_key_from_bytes(vec![0u8; curve.secret_key_size()], curve),
909 // Err(EcError::EcKeyInvalidKeyData)
910 // );
911 // }
912 // }
913
914 use serde::Deserialize;
915
916 #[derive(Deserialize)]
917 struct TestCaseSignature {
918 pub algorithm: String,
919 #[serde(with = "hex::serde")]
920 pub private_key: Vec<u8>,
921 #[serde(with = "hex::serde")]
922 pub public_key: Vec<u8>,
923 #[serde(with = "hex::serde")]
924 pub hash: Vec<u8>,
925 #[serde(with = "hex::serde")]
926 pub signature: Vec<u8>,
927 }
928
929 fn test_sign_p256(private_key: Vec<u8>, public_key: Vec<u8>, data: Vec<u8>) {
930 let curve = Curve::P256;
931 let private_key = private_key_from_bytes(private_key, curve).unwrap();
932 let public_key = pub_key_from_uncompressed(public_key, curve).unwrap();
933 match private_key {
934 super::EcPrivateKey::P256(private_key) => {
935 let signature = sign_p256(private_key, &data).unwrap();
936 match public_key {
937 EcPublicKey::P256(public_key) => {
938 let verify = verify_p256(public_key, &signature, &data).unwrap();
939 assert_eq!(verify, true)
940 }
941 _ => assert!(false),
942 }
943 }
944 _ => assert!(false),
945 }
946 }
947
948 fn test_sign_ed25519(
949 private_key: Vec<u8>,
950 public_key: Vec<u8>,
951 data: Vec<u8>,
952 expected_signature: Vec<u8>,
953 ) {
954 let curve = Curve::Ed25519;
955 let private_key = private_key_from_bytes(private_key, curve).unwrap();
956 let public_key = pub_key_from_uncompressed(public_key, curve).unwrap();
957 match private_key {
958 super::EcPrivateKey::Ed25519(private_key) => {
959 let signature = sign_ed25519(private_key, &data).unwrap();
960 assert_eq!(signature, expected_signature);
961 match public_key {
962 EcPublicKey::Ed25519(public_key) => {
963 let verify = verify_ed25519(public_key, &signature, &data).unwrap();
964 assert_eq!(verify, true)
965 }
966 _ => assert!(false),
967 }
968 }
969 _ => assert!(false),
970 }
971 }
972
973 #[test]
974 fn test_ecdsa_eddsa() {
975 let test_case_file = include_str!("../test_data/test_ecdsa_eddsa.json");
976 let test_cases: Vec<TestCaseSignature> = serde_json::from_str(test_case_file).unwrap();
977
978 for case in test_cases {
979 match case.algorithm.as_str() {
980 "ECDSA" => test_sign_p256(case.private_key, case.public_key, case.hash),
981 "EDDSA" => {
982 test_sign_ed25519(case.private_key, case.public_key, case.hash, case.signature)
983 }
984 _ => assert!(false),
985 }
986 }
987 }
988 }