dryoc 1.0.0

Don't Roll Your Own Crypto: pure-Rust, hard to misuse cryptography library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
//! # Public-key signatures
//!
//! This module implements libsodium's public-key signature functions. The
//! signatures are based on Ed25519 (EdDSA). It provides both a
//! [single-part](SigningKeyPair::sign) and [multi-part](IncrementalSigner)
//! interface.
//!
//! The single-part interface is convenient for short
//! messages, such as those small enough to fit in memory. The multi-part
//! interface may be more appropriate for lengthy messages, those which don't
//! fit in memory, or those for which the entire message isn't known at once
//! (i.e., during network communication, or reading a large file).
//!
//! The single-part and multi-part variants use slightly different algorithms,
//! and thus they are not compatible with each other.
//!
//! Use this module when you want to:
//!
//! * share a message with other parties, and provide a proof that the message
//!   is authentic
//! * verify that the message from another party was signed using their secret
//!   key, without having knowledge of the original secret
//!
//! The public key of the signer must be known to the verifier.
//!
//! Keep signing and encryption keys separate. Although Ed25519 keys can be
//! converted to X25519 keys or derived from the same seed, doing so couples two
//! distinct security roles.
//!
//! Signing secret keys include both the seed and public key. Use
//! [`secret_key_to_seed`], [`secret_key_to_public_key`],
//! [`SigningKeyPair::to_seed`], or [`SigningKeyPair::to_public_key`] to extract
//! those parts when interoperating with libsodium-style key storage.
//!
//! ## Rustaceous API example, single-part
//!
//! ```
//! use dryoc::sign::*;
//!
//! // Generate a random keypair, using default types
//! let keypair = SigningKeyPair::<PublicKey, SecretKey>::generate();
//! let message = b"Fair is foul, and foul is fair: Hover through the fog and filthy air.";
//!
//! // Sign the message, using default types (stack-allocated byte array, Vec<u8>)
//! let signed_message = keypair.sign_with_defaults(message).expect("signing failed");
//!
//! // Verify the message signature
//! signed_message
//!     .verify(&keypair.public_key)
//!     .expect("verification failed");
//! ```
//!
//! ## Extracting key material
//!
//! ```
//! use dryoc::sign::*;
//!
//! let seed = Seed::from([7u8; dryoc::constants::CRYPTO_SIGN_SEEDBYTES]);
//! let keypair = SigningKeyPair::<PublicKey, SecretKey>::from_seed(&seed);
//!
//! let extracted_seed: Seed = keypair.to_seed();
//! let extracted_public_key: PublicKey = keypair.to_public_key();
//!
//! assert_eq!(extracted_seed, seed);
//! assert_eq!(extracted_public_key, keypair.public_key);
//! ```
//!
//! ## Incremental (multi-part) interface
//!
//! ```
//! use dryoc::sign::*;
//!
//! // Generate a random keypair, using default types
//! let keypair = SigningKeyPair::<PublicKey, SecretKey>::generate();
//!
//! // Initialize the incremental signer interface
//! let mut signer = IncrementalSigner::new();
//! signer.update(b"This above all: to thine ownself be true.");
//! signer.update(b"And it must follow, as the night the day,");
//! signer.update(b"Thou canst not then be false to any man.");
//!
//! let signature: Signature = signer
//!     .finalize(&keypair.secret_key)
//!     .expect("signing failed");
//! ```
//!
//! ## Additional resources
//!
//! * See <https://libsodium.gitbook.io/doc/public-key_cryptography/public-key_signatures>
//!   for additional details on public-key signatures
//! * For secret-key based encryption, see
//!   [`DryocSecretBox`](crate::dryocsecretbox)
//! * For stream encryption, see [`DryocStream`](crate::dryocstream)
//! * See the [protected] mod for an example using the protected memory features

use std::fmt;

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use subtle::ConstantTimeEq;
use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};

use crate::classic::crypto_sign::{
    SignerState, crypto_sign_detached, crypto_sign_ed25519_sk_to_pk,
    crypto_sign_ed25519_sk_to_seed, crypto_sign_final_create, crypto_sign_final_verify,
    crypto_sign_init, crypto_sign_keypair_inplace, crypto_sign_seed_keypair_inplace,
    crypto_sign_update, crypto_sign_verify_detached,
};
use crate::constants::{
    CRYPTO_SIGN_BYTES, CRYPTO_SIGN_PUBLICKEYBYTES, CRYPTO_SIGN_SECRETKEYBYTES,
    CRYPTO_SIGN_SEEDBYTES,
};
use crate::error::Error;
use crate::types::*;

