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