1use core::fmt;
2use core::ops::{Deref, DerefMut};
3
4use super::common::*;
5#[cfg(feature = "blind-keys")]
6use super::edwards25519::{ge_scalarmult, sc_invert, sc_mul};
7use super::edwards25519::{
8 ge_scalarmult_base, is_identity, sc_muladd, sc_reduce, sc_reduce32, sc_reject_noncanonical,
9 GeP2, GeP3,
10};
11use super::error::Error;
12use super::sha512;
13
14#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
16pub struct PublicKey([u8; PublicKey::BYTES]);
17
18impl PublicKey {
19 pub const BYTES: usize = 32;
21
22 pub fn new(pk: [u8; PublicKey::BYTES]) -> Self {
24 PublicKey(pk)
25 }
26
27 pub fn from_slice(pk: &[u8]) -> Result<Self, Error> {
29 let mut pk_ = [0u8; PublicKey::BYTES];
30 if pk.len() != pk_.len() {
31 return Err(Error::InvalidPublicKey);
32 }
33 pk_.copy_from_slice(pk);
34 Ok(PublicKey::new(pk_))
35 }
36}
37
38impl Deref for PublicKey {
39 type Target = [u8; PublicKey::BYTES];
40
41 fn deref(&self) -> &Self::Target {
43 &self.0
44 }
45}
46
47impl DerefMut for PublicKey {
48 fn deref_mut(&mut self) -> &mut Self::Target {
50 &mut self.0
51 }
52}
53
54#[derive(Clone, Debug, Eq, PartialEq, Hash)]
56pub struct SecretKey([u8; SecretKey::BYTES]);
57
58impl SecretKey {
59 pub const BYTES: usize = 32 + PublicKey::BYTES;
61
62 pub fn new(sk: [u8; SecretKey::BYTES]) -> Self {
64 SecretKey(sk)
65 }
66
67 pub fn from_slice(sk: &[u8]) -> Result<Self, Error> {
69 let mut sk_ = [0u8; SecretKey::BYTES];
70 if sk.len() != sk_.len() {
71 return Err(Error::InvalidSecretKey);
72 }
73 sk_.copy_from_slice(sk);
74 Ok(SecretKey::new(sk_))
75 }
76
77 pub fn public_key(&self) -> PublicKey {
79 let mut pk = [0u8; PublicKey::BYTES];
80 pk.copy_from_slice(&self[Seed::BYTES..]);
81 PublicKey(pk)
82 }
83
84 pub fn seed(&self) -> Seed {
86 Seed::from_slice(&self[0..Seed::BYTES]).unwrap()
87 }
88
89 pub fn validate_public_key(&self, pk: &PublicKey) -> Result<(), Error> {
95 let kp = KeyPair::from_seed(self.seed());
96 if kp.pk != *pk {
97 return Err(Error::InvalidPublicKey);
98 }
99 Ok(())
100 }
101}
102
103impl Drop for SecretKey {
104 fn drop(&mut self) {
105 Mem::wipe(self.0)
106 }
107}
108
109impl Deref for SecretKey {
110 type Target = [u8; SecretKey::BYTES];
111
112 fn deref(&self) -> &Self::Target {
114 &self.0
115 }
116}
117
118impl DerefMut for SecretKey {
119 fn deref_mut(&mut self) -> &mut Self::Target {
121 &mut self.0
122 }
123}
124
125#[derive(Clone, Debug, Eq, PartialEq, Hash)]
127pub struct KeyPair {
128 pub pk: PublicKey,
130 pub sk: SecretKey,
132}
133
134#[derive(Copy, Clone, Eq, PartialEq, Hash)]
136pub struct Signature([u8; Signature::BYTES]);
137
138impl fmt::Debug for Signature {
139 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
140 f.write_fmt(format_args!("{:x?}", &self.0))
141 }
142}
143
144impl AsRef<[u8]> for Signature {
145 fn as_ref(&self) -> &[u8] {
146 &self.0
147 }
148}
149
150impl Signature {
151 pub const BYTES: usize = 64;
153
154 pub fn new(bytes: [u8; Signature::BYTES]) -> Self {
156 Signature(bytes)
157 }
158
159 pub fn from_slice(signature: &[u8]) -> Result<Self, Error> {
161 let mut signature_ = [0u8; Signature::BYTES];
162 if signature.len() != signature_.len() {
163 return Err(Error::InvalidSignature);
164 }
165 signature_.copy_from_slice(signature);
166 Ok(Signature::new(signature_))
167 }
168}
169
170impl Deref for Signature {
171 type Target = [u8; Signature::BYTES];
172
173 fn deref(&self) -> &Self::Target {
175 &self.0
176 }
177}
178
179impl DerefMut for Signature {
180 fn deref_mut(&mut self) -> &mut Self::Target {
182 &mut self.0
183 }
184}
185
186#[derive(Clone)]
188pub struct VerifyingState {
189 hasher: sha512::Hash,
190 signature: Signature,
191 a: GeP3,
192}
193
194impl Drop for VerifyingState {
195 fn drop(&mut self) {
196 Mem::wipe(self.signature.0);
197 }
198}
199
200impl VerifyingState {
201 fn new(pk: &PublicKey, signature: &Signature) -> Result<Self, Error> {
202 let r = &signature[0..32];
203 let s = &signature[32..64];
204 sc_reject_noncanonical(s)?;
205 if is_identity(pk) || pk.iter().fold(0, |acc, x| acc | x) == 0 {
206 return Err(Error::WeakPublicKey);
207 }
208 let a = match GeP3::from_bytes_negate_vartime(pk) {
209 Some(g) => g,
210 None => {
211 return Err(Error::InvalidPublicKey);
212 }
213 };
214 let mut hasher = sha512::Hash::new();
215 hasher.update(r);
216 hasher.update(&pk[..]);
217 Ok(VerifyingState {
218 hasher,
219 signature: *signature,
220 a,
221 })
222 }
223
224 pub fn absorb(&mut self, chunk: impl AsRef<[u8]>) {
226 self.hasher.update(chunk)
227 }
228
229 pub fn verify(&self) -> Result<(), Error> {
231 let mut expected_r_bytes = [0u8; 32];
232 expected_r_bytes.copy_from_slice(&self.signature[0..32]);
233 let expected_r =
234 GeP3::from_bytes_vartime(&expected_r_bytes).ok_or(Error::InvalidSignature)?;
235 let s = &self.signature[32..64];
236
237 let mut hash = self.hasher.finalize();
238 sc_reduce(&mut hash);
239
240 let r = GeP2::double_scalarmult_vartime(hash.as_ref(), self.a, s);
241 if (expected_r - GeP3::from(r)).has_small_order() {
242 Ok(())
243 } else {
244 Err(Error::SignatureMismatch)
245 }
246 }
247}
248
249impl PublicKey {
250 pub fn verify_incremental(&self, signature: &Signature) -> Result<VerifyingState, Error> {
252 VerifyingState::new(self, signature)
253 }
254
255 pub fn verify(&self, message: impl AsRef<[u8]>, signature: &Signature) -> Result<(), Error> {
258 let mut st = VerifyingState::new(self, signature)?;
259 st.absorb(message);
260 st.verify()
261 }
262}
263
264#[derive(Clone)]
266pub struct SigningState {
267 hasher: sha512::Hash,
268 az: [u8; 64],
269 nonce: [u8; 64],
270}
271
272impl Drop for SigningState {
273 fn drop(&mut self) {
274 Mem::wipe(self.az);
275 Mem::wipe(self.nonce);
276 }
277}
278
279impl SigningState {
280 fn new(nonce: [u8; 64], az: [u8; 64], pk_: &[u8]) -> Self {
281 let mut prefix: [u8; 64] = [0; 64];
282 let r = ge_scalarmult_base(&nonce[0..32]);
283 prefix[0..32].copy_from_slice(&r.to_bytes()[..]);
284 prefix[32..64].copy_from_slice(pk_);
285
286 let mut st = sha512::Hash::new();
287 st.update(prefix);
288
289 SigningState {
290 hasher: st,
291 nonce,
292 az,
293 }
294 }
295
296 pub fn absorb(&mut self, chunk: impl AsRef<[u8]>) {
298 self.hasher.update(chunk)
299 }
300
301 pub fn sign(&self) -> Signature {
303 let mut signature: [u8; 64] = [0; 64];
304 let r = ge_scalarmult_base(&self.nonce[0..32]);
305 signature[0..32].copy_from_slice(&r.to_bytes()[..]);
306 let mut hram = self.hasher.finalize();
307 sc_reduce(&mut hram);
308 sc_muladd(
309 &mut signature[32..64],
310 &hram[0..32],
311 &self.az[0..32],
312 &self.nonce[0..32],
313 );
314 Signature(signature)
315 }
316}
317
318impl SecretKey {
319 pub fn sign_incremental(&self, noise: Noise) -> SigningState {
322 let seed = &self[0..32];
323 let pk = &self[32..64];
324 let az: [u8; 64] = {
325 let mut hash_output = sha512::Hash::hash(seed);
326 hash_output[0] &= 248;
327 hash_output[31] &= 63;
328 hash_output[31] |= 64;
329 hash_output
330 };
331 let mut st = sha512::Hash::new();
332 #[cfg(feature = "random")]
333 {
334 let additional_noise = Noise::generate();
335 st.update(additional_noise.as_ref());
336 }
337 st.update(noise.as_ref());
338 st.update(seed);
339 let nonce = st.finalize();
340 SigningState::new(nonce, az, pk)
341 }
342
343 pub fn sign(&self, message: impl AsRef<[u8]>, noise: Option<Noise>) -> Signature {
347 let seed = &self[0..32];
348 let pk = &self[32..64];
349 let az: [u8; 64] = {
350 let mut hash_output = sha512::Hash::hash(seed);
351 hash_output[0] &= 248;
352 hash_output[31] &= 63;
353 hash_output[31] |= 64;
354 hash_output
355 };
356 let nonce = {
357 let mut hasher = sha512::Hash::new();
358 if let Some(noise) = noise {
359 hasher.update(&noise[..]);
360 hasher.update(&az[..]);
361 } else {
362 hasher.update(&az[32..64]);
363 }
364 hasher.update(&message);
365 let mut hash_output = hasher.finalize();
366 sc_reduce(&mut hash_output[0..64]);
367 hash_output
368 };
369 let mut st = SigningState::new(nonce, az, pk);
370 st.absorb(&message);
371 let signature = st.sign();
372
373 #[cfg(feature = "self-verify")]
374 {
375 PublicKey::from_slice(pk)
376 .expect("Key length changed")
377 .verify(message, &signature)
378 .expect("Newly created signature cannot be verified");
379 }
380
381 signature
382 }
383}
384
385impl KeyPair {
386 pub const BYTES: usize = SecretKey::BYTES;
388
389 #[cfg(feature = "random")]
391 pub fn generate() -> KeyPair {
392 KeyPair::from_seed(Seed::default())
393 }
394
395 pub fn from_seed(seed: Seed) -> KeyPair {
397 if seed.iter().fold(0, |acc, x| acc | x) == 0 {
398 panic!("All-zero seed");
399 }
400 let scalar = seed.scalar();
401 let pk = ge_scalarmult_base(&scalar).to_bytes();
402 let mut sk = [0u8; 64];
403 sk[0..32].copy_from_slice(&*seed);
404 sk[32..64].copy_from_slice(&pk);
405 KeyPair {
406 pk: PublicKey(pk),
407 sk: SecretKey(sk),
408 }
409 }
410
411 pub fn from_slice(bytes: &[u8]) -> Result<Self, Error> {
413 let sk = SecretKey::from_slice(bytes)?;
414 let pk = sk.public_key();
415 Ok(KeyPair { pk, sk })
416 }
417
418 pub fn clamp(scalar: &mut [u8]) {
420 scalar[0] &= 248;
421 scalar[31] &= 63;
422 scalar[31] |= 64;
423 }
424
425 pub fn split(bytes: &[u8; 64], reduce: bool, clamp: bool) -> ([u8; 32], [u8; 32]) {
428 let mut scalar = [0u8; 32];
429 scalar.copy_from_slice(&bytes[0..32]);
430 if clamp {
431 Self::clamp(&mut scalar);
432 }
433 if reduce {
434 sc_reduce32(&mut scalar);
435 }
436 let mut prefix = [0u8; 32];
437 prefix.copy_from_slice(&bytes[32..64]);
438 (scalar, prefix)
439 }
440
441 pub fn validate(&self) -> Result<(), Error> {
443 self.sk.validate_public_key(&self.pk)
444 }
445}
446
447impl Deref for KeyPair {
448 type Target = [u8; KeyPair::BYTES];
449
450 fn deref(&self) -> &Self::Target {
452 &self.sk
453 }
454}
455
456impl DerefMut for KeyPair {
457 fn deref_mut(&mut self) -> &mut Self::Target {
459 &mut self.sk
460 }
461}
462
463#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
465pub struct Noise([u8; Noise::BYTES]);
466
467impl Noise {
468 pub const BYTES: usize = 16;
470
471 pub fn new(noise: [u8; Noise::BYTES]) -> Self {
473 Noise(noise)
474 }
475
476 pub fn from_slice(noise: &[u8]) -> Result<Self, Error> {
478 let mut noise_ = [0u8; Noise::BYTES];
479 if noise.len() != noise_.len() {
480 return Err(Error::InvalidSeed);
481 }
482 noise_.copy_from_slice(noise);
483 Ok(Noise::new(noise_))
484 }
485}
486
487impl Deref for Noise {
488 type Target = [u8; Noise::BYTES];
489
490 fn deref(&self) -> &Self::Target {
492 &self.0
493 }
494}
495
496impl DerefMut for Noise {
497 fn deref_mut(&mut self) -> &mut Self::Target {
499 &mut self.0
500 }
501}
502
503#[cfg(feature = "random")]
504impl Default for Noise {
505 fn default() -> Self {
507 let mut noise = [0u8; Noise::BYTES];
508 getrandom::getrandom(&mut noise).expect("RNG failure");
509 Noise(noise)
510 }
511}
512
513#[cfg(feature = "random")]
514impl Noise {
515 pub fn generate() -> Self {
517 Noise::default()
518 }
519}
520
521#[cfg(feature = "traits")]
522mod ed25519_trait {
523 use ::ed25519::signature as ed25519_trait;
524
525 use super::{PublicKey, SecretKey, Signature};
526
527 impl ed25519_trait::Signature for Signature {
528 fn from_bytes(bytes: &[u8]) -> Result<Self, ed25519_trait::Error> {
529 let mut bytes_ = [0u8; Signature::BYTES];
530 bytes_.copy_from_slice(bytes);
531 Ok(Signature::new(bytes_))
532 }
533 }
534
535 impl ed25519_trait::Signer<Signature> for SecretKey {
536 fn try_sign(&self, message: &[u8]) -> Result<Signature, ed25519_trait::Error> {
537 Ok(self.sign(message, None))
538 }
539 }
540
541 impl ed25519_trait::Verifier<Signature> for PublicKey {
542 fn verify(
543 &self,
544 message: &[u8],
545 signature: &Signature,
546 ) -> Result<(), ed25519_trait::Error> {
547 #[cfg(feature = "std")]
548 {
549 self.verify(message, signature)
550 .map_err(|e| ed25519_trait::Error::from_source(e))
551 }
552
553 #[cfg(not(feature = "std"))]
554 {
555 self.verify(message, signature)
556 .map_err(|_| ed25519_trait::Error::new())
557 }
558 }
559 }
560}
561
562#[test]
563fn test_ed25519() {
564 let kp = KeyPair::from_seed([42u8; 32].into());
565 let message = b"Hello, World!";
566 let signature = kp.sk.sign(message, None);
567 assert!(kp.pk.verify(message, &signature).is_ok());
568 assert!(kp.pk.verify(b"Hello, world!", &signature).is_err());
569 assert_eq!(
570 signature.as_ref(),
571 [
572 196, 182, 1, 15, 182, 182, 231, 166, 227, 62, 243, 85, 49, 174, 169, 9, 162, 196, 98,
573 104, 30, 81, 22, 38, 184, 136, 253, 128, 10, 160, 128, 105, 127, 130, 138, 164, 57, 86,
574 94, 160, 216, 85, 153, 139, 81, 100, 38, 124, 235, 210, 26, 95, 231, 90, 73, 206, 33,
575 216, 171, 15, 188, 181, 136, 7,
576 ]
577 );
578}
579
580#[cfg(feature = "blind-keys")]
581mod blind_keys {
582 use super::*;
583
584 #[derive(Clone, Debug, Eq, PartialEq, Hash)]
585 pub struct Blind([u8; Blind::BYTES]);
586
587 impl From<[u8; 32]> for Blind {
588 fn from(blind: [u8; 32]) -> Self {
589 Blind(blind)
590 }
591 }
592
593 impl Blind {
594 pub const BYTES: usize = 32;
596
597 pub fn new(blind: [u8; Blind::BYTES]) -> Self {
599 Blind(blind)
600 }
601
602 pub fn from_slice(blind: &[u8]) -> Result<Self, Error> {
604 let mut blind_ = [0u8; Blind::BYTES];
605 if blind.len() != blind_.len() {
606 return Err(Error::InvalidBlind);
607 }
608 blind_.copy_from_slice(blind);
609 Ok(Blind::new(blind_))
610 }
611 }
612
613 impl Drop for Blind {
614 fn drop(&mut self) {
615 Mem::wipe(self.0)
616 }
617 }
618
619 #[cfg(feature = "random")]
620 impl Default for Blind {
621 fn default() -> Self {
623 let mut blind = [0u8; Blind::BYTES];
624 getrandom::getrandom(&mut blind).expect("RNG failure");
625 Blind(blind)
626 }
627 }
628
629 #[cfg(feature = "random")]
630 impl Blind {
631 pub fn generate() -> Self {
633 Blind::default()
634 }
635 }
636
637 impl Deref for Blind {
638 type Target = [u8; Blind::BYTES];
639
640 fn deref(&self) -> &Self::Target {
642 &self.0
643 }
644 }
645
646 impl DerefMut for Blind {
647 fn deref_mut(&mut self) -> &mut Self::Target {
649 &mut self.0
650 }
651 }
652
653 #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
655 pub struct BlindPublicKey([u8; PublicKey::BYTES]);
656
657 impl Deref for BlindPublicKey {
658 type Target = [u8; BlindPublicKey::BYTES];
659
660 fn deref(&self) -> &Self::Target {
662 &self.0
663 }
664 }
665
666 impl DerefMut for BlindPublicKey {
667 fn deref_mut(&mut self) -> &mut Self::Target {
669 &mut self.0
670 }
671 }
672
673 impl BlindPublicKey {
674 pub const BYTES: usize = PublicKey::BYTES;
676
677 pub fn new(bpk: [u8; PublicKey::BYTES]) -> Self {
679 BlindPublicKey(bpk)
680 }
681
682 pub fn from_slice(bpk: &[u8]) -> Result<Self, Error> {
684 let mut bpk_ = [0u8; PublicKey::BYTES];
685 if bpk.len() != bpk_.len() {
686 return Err(Error::InvalidPublicKey);
687 }
688 bpk_.copy_from_slice(bpk);
689 Ok(BlindPublicKey::new(bpk_))
690 }
691
692 pub fn unblind(&self, blind: &Blind, ctx: impl AsRef<[u8]>) -> Result<PublicKey, Error> {
694 let pk_p3 = GeP3::from_bytes_vartime(&self.0).ok_or(Error::InvalidPublicKey)?;
695 let mut hx = sha512::Hash::new();
696 hx.update(&blind[..]);
697 hx.update([0u8]);
698 hx.update(ctx.as_ref());
699 let hash_output = hx.finalize();
700 let (blind_factor, _) = KeyPair::split(&hash_output, true, false);
701 let inverse = sc_invert(&blind_factor);
702 Ok(PublicKey(ge_scalarmult(&inverse, &pk_p3).to_bytes()))
703 }
704
705 pub fn verify(
708 &self,
709 message: impl AsRef<[u8]>,
710 signature: &Signature,
711 ) -> Result<(), Error> {
712 PublicKey::new(self.0).verify(message, signature)
713 }
714 }
715
716 impl From<PublicKey> for BlindPublicKey {
717 fn from(pk: PublicKey) -> Self {
718 BlindPublicKey(pk.0)
719 }
720 }
721
722 impl From<BlindPublicKey> for PublicKey {
723 fn from(bpk: BlindPublicKey) -> Self {
724 PublicKey(bpk.0)
725 }
726 }
727
728 #[derive(Clone, Debug, Eq, PartialEq, Hash)]
730 pub struct BlindSecretKey {
731 pub prefix: [u8; 2 * Seed::BYTES],
732 pub blind_scalar: [u8; 32],
733 pub blind_pk: BlindPublicKey,
734 }
735
736 #[derive(Clone, Debug, Eq, PartialEq, Hash)]
737 pub struct BlindKeyPair {
738 pub blind_pk: BlindPublicKey,
740 pub blind_sk: BlindSecretKey,
742 }
743
744 impl BlindSecretKey {
745 pub fn sign(&self, message: impl AsRef<[u8]>, noise: Option<Noise>) -> Signature {
749 let nonce = {
750 let mut hasher = sha512::Hash::new();
751 if let Some(noise) = noise {
752 hasher.update(&noise[..]);
753 hasher.update(self.prefix);
754 } else {
755 hasher.update(self.prefix);
756 }
757 hasher.update(&message);
758 let mut hash_output = hasher.finalize();
759 sc_reduce(&mut hash_output[0..64]);
760 hash_output
761 };
762 let mut signature: [u8; 64] = [0; 64];
763 let r = ge_scalarmult_base(&nonce[0..32]);
764 signature[0..32].copy_from_slice(&r.to_bytes()[..]);
765 signature[32..64].copy_from_slice(&self.blind_pk.0);
766 let mut hasher = sha512::Hash::new();
767 hasher.update(signature.as_ref());
768 hasher.update(&message);
769 let mut hram = hasher.finalize();
770 sc_reduce(&mut hram);
771 sc_muladd(
772 &mut signature[32..64],
773 &hram[0..32],
774 &self.blind_scalar,
775 &nonce[0..32],
776 );
777 let signature = Signature(signature);
778
779 #[cfg(feature = "self-verify")]
780 {
781 PublicKey::from_slice(&self.blind_pk.0)
782 .expect("Key length changed")
783 .verify(message, &signature)
784 .expect("Newly created signature cannot be verified");
785 }
786 signature
787 }
788 }
789
790 impl Drop for BlindSecretKey {
791 fn drop(&mut self) {
792 Mem::wipe(self.prefix);
793 Mem::wipe(self.blind_scalar);
794 }
795 }
796
797 impl PublicKey {
798 pub fn blind(&self, blind: &Blind, ctx: impl AsRef<[u8]>) -> Result<BlindPublicKey, Error> {
800 let (blind_factor, _prefix2) = {
801 let mut hx = sha512::Hash::new();
802 hx.update(&blind[..]);
803 hx.update([0u8]);
804 hx.update(ctx.as_ref());
805 let hash_output = hx.finalize();
806 KeyPair::split(&hash_output, true, false)
807 };
808 let pk_p3 = GeP3::from_bytes_vartime(&self.0).ok_or(Error::InvalidPublicKey)?;
809 Ok(BlindPublicKey(
810 ge_scalarmult(&blind_factor, &pk_p3).to_bytes(),
811 ))
812 }
813 }
814
815 impl KeyPair {
816 pub fn blind(&self, blind: &Blind, ctx: impl AsRef<[u8]>) -> BlindKeyPair {
818 let seed = self.sk.seed();
819 let (scalar, prefix1) = {
820 let hash_output = sha512::Hash::hash(&seed[..]);
821 KeyPair::split(&hash_output, false, true)
822 };
823
824 let (blind_factor, prefix2) = {
825 let mut hx = sha512::Hash::new();
826 hx.update(&blind[..]);
827 hx.update([0u8]);
828 hx.update(ctx.as_ref());
829 let hash_output = hx.finalize();
830 KeyPair::split(&hash_output, true, false)
831 };
832
833 let blind_scalar = sc_mul(&scalar, &blind_factor);
834 let blind_pk = ge_scalarmult_base(&blind_scalar).to_bytes();
835
836 let mut prefix = [0u8; 2 * Seed::BYTES];
837 prefix[0..32].copy_from_slice(&prefix1);
838 prefix[32..64].copy_from_slice(&prefix2);
839 let blind_pk = BlindPublicKey::new(blind_pk);
840
841 BlindKeyPair {
842 blind_pk,
843 blind_sk: BlindSecretKey {
844 prefix,
845 blind_scalar,
846 blind_pk,
847 },
848 }
849 }
850 }
851}
852
853#[cfg(feature = "blind-keys")]
854pub use blind_keys::*;
855
856#[test]
857#[cfg(feature = "blind-keys")]
858fn test_blind_ed25519() {
859 use ct_codecs::{Decoder, Hex};
860
861 let kp = KeyPair::generate();
862 let blind = Blind::new([69u8; 32]);
863 let blind_kp = kp.blind(&blind, "ctx");
864 let message = b"Hello, World!";
865 let signature = blind_kp.blind_sk.sign(message, None);
866 assert!(blind_kp.blind_pk.verify(message, &signature).is_ok());
867 let recovered_pk = blind_kp.blind_pk.unblind(&blind, "ctx").unwrap();
868 assert!(recovered_pk == kp.pk);
869
870 let kp = KeyPair::from_seed(
871 Seed::from_slice(
872 &Hex::decode_to_vec(
873 "875532ab039b0a154161c284e19c74afa28d5bf5454e99284bbcffaa71eebf45",
874 None,
875 )
876 .unwrap(),
877 )
878 .unwrap(),
879 );
880 assert_eq!(
881 Hex::decode_to_vec(
882 "3b5983605b277cd44918410eb246bb52d83adfc806ccaa91a60b5b2011bc5973",
883 None
884 )
885 .unwrap(),
886 kp.pk.as_ref()
887 );
888
889 let blind = Blind::from_slice(
890 &Hex::decode_to_vec(
891 "c461e8595f0ac41d374f878613206704978115a226f60470ffd566e9e6ae73bf",
892 None,
893 )
894 .unwrap(),
895 )
896 .unwrap();
897 let blind_kp = kp.blind(&blind, "ctx");
898 assert_eq!(
899 Hex::decode_to_vec(
900 "246dcd43930b81d5e4d770db934a9fcd985b75fd014bc2a98b0aea02311c1836",
901 None
902 )
903 .unwrap(),
904 blind_kp.blind_pk.as_ref()
905 );
906
907 let message = Hex::decode_to_vec("68656c6c6f20776f726c64", None).unwrap();
908 let signature = blind_kp.blind_sk.sign(message, None);
909 assert_eq!(Hex::decode_to_vec("947bacfabc63448f8955dc20630e069e58f37b72bb433ae17f2fa904ea860b44deb761705a3cc2168a6673ee0b41ff7765c7a4896941eec6833c1689315acb0b",
910 None).unwrap(), signature.as_ref());
911}
912
913#[test]
914fn test_streaming() {
915 let kp = KeyPair::generate();
916
917 let msg1 = "mes";
918 let msg2 = "sage";
919 let mut st = kp.sk.sign_incremental(Noise::default());
920 st.absorb(msg1);
921 st.absorb(msg2);
922 let signature = st.sign();
923
924 let msg1 = "mess";
925 let msg2 = "age";
926 let mut st = kp.pk.verify_incremental(&signature).unwrap();
927 st.absorb(msg1);
928 st.absorb(msg2);
929 assert!(st.verify().is_ok());
930}
931
932#[test]
933#[cfg(feature = "random")]
934fn test_ed25519_invalid_keypair() {
935 let kp1 = KeyPair::generate();
936 let kp2 = KeyPair::generate();
937
938 assert_eq!(
939 kp1.sk.validate_public_key(&kp2.pk).unwrap_err(),
940 Error::InvalidPublicKey
941 );
942 assert_eq!(
943 kp2.sk.validate_public_key(&kp1.pk).unwrap_err(),
944 Error::InvalidPublicKey
945 );
946 assert!(kp1.sk.validate_public_key(&kp1.pk).is_ok());
947 assert!(kp2.sk.validate_public_key(&kp2.pk).is_ok());
948 assert!(kp1.validate().is_ok());
949}