/// Stack-allocated public key for message signing.
pub type PublicKey = StackByteArray<CRYPTO_SIGN_PUBLICKEYBYTES>;
/// Stack-allocated secret key for message signing.
pub type SecretKey = StackByteArray<CRYPTO_SIGN_SECRETKEYBYTES>;
/// Stack-allocated seed for message signing.
pub type Seed = StackByteArray<CRYPTO_SIGN_SEEDBYTES>;
/// Stack-allocated signature for message signing.
pub type Signature = StackByteArray<CRYPTO_SIGN_BYTES>;
/// Heap-allocated message for message signing.
pub type Message = Vec<u8>;

/// Extracts the Ed25519 seed from a signing secret key.
pub fn secret_key_to_seed<
    SeedOut: NewByteArray<CRYPTO_SIGN_SEEDBYTES>,
    SigningSecretKey: ByteArray<CRYPTO_SIGN_SECRETKEYBYTES>,
>(
    secret_key: &SigningSecretKey,
) -> SeedOut {
    let mut seed = SeedOut::new_byte_array();
    crypto_sign_ed25519_sk_to_seed(seed.as_mut_array(), secret_key.as_array());
    seed
}

/// Extracts the Ed25519 public key from a signing secret key.
pub fn secret_key_to_public_key<
    PublicKeyOut: NewByteArray<CRYPTO_SIGN_PUBLICKEYBYTES>,
    SigningSecretKey: ByteArray<CRYPTO_SIGN_SECRETKEYBYTES>,
>(
    secret_key: &SigningSecretKey,
) -> PublicKeyOut {
    let mut public_key = PublicKeyOut::new_byte_array();
    crypto_sign_ed25519_sk_to_pk(public_key.as_mut_array(), secret_key.as_array());
    public_key
}

#[cfg_attr(
    feature = "serde",
    derive(Zeroize, ZeroizeOnDrop, Serialize, Deserialize, Clone)
)]
#[cfg_attr(not(feature = "serde"), derive(Zeroize, ZeroizeOnDrop, Clone))]
/// An Ed25519 keypair for public-key signatures
pub struct SigningKeyPair<
    PublicKey: ByteArray<CRYPTO_SIGN_PUBLICKEYBYTES> + Zeroize,
    SecretKey: ByteArray<CRYPTO_SIGN_SECRETKEYBYTES> + Zeroize,
> {
    /// Public key
    pub public_key: PublicKey,
    /// Secret key
    pub secret_key: SecretKey,
}

impl<
    PublicKey: ByteArray<CRYPTO_SIGN_PUBLICKEYBYTES> + Zeroize,
    SecretKey: ByteArray<CRYPTO_SIGN_SECRETKEYBYTES> + Zeroize,
> fmt::Debug for SigningKeyPair<PublicKey, SecretKey>
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SigningKeyPair")
            .field("public_key", &"[REDACTED]")
            .field("secret_key", &"[REDACTED]")
            .finish()
    }
}

impl<
    PublicKey: NewByteArray<CRYPTO_SIGN_PUBLICKEYBYTES> + Zeroize,
    SecretKey: NewByteArray<CRYPTO_SIGN_SECRETKEYBYTES> + Zeroize,
