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(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(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}
280
281impl Drop for SigningState {
282 fn drop(&mut self) {
283 Mem::wipe(self.az);
284 Mem::wipe(self.nonce);
285 }
286}
287
288impl SigningState {
289 fn new(nonce: [u8; 64], az: [u8; 64], pk_: &[u8]) -> Self {
290 let mut prefix: [u8; 64] = [0; 64];
291 let r = ge_scalarmult_base(&nonce[0..32]);
292 prefix[0..32].copy_from_slice(&r.to_bytes()[..]);
293 prefix[32..64].copy_from_slice(pk_);
294
295 let mut st = sha512::Hash::new();
296 st.update(prefix);
297
298 SigningState {
299 hasher: st,
300 nonce,
301 az,
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 let r = ge_scalarmult_base(&self.nonce[0..32]);
314 signature[0..32].copy_from_slice(&r.to_bytes()[..]);
315 let mut hram = self.hasher.finalize();
316 sc_reduce(&mut hram);
317 sc_muladd(
318 &mut signature[32..64],
319 &hram[0..32],
320 &self.az[0..32],
321 &self.nonce[0..32],
322 );
323 Signature(signature)
324 }
325}
326
327impl SecretKey {
328 pub fn sign_incremental(&self, noise: Noise) -> SigningState {
331 let seed = &self[0..32];
332 let pk = &self[32..64];
333 let az: [u8; 64] = {
334 let mut hash_output = sha512::Hash::hash(seed);
335 hash_output[0] &= 248;
336 hash_output[31] &= 63;
337 hash_output[31] |= 64;
338 hash_output
339 };
340 let mut st = sha512::Hash::new();
341 #[cfg(feature = "random")]
342 {
343 let additional_noise = Noise::generate();
344 st.update(additional_noise.as_ref());
345 }
346 st.update(noise.as_ref());
347 st.update(seed);
348 let nonce = st.finalize();
349 SigningState::new(nonce, az, pk)
350 }
351
352 pub fn sign(&self, message: impl AsRef<[u8]>, noise: Option<Noise>) -> Signature {
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::InvalidSeed);
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::getrandom(&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(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::getrandom(&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 nonce = {
758 let mut hasher = sha512::Hash::new();
759 if let Some(noise) = noise {
760 hasher.update(&noise[..]);
761 hasher.update(self.prefix);
762 } else {
763 hasher.update(self.prefix);
764 }
765 hasher.update(&message);
766 let mut hash_output = hasher.finalize();
767 sc_reduce(&mut hash_output[0..64]);
768 hash_output
769 };
770 let mut signature: [u8; 64] = [0; 64];
771 let r = ge_scalarmult_base(&nonce[0..32]);
772 signature[0..32].copy_from_slice(&r.to_bytes()[..]);
773 signature[32..64].copy_from_slice(&self.blind_pk.0);
774 let mut hasher = sha512::Hash::new();
775 hasher.update(signature.as_ref());
776 hasher.update(&message);
777 let mut hram = hasher.finalize();
778 sc_reduce(&mut hram);
779 sc_muladd(
780 &mut signature[32..64],
781 &hram[0..32],
782 &self.blind_scalar,
783 &nonce[0..32],
784 );
785 let signature = Signature(signature);
786
787 #[cfg(feature = "self-verify")]
788 {
789 PublicKey::from_slice(&self.blind_pk.0)
790 .expect("Key length changed")
791 .verify(message, &signature)
792 .expect("Newly created signature cannot be verified");
793 }
794 signature
795 }
796 }
797
798 impl Drop for BlindSecretKey {
799 fn drop(&mut self) {
800 Mem::wipe(self.prefix);
801 Mem::wipe(self.blind_scalar);
802 }
803 }
804
805 impl PublicKey {
806 pub fn blind(&self, blind: &Blind, ctx: impl AsRef<[u8]>) -> Result<BlindPublicKey, Error> {
808 let (blind_factor, _prefix2) = {
809 let mut hx = sha512::Hash::new();
810 hx.update(&blind[..]);
811 hx.update([0u8]);
812 hx.update(ctx.as_ref());
813 let hash_output = hx.finalize();
814 KeyPair::split(&hash_output, true, false)
815 };
816 let pk_p3 = GeP3::from_bytes_vartime(&self.0).ok_or(Error::InvalidPublicKey)?;
817 Ok(BlindPublicKey(
818 ge_scalarmult(&blind_factor, &pk_p3).to_bytes(),
819 ))
820 }
821 }
822
823 impl KeyPair {
824 pub fn blind(&self, blind: &Blind, ctx: impl AsRef<[u8]>) -> BlindKeyPair {
826 let seed = self.sk.seed();
827 let (scalar, prefix1) = {
828 let hash_output = sha512::Hash::hash(&seed[..]);
829 KeyPair::split(&hash_output, false, true)
830 };
831
832 let (blind_factor, prefix2) = {
833 let mut hx = sha512::Hash::new();
834 hx.update(&blind[..]);
835 hx.update([0u8]);
836 hx.update(ctx.as_ref());
837 let hash_output = hx.finalize();
838 KeyPair::split(&hash_output, true, false)
839 };
840
841 let blind_scalar = sc_mul(&scalar, &blind_factor);
842 let blind_pk = ge_scalarmult_base(&blind_scalar).to_bytes();
843
844 let mut prefix = [0u8; 2 * Seed::BYTES];
845 prefix[0..32].copy_from_slice(&prefix1);
846 prefix[32..64].copy_from_slice(&prefix2);
847 let blind_pk = BlindPublicKey::new(blind_pk);
848
849 BlindKeyPair {
850 blind_pk,
851 blind_sk: BlindSecretKey {
852 prefix,
853 blind_scalar,
854 blind_pk,
855 },
856 }
857 }
858 }
859}
860
861#[cfg(feature = "blind-keys")]
862pub use blind_keys::*;
863
864#[test]
865#[cfg(feature = "blind-keys")]
866fn test_blind_ed25519() {
867 use ct_codecs::{Decoder, Hex};
868
869 let kp = KeyPair::generate();
870 let blind = Blind::new([69u8; 32]);
871 let blind_kp = kp.blind(&blind, "ctx");
872 let message = b"Hello, World!";
873 let signature = blind_kp.blind_sk.sign(message, None);
874 assert!(blind_kp.blind_pk.verify(message, &signature).is_ok());
875 let recovered_pk = blind_kp.blind_pk.unblind(&blind, "ctx").unwrap();
876 assert!(recovered_pk == kp.pk);
877
878 let kp = KeyPair::from_seed(
879 Seed::from_slice(
880 &Hex::decode_to_vec(
881 "875532ab039b0a154161c284e19c74afa28d5bf5454e99284bbcffaa71eebf45",
882 None,
883 )
884 .unwrap(),
885 )
886 .unwrap(),
887 );
888 assert_eq!(
889 Hex::decode_to_vec(
890 "3b5983605b277cd44918410eb246bb52d83adfc806ccaa91a60b5b2011bc5973",
891 None
892 )
893 .unwrap(),
894 kp.pk.as_ref()
895 );
896
897 let blind = Blind::from_slice(
898 &Hex::decode_to_vec(
899 "c461e8595f0ac41d374f878613206704978115a226f60470ffd566e9e6ae73bf",
900 None,
901 )
902 .unwrap(),
903 )
904 .unwrap();
905 let blind_kp = kp.blind(&blind, "ctx");
906 assert_eq!(
907 Hex::decode_to_vec(
908 "246dcd43930b81d5e4d770db934a9fcd985b75fd014bc2a98b0aea02311c1836",
909 None
910 )
911 .unwrap(),
912 blind_kp.blind_pk.as_ref()
913 );
914
915 let message = Hex::decode_to_vec("68656c6c6f20776f726c64", None).unwrap();
916 let signature = blind_kp.blind_sk.sign(message, None);
917 assert_eq!(Hex::decode_to_vec("947bacfabc63448f8955dc20630e069e58f37b72bb433ae17f2fa904ea860b44deb761705a3cc2168a6673ee0b41ff7765c7a4896941eec6833c1689315acb0b",
918 None).unwrap(), signature.as_ref());
919}
920
921#[test]
922fn test_streaming() {
923 let kp = KeyPair::generate();
924
925 let msg1 = "mes";
926 let msg2 = "sage";
927 let mut st = kp.sk.sign_incremental(Noise::default());
928 st.absorb(msg1);
929 st.absorb(msg2);
930 let signature = st.sign();
931
932 let msg1 = "mess";
933 let msg2 = "age";
934 let mut st = kp.pk.verify_incremental(&signature).unwrap();
935 st.absorb(msg1);
936 st.absorb(msg2);
937 assert!(st.verify().is_ok());
938}
939
940#[test]
941#[cfg(feature = "random")]
942fn test_ed25519_invalid_keypair() {
943 let kp1 = KeyPair::generate();
944 let kp2 = KeyPair::generate();
945
946 assert_eq!(
947 kp1.sk.validate_public_key(&kp2.pk).unwrap_err(),
948 Error::InvalidPublicKey
949 );
950 assert_eq!(
951 kp2.sk.validate_public_key(&kp1.pk).unwrap_err(),
952 Error::InvalidPublicKey
953 );
954 assert!(kp1.sk.validate_public_key(&kp1.pk).is_ok());
955 assert!(kp2.sk.validate_public_key(&kp2.pk).is_ok());
956 assert!(kp1.validate().is_ok());
957}