> SigningKeyPair<PublicKey, SecretKey>
{
    /// Creates a new, empty signing keypair.
    pub fn new() -> Self {
        Self {
            public_key: PublicKey::new_byte_array(),
            secret_key: SecretKey::new_byte_array(),
        }
    }

    /// Generates a random signing keypair.
    pub fn generate() -> Self {
        let mut public_key = PublicKey::new_byte_array();
        let mut secret_key = SecretKey::new_byte_array();
        crypto_sign_keypair_inplace(public_key.as_mut_array(), secret_key.as_mut_array());
        Self {
            public_key,
            secret_key,
        }
    }

    /// Generates a random signing keypair.
    ///
    /// Prefer [`generate`](Self::generate). `gen` is retained for compatibility
    /// with older Rust editions.
    #[deprecated(note = "use generate() instead")]
    pub fn r#gen() -> Self {
        Self::generate()
    }

    /// Derives a signing keypair from `secret_key`, and consumes it, returning
    /// a new keypair.
    pub fn from_secret_key(secret_key: SecretKey) -> Self {
        let mut seed = Zeroizing::new([0u8; 32]);
        seed.copy_from_slice(&secret_key.as_slice()[..32]);

        Self::from_seed(&*seed)
    }

    /// Derives a signing keypair from `seed`, returning
    /// a new keypair.
    pub fn from_seed<Seed: ByteArray<CRYPTO_SIGN_SEEDBYTES>>(seed: &Seed) -> Self {
        let mut public_key = PublicKey::new_byte_array();
        let mut secret_key = SecretKey::new_byte_array();

        crypto_sign_seed_keypair_inplace(
            public_key.as_mut_array(),
            secret_key.as_mut_array(),
            seed.as_array(),
        );

        Self {
            public_key,
            secret_key,
        }
    }
}

impl<
    PublicKey: ByteArray<CRYPTO_SIGN_PUBLICKEYBYTES> + Zeroize,
    SecretKey: ByteArray<CRYPTO_SIGN_SECRETKEYBYTES> + Zeroize,
> SigningKeyPair<PublicKey, SecretKey>
{
    /// Extracts the Ed25519 seed from this keypair's secret key.
    pub fn to_seed<SeedOut: NewByteArray<CRYPTO_SIGN_SEEDBYTES>>(&self) -> SeedOut {
        secret_key_to_seed(&self.secret_key)
    }

    /// Extracts the Ed25519 public key embedded in this keypair's secret key.
    pub fn to_public_key<PublicKeyOut: NewByteArray<CRYPTO_SIGN_PUBLICKEYBYTES>>(
        &self,
    ) -> PublicKeyOut {
        secret_key_to_public_key(&self.secret_key)
    }
}

impl
    SigningKeyPair<
        StackByteArray<CRYPTO_SIGN_PUBLICKEYBYTES>,
        StackByteArray<CRYPTO_SIGN_SECRETKEYBYTES>,
    >
{
    /// Randomly generates a new signing keypair, using default types
    /// (stack-allocated byte arrays). Provided for convenience.
    pub fn generate_with_defaults() -> Self {
        Self::generate()
    }

    /// Randomly generates a new signing keypair, using default types
    /// (stack-allocated byte arrays). Provided for convenience.
    ///
    /// Prefer [`generate_with_defaults`](Self::generate_with_defaults). This
    /// method is retained for compatibility.
    #[deprecated(note = "use generate_with_defaults() instead")]
    pub fn gen_with_defaults() -> Self {
        Self::generate_with_defaults()
    }
}

impl<
    'a,
    PublicKey: ByteArray<CRYPTO_SIGN_PUBLICKEYBYTES> + std::convert::TryFrom<&'a [u8]> + Zeroize,
    SecretKey: ByteArray<CRYPTO_SIGN_SECRETKEYBYTES> + std::convert::TryFrom<&'a [u8]> + Zeroize,
> SigningKeyPair<PublicKey, SecretKey>
{
    /// Constructs a new signing keypair from key slices, consuming them. Does
    /// not check validity or authenticity of keypair.
    ///
    /// # Errors
    ///
    /// Returns an error if either slice has the wrong length for its key type,
    /// or if the target key type rejects the key bytes.
    pub fn from_slices(public_key: &'a [u8], secret_key: &'a [u8]) -> Result<Self, Error> {
        validate_length!(
            exact CRYPTO_SIGN_PUBLICKEYBYTES,
            public_key.len(),
            crate::ErrorContext::PublicKey
        );
        validate_length!(
            exact CRYPTO_SIGN_SECRETKEYBYTES,
            secret_key.len(),
            crate::ErrorContext::SecretKey
        );

        Ok(Self {
            public_key: PublicKey::try_from(public_key)
                .map_err(|_| Error::invalid_key(crate::ErrorContext::PublicKey))?,
            secret_key: SecretKey::try_from(secret_key)
                .map_err(|_| Error::invalid_key(crate::ErrorContext::SecretKey))?,
        })
    }
}

#[cfg(any(all(feature = "protected", any(unix, windows)), all(doc, not(doctest))))]
#[cfg_attr(all(feature = "nightly", doc), doc(cfg(feature = "protected")))]
pub mod protected {
    //! # Protected memory for [`SigningKeyPair`] and [`SignedMessage`]
    //!
    //! ## Example
    //! ```
    //! use dryoc::sign::SigningKeyPair;
    //! use dryoc::sign::protected::*;
    //!
    //! // Generate a random keypair, using default types
    //! let keypair = SigningKeyPair::generate_locked_keypair().expect("keypair generate failed");
    //! let message = Message::from_slice_into_locked(
    //!     b"Fair is foul, and foul is fair: Hover through the fog and filthy air.",
    //! )
    //! .expect("message lock failed");
    //!
    //! // Sign the message, using default types (stack-allocated byte array, Vec<u8>)
    //! let signed_message: LockedSignedMessage = keypair.sign(message).expect("signing failed");
    //!
    //! // Verify the message signature
    //! signed_message
    //!     .verify(&keypair.public_key)
    //!     .expect("verification failed");
    //! ```
    use super::*;
    pub use crate::protected::*;

    /// Heap-allocated, page-aligned public-key for signed messages,
    /// for use with protected memory.
    pub type PublicKey = HeapByteArray<CRYPTO_SIGN_PUBLICKEYBYTES>;
    /// Heap-allocated, page-aligned secret-key for signed messages,
    /// for use with protected memory.
    pub type SecretKey = HeapByteArray<CRYPTO_SIGN_SECRETKEYBYTES>;
    /// Heap-allocated, page-aligned seed for signed messages,
    /// for use with protected memory.
    pub type Seed = HeapByteArray<CRYPTO_SIGN_SEEDBYTES>;
    /// Heap-allocated, page-aligned signature for signed messages,
    /// for use with protected memory.
    pub type Signature = HeapByteArray<CRYPTO_SIGN_BYTES>;
    /// Heap-allocated, page-aligned message for signed messages,
    /// for use with protected memory.
    pub type Message = HeapBytes;

    /// Heap-allocated, page-aligned public/secret keypair for message signing,
    /// for use with protected memory.
    pub type LockedSigningKeyPair = SigningKeyPair<Locked<PublicKey>, Locked<SecretKey>>;
    /// Heap-allocated, page-aligned signed message, for use with protected
    /// memory.
    pub type LockedSignedMessage = SignedMessage<Locked<Signature>, Locked<Message>>;

    impl
        SigningKeyPair<
            Locked<HeapByteArray<CRYPTO_SIGN_PUBLICKEYBYTES>>,
            Locked<HeapByteArray<CRYPTO_SIGN_SECRETKEYBYTES>>,
        >
    {
        /// Returns a new locked signing keypair.
        ///
        /// # Errors
        ///
        /// Returns [`Error::Io`] if either allocation cannot be locked.
        ///
        /// # Panics
        ///
        /// Panics if either page-aligned allocation cannot be created or its
        /// size cannot be represented with guard pages.
        pub fn new_locked_keypair() -> Result<Self, Error> {
            Ok(Self {
                public_key: HeapByteArray::<CRYPTO_SIGN_PUBLICKEYBYTES>::new_locked()?,
                secret_key: HeapByteArray::<CRYPTO_SIGN_SECRETKEYBYTES>::new_locked()?,
            })
        }

        /// Returns a new randomly generated locked signing keypair.
        ///
        /// # Errors
        ///
        /// Returns [`Error::Io`] if either allocation cannot be locked.
        ///
        /// # Panics
        ///
        /// Panics if either page-aligned allocation cannot be created, its
        /// size cannot be represented with guard pages, or the operating
        /// system's random number generator fails.
        pub fn generate_locked_keypair() -> Result<Self, Error> {
            let mut res = Self::new_locked_keypair()?;

            crypto_sign_keypair_inplace(
                res.public_key.as_mut_array(),
                res.secret_key.as_mut_array(),
            );

            Ok(res)
        }

        /// Returns a new randomly generated locked signing keypair.
        ///
        /// Prefer [`generate_locked_keypair`](Self::generate_locked_keypair).
        /// This method is retained for compatibility.
        ///
        /// # Errors
        ///
        /// Returns the same errors as
        /// [`generate_locked_keypair`](Self::generate_locked_keypair).
        ///
        /// # Panics
        ///
        /// Panics under the same conditions as
        /// [`generate_locked_keypair`](Self::generate_locked_keypair).
        #[deprecated(note = "use generate_locked_keypair() instead")]
        pub fn gen_locked_keypair() -> Result<Self, Error> {
            Self::generate_locked_keypair()
        }
    }

    impl
        SigningKeyPair<
            LockedRO<HeapByteArray<CRYPTO_SIGN_PUBLICKEYBYTES>>,
            LockedRO<HeapByteArray<CRYPTO_SIGN_SECRETKEYBYTES>>,
        >
    {
        /// Returns a new randomly generated locked, read-only signing keypair.
        ///
        /// # Errors
        ///
        /// Returns [`Error::Io`] if either allocation cannot be locked or its
        /// page permissions cannot be changed to read-only.
        ///
        /// # Panics
        ///
        /// Panics if either page-aligned allocation cannot be created, its
        /// size cannot be represented with guard pages, or the operating
        /// system's random number generator fails.
        pub fn generate_readonly_locked_keypair() -> Result<Self, Error> {
            let mut public_key = HeapByteArray::<CRYPTO_SIGN_PUBLICKEYBYTES>::new_locked()?;
            let mut secret_key = HeapByteArray::<CRYPTO_SIGN_SECRETKEYBYTES>::new_locked()?;

            crypto_sign_keypair_inplace(public_key.as_mut_array(), secret_key.as_mut_array());

            let public_key = public_key.mprotect_readonly()?;
            let secret_key = secret_key.mprotect_readonly()?;

            Ok(Self {
                public_key,
                secret_key,
            })
        }

        /// Returns a new randomly generated locked, read-only signing keypair.
        ///
        /// Prefer
        /// [`generate_readonly_locked_keypair`](Self::generate_readonly_locked_keypair).
        /// This method is retained for compatibility.
        ///
        /// # Errors
        ///
        /// Returns the same errors as
        /// [`generate_readonly_locked_keypair`](Self::generate_readonly_locked_keypair).
        ///
        /// # Panics
        ///
        /// Panics under the same conditions as
        /// [`generate_readonly_locked_keypair`](Self::generate_readonly_locked_keypair).
        #[deprecated(note = "use generate_readonly_locked_keypair() instead")]
        pub fn gen_readonly_locked_keypair() -> Result<Self, Error> {
            Self::generate_readonly_locked_keypair()
        }
    }
}

#[cfg_attr(
    feature = "serde",
    derive(Zeroize, Clone, Debug, Serialize, Deserialize)
)]
#[cfg_attr(not(feature = "serde"), derive(Zeroize, Clone, Debug))]
/// A signed message, for use with [`SigningKeyPair`].
pub struct SignedMessage<
    Signature: ByteArray<CRYPTO_SIGN_BYTES> + Zeroize,
    Message: Bytes + Zeroize,
> {
    signature: Signature,
    message: Message,
}

/// [Vec]-based signed message.
pub type VecSignedMessage = SignedMessage<Signature, Vec<u8>>;

impl<
    PublicKey: ByteArray<CRYPTO_SIGN_PUBLICKEYBYTES> + Zeroize,
    SecretKey: ByteArray<CRYPTO_SIGN_SECRETKEYBYTES> + Zeroize,
> SigningKeyPair<PublicKey, SecretKey>
{
    /// Signs `message` using this keypair, consuming the message, and returning
    /// a new [`SignedMessage`]. The type of `message` should match that of the
    /// target signed message.
    ///
    /// # Errors
    ///
    /// The fixed-size signature and secret-key types satisfy the current
    /// implementation's requirements, so this function does not return an
    /// error for valid type implementations. The [`Result`] is retained for
    /// compatibility with the underlying signing API.
    pub fn sign<Signature: NewByteArray<CRYPTO_SIGN_BYTES> + Zeroize, Message: Bytes + Zeroize>(
        &self,
        message: Message,
    ) -> Result<SignedMessage<Signature, Message>, Error> {
        let mut signature = Signature::new_byte_array();
        crypto_sign_detached(
            signature.as_mut_array(),
            message.as_slice(),
            self.secret_key.as_array(),
        )?;

        Ok(SignedMessage::<Signature, Message> { signature, message })
    }

    /// Signs `message`, putting the result into a [`Vec`]. Convenience wrapper
    /// for [`SigningKeyPair::sign`].
    ///
    /// # Errors
    ///
    /// The default fixed-size types satisfy the current implementation's
    /// requirements, so this function does not return an error in normal use.
    /// The [`Result`] is retained for API compatibility.
    pub fn sign_with_defaults<Message: Bytes>(
        &self,
        message: Message,
    ) -> Result<SignedMessage<StackByteArray<CRYPTO_SIGN_BYTES>, Vec<u8>>, Error> {
        self.sign(Vec::from(message.as_slice()))
    }
}

impl Default for SigningKeyPair<PublicKey, SecretKey> {
    fn default() -> Self {
        Self::new()
    }
}

/// Multi-part (incremental)  interface for [`SigningKeyPair`].
pub struct IncrementalSigner {
    state: SignerState,
}

impl IncrementalSigner {
    /// Returns a new incremental signer instance.
    pub fn new() -> Self {
        Self {
            state: crypto_sign_init(),
        }
    }

    /// Updates the state for this incremental signer with `message`.
    pub fn update<Message: Bytes>(&mut self, message: &Message) {
        crypto_sign_update(&mut self.state, message.as_slice())
    }

    /// Finalizes this incremental signer, returning the signature upon
    /// success.
    ///
    /// # Errors
    ///
    /// The fixed-size signature and secret-key types satisfy the current
    /// implementation's requirements, so this function does not return an
    /// error for valid type implementations. The [`Result`] is retained for
    /// compatibility with the underlying signing API.
    pub fn finalize<
        Signature: NewByteArray<CRYPTO_SIGN_BYTES>,
        SecretKey: ByteArray<CRYPTO_SIGN_SECRETKEYBYTES>,
    >(
        self,
        secret_key: &SecretKey,
    ) -> Result<Signature, Error> {
        let mut signature = Signature::new_byte_array();

        crypto_sign_final_create(self.state, signature.as_mut_array(), secret_key.as_array())?;

        Ok(signature)
    }

    /// Verifies `signature` as a valid signature for this signer.
    ///
    /// # Errors
    ///
    /// Returns an error if `signature` is not valid for the accumulated
    /// message and `public_key`.
    pub fn verify<
        Signature: ByteArray<CRYPTO_SIGN_BYTES>,
        PublicKey: ByteArray<CRYPTO_SIGN_PUBLICKEYBYTES>,
    >(
        self,
        signature: &Signature,
        public_key: &PublicKey,
    ) -> Result<(), Error> {
        crypto_sign_final_verify(self.state, signature.as_array(), public_key.as_array())?;

        Ok(())
    }
}

impl Default for IncrementalSigner {
    fn default() -> Self {
        Self::new()
    }
}

impl<Signature: ByteArray<CRYPTO_SIGN_BYTES> + Zeroize, Message: Bytes + Zeroize>
    SignedMessage<Signature, Message>
{
    /// Verifies that this signed message is valid for `public_key`.
    ///
    /// # Errors
    ///
    /// Returns an error if the signature is not valid for the message and
    /// `public_key`.
    pub fn verify<PublicKey: ByteArray<CRYPTO_SIGN_PUBLICKEYBYTES>>(
        &self,
        public_key: &PublicKey,
    ) -> Result<(), Error> {
        crypto_sign_verify_detached(
            self.signature.as_array(),
            self.message.as_slice(),
            public_key.as_array(),
        )
    }
}

impl<
    'a,
    Signature: ByteArray<CRYPTO_SIGN_BYTES> + std::convert::TryFrom<&'a [u8]> + Zeroize,
    Message: Bytes + From<&'a [u8]> + Zeroize,
> SignedMessage<Signature, Message>
{
    /// Initializes a [`SignedMessage`] from a slice. Expects the first
    /// [`CRYPTO_SIGN_BYTES`] bytes to contain the message signature,
    /// with the remaining bytes containing the message.
    ///
    /// # Errors
    ///
    /// Returns an error if `bytes` is shorter than a signature or the
    /// signature cannot be converted to the requested output type.
    pub fn from_bytes(bytes: &'a [u8]) -> Result<Self, Error> {
        if bytes.len() < CRYPTO_SIGN_BYTES {
            Err(
                length_error!(crate::ErrorContext::SignedMessage, bytes.len(), min CRYPTO_SIGN_BYTES),
            )
        } else {
            let (signature, message) = bytes.split_at(CRYPTO_SIGN_BYTES);
            Ok(Self {
                signature: Signature::try_from(signature)
                    .map_err(|_| Error::invalid_encoding(crate::ErrorContext::Signature))?,
                message: Message::from(message),
            })
        }
    }
}

impl<Signature: ByteArray<CRYPTO_SIGN_BYTES> + Zeroize, Message: Bytes + Zeroize>
    SignedMessage<Signature, Message>
{
    /// Returns a new box with `tag`, `data` and (optional) `ephemeral_pk`,
    /// consuming each.
    pub fn from_parts(signature: Signature, message: Message) -> Self {
        Self { signature, message }
    }

    /// Copies `self` into a new [`Vec`]
    pub fn to_vec(&self) -> Vec<u8> {
        self.to_bytes()
    }

    /// Moves the tag, data, and (optional) ephemeral public key out of this
    /// instance, returning them as a tuple.
    pub fn into_parts(self) -> (Signature, Message) {
        (self.signature, self.message)
    }

    /// Copies `self` into the target. Can be used with protected memory.
    pub fn to_bytes<Bytes: NewBytes + ResizableBytes>(&self) -> Bytes {
        let mut data = Bytes::new_bytes();

        data.resize(self.signature.len() + self.message.len(), 0);
        let s = data.as_mut_slice();
        s[..CRYPTO_SIGN_BYTES].copy_from_slice(self.signature.as_slice());
        s[CRYPTO_SIGN_BYTES..].copy_from_slice(self.message.as_slice());

        data
    }
}

impl<
    PublicKey: ByteArray<CRYPTO_SIGN_PUBLICKEYBYTES> + Zeroize,
    SecretKey: ByteArray<CRYPTO_SIGN_SECRETKEYBYTES> + Zeroize,
> PartialEq<SigningKeyPair<PublicKey, SecretKey>> for SigningKeyPair<PublicKey, SecretKey>
{
    fn eq(&self, other: &Self) -> bool {
        self.public_key
            .as_slice()
            .ct_eq(other.public_key.as_slice())
            .unwrap_u8()
            == 1
            && self
                .secret_key
                .as_slice()
                .ct_eq(other.secret_key.as_slice())
                .unwrap_u8()
                == 1
    }
}

impl<Signature: ByteArray<CRYPTO_SIGN_BYTES> + Zeroize, Message: Bytes + Zeroize>
    PartialEq<SignedMessage<Signature, Message>> for SignedMessage<Signature, Message>
{
    fn eq(&self, other: &Self) -> bool {
        self.signature
            .as_slice()
            .ct_eq(other.signature.as_slice())
            .unwrap_u8()
            == 1
            && self
                .message
                .as_slice()
                .ct_eq(other.message.as_slice())
                .unwrap_u8()
                == 1
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn signing_keypair_debug_redacts_keys_and_secret_key_reconstructs_keypair() {
        let keypair = SigningKeyPair::<PublicKey, SecretKey>::generate();
        let debug = format!("{keypair:?}");
        let reconstructed = SigningKeyPair::from_secret_key(keypair.secret_key.clone());

        assert_eq!(
            debug,
            "SigningKeyPair { public_key: \"[REDACTED]\", secret_key: \"[REDACTED]\" }"
        );
        assert_eq!(reconstructed, keypair);
    }

    #[test]
    fn test_message_signing() {
        let keypair = SigningKeyPair::generate_with_defaults();
        let message = b"hello my frens";

        let signed_message = keypair.sign_with_defaults(message).expect("signing failed");

        signed_message
            .verify(&keypair.public_key)
            .expect("verification failed");
    }

    #[test]
    fn test_secret_key_extraction() {
        let seed = Seed::generate();
        let keypair = SigningKeyPair::<PublicKey, SecretKey>::from_seed(&seed);

        let extracted_seed: Seed = keypair.to_seed();
        let extracted_public_key: PublicKey = keypair.to_public_key();
        assert_eq!(extracted_seed, seed);
        assert_eq!(extracted_public_key, keypair.public_key);

        let extracted_seed_vec: Vec<u8> = secret_key_to_seed(&keypair.secret_key);
        let extracted_public_key_vec: Vec<u8> = secret_key_to_public_key(&keypair.secret_key);
        assert_eq!(extracted_seed_vec.as_slice(), seed.as_slice());
        assert_eq!(
            extracted_public_key_vec.as_slice(),
            keypair.public_key.as_slice()
        );
    }
}