wolfcose 0.1.0

Safe Rust API for wolfSSL wolfCOSE.
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
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
#![allow(clippy::too_many_arguments)]

use crate::error::{Error, Result};
use crate::raw;
use crate::types::{Algorithm, Curve, KeyType};
use alloc::{vec, vec::Vec};
use core::ffi::c_void;
use core::marker::PhantomData;
use core::ptr;
use core::ptr::NonNull;
use core::slice;

/// Attached or detached payload input.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PayloadMode<'a> {
    /// Payload is embedded in the COSE message.
    Attached(&'a [u8]),
    /// Payload is authenticated externally and encoded as CBOR null.
    Detached(&'a [u8]),
}

impl<'a> PayloadMode<'a> {
    fn sign_parts(self) -> (*const u8, usize, *const u8, usize) {
        match self {
            Self::Attached(payload) => ptr_len(payload).with_detached(None),
            Self::Detached(payload) => (ptr::null(), 0, ptr_or_null(payload), payload.len()),
        }
    }
}

trait WithDetached {
    fn with_detached(self, detached: Option<&[u8]>) -> (*const u8, usize, *const u8, usize);
}

impl WithDetached for (*const u8, usize) {
    fn with_detached(self, detached: Option<&[u8]>) -> (*const u8, usize, *const u8, usize) {
        match detached {
            Some(data) => (self.0, self.1, ptr_or_null(data), data.len()),
            None => (self.0, self.1, ptr::null(), 0),
        }
    }
}

/// Parsed COSE protected/unprotected header subset exposed by wolfCOSE.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Header {
    /// Algorithm identifier.
    pub algorithm: i32,
    /// Key identifier, if present.
    pub kid: Vec<u8>,
    /// IV, if present.
    pub iv: Vec<u8>,
    /// Partial IV, if present.
    pub partial_iv: Vec<u8>,
    /// Content type, or zero if absent.
    pub content_type: i32,
    /// Whether the payload/ciphertext is detached.
    pub detached: bool,
}

impl Header {
    fn from_raw(raw_hdr: &raw::WOLFCOSE_HDR) -> Self {
        Self {
            algorithm: raw_hdr.alg,
            kid: copy_opt(raw_hdr.kid, raw_hdr.kidLen),
            iv: copy_opt(raw_hdr.iv, raw_hdr.ivLen),
            partial_iv: copy_opt(raw_hdr.partialIv, raw_hdr.partialIvLen),
            content_type: raw_hdr.contentType,
            detached: (raw_hdr.flags & raw::WOLFCOSE_HDR_FLAG_DETACHED as u8) != 0,
        }
    }
}

/// Owned wolfCOSE key descriptor.
///
/// Symmetric key material and key IDs are owned by this Rust value. Asymmetric
/// wolfCrypt key objects are intentionally handled through raw FFI escape
/// hatches because ownership APIs depend on the installed wolfSSL feature set.
pub struct CoseKey {
    raw: raw::WOLFCOSE_KEY,
    key_material: Option<Vec<u8>>,
    kid: Option<Vec<u8>>,
}

impl CoseKey {
    /// Create an initialized empty key descriptor.
    pub fn new() -> Result<Self> {
        let mut raw_key = raw::WOLFCOSE_KEY::default();
        // SAFETY: `raw_key` is valid output storage for wolfCOSE initialization.
        Error::from_code(unsafe { raw::wc_CoseKey_Init(&mut raw_key) })?;
        Ok(Self {
            raw: raw_key,
            key_material: None,
            kid: None,
        })
    }

    /// Create an owned symmetric key descriptor.
    pub fn symmetric(material: impl AsRef<[u8]>) -> Result<Self> {
        let mut key = Self::new()?;
        key.set_symmetric(material)?;
        Ok(key)
    }

    /// Replace this descriptor with owned symmetric key material.
    pub fn set_symmetric(&mut self, material: impl AsRef<[u8]>) -> Result<()> {
        let material = material.as_ref().to_vec();
        let ptr = ptr_or_null(&material);
        // SAFETY: `self.raw` is initialized and `material` is stored in `self`
        // after the call, so wolfCOSE's borrowed pointer remains valid.
        Error::from_code(unsafe {
            raw::wc_CoseKey_SetSymmetric(&mut self.raw, ptr, material.len())
        })?;
        self.key_material = Some(material);
        Ok(())
    }

    /// Attach a caller-owned wolfCrypt ECC key.
    ///
    /// # Safety
    ///
    /// `ecc_key` must point to an initialized `ecc_key` from the same wolfSSL
    /// build that wolfCOSE is linked against, and it must outlive this
    /// `CoseKey` descriptor and all operations using it.
    pub unsafe fn set_ecc_raw(&mut self, curve: Curve, ecc_key: NonNull<c_void>) -> Result<()> {
        // SAFETY: The caller guarantees `ecc_key` points to a valid wolfCrypt
        // ECC key. The shim returns Unsupported when ECC is unavailable.
        Error::from_code(unsafe {
            raw::rb_wc_CoseKey_SetEcc(self.as_raw_mut(), curve.id(), ecc_key.as_ptr())
        })
    }

    /// Attach a caller-owned wolfCrypt Ed25519 key.
    ///
    /// # Safety
    ///
    /// `ed_key` must point to an initialized `ed25519_key` from the same
    /// wolfSSL build that wolfCOSE is linked against, and it must outlive this
    /// descriptor and all operations using it.
    pub unsafe fn set_ed25519_raw(&mut self, ed_key: NonNull<c_void>) -> Result<()> {
        // SAFETY: The caller guarantees `ed_key` points to a valid wolfCrypt
        // Ed25519 key. The shim returns Unsupported when Ed25519 is unavailable.
        Error::from_code(unsafe {
            raw::rb_wc_CoseKey_SetEd25519(self.as_raw_mut(), ed_key.as_ptr())
        })
    }

    /// Attach a caller-owned wolfCrypt Ed448 key.
    ///
    /// # Safety
    ///
    /// `ed_key` must point to an initialized `ed448_key` from the same wolfSSL
    /// build that wolfCOSE is linked against, and it must outlive this
    /// descriptor and all operations using it.
    pub unsafe fn set_ed448_raw(&mut self, ed_key: NonNull<c_void>) -> Result<()> {
        // SAFETY: The caller guarantees `ed_key` points to a valid wolfCrypt
        // Ed448 key. The shim returns Unsupported when Ed448 is unavailable.
        Error::from_code(unsafe { raw::rb_wc_CoseKey_SetEd448(self.as_raw_mut(), ed_key.as_ptr()) })
    }

    /// Attach a caller-owned wolfCrypt Dilithium/ML-DSA key.
    ///
    /// # Safety
    ///
    /// `dl_key` must point to an initialized `dilithium_key` from the same
    /// wolfSSL build that wolfCOSE is linked against, and it must outlive this
    /// descriptor and all operations using it.
    pub unsafe fn set_dilithium_raw(
        &mut self,
        algorithm: Algorithm,
        dl_key: NonNull<c_void>,
    ) -> Result<()> {
        // SAFETY: The caller guarantees `dl_key` points to a valid wolfCrypt
        // Dilithium key. The shim returns Unsupported when Dilithium is unavailable.
        Error::from_code(unsafe {
            raw::rb_wc_CoseKey_SetDilithium(self.as_raw_mut(), algorithm.id(), dl_key.as_ptr())
        })
    }

    /// Attach a caller-owned wolfCrypt RSA key.
    ///
    /// # Safety
    ///
    /// `rsa_key` must point to an initialized `RsaKey` from the same wolfSSL
    /// build that wolfCOSE is linked against, and it must outlive this
    /// descriptor and all operations using it.
    pub unsafe fn set_rsa_raw(&mut self, rsa_key: NonNull<c_void>) -> Result<()> {
        // SAFETY: The caller guarantees `rsa_key` points to a valid wolfCrypt
        // RSA key. The shim returns Unsupported when RSA-PSS is unavailable.
        Error::from_code(unsafe { raw::rb_wc_CoseKey_SetRsa(self.as_raw_mut(), rsa_key.as_ptr()) })
    }

    /// Set an owned key identifier on this descriptor.
    pub fn set_kid(&mut self, kid: impl AsRef<[u8]>) {
        let kid = kid.as_ref().to_vec();
        self.raw.kid = ptr_or_null(&kid);
        self.raw.kidLen = kid.len();
        self.kid = Some(kid);
    }

    /// Set the raw algorithm identifier.
    pub fn set_algorithm(&mut self, algorithm: Algorithm) {
        self.raw.alg = algorithm.id();
    }

    /// Set the COSE key type.
    pub fn set_key_type(&mut self, key_type: KeyType) {
        self.raw.kty = key_type.id();
    }

    /// Set the COSE curve identifier.
    pub fn set_curve(&mut self, curve: Curve) {
        self.raw.crv = curve.id();
    }

    /// Mark whether private key material is present.
    pub fn set_has_private(&mut self, has_private: bool) {
        self.raw.hasPrivate = u8::from(has_private);
    }

    /// Whether private key material is marked as present.
    pub fn has_private(&self) -> bool {
        self.raw.hasPrivate != 0
    }

    /// Key identifier bytes currently attached to this descriptor.
    pub fn kid(&self) -> Option<&[u8]> {
        self.kid.as_deref()
    }

    /// Owned symmetric key material currently held by this descriptor.
    pub fn symmetric_material(&self) -> Option<&[u8]> {
        self.key_material.as_deref()
    }

    /// Encode this key as a COSE_Key map into a caller-provided buffer.
    pub fn encode_into<'out>(&mut self, out: &'out mut [u8]) -> Result<&'out [u8]> {
        let mut out_len = 0;
        // SAFETY: key and output buffer are valid.
        Error::from_code(unsafe {
            raw::wc_CoseKey_Encode(&mut self.raw, out.as_mut_ptr(), out.len(), &mut out_len)
        })?;
        Ok(&out[..out_len])
    }

    /// Encode this key as a COSE_Key map into a new vector.
    pub fn encode_to_vec(&mut self) -> Result<Vec<u8>> {
        with_growing_output(|out| self.encode_into(out).map(|slice| slice.len()))
    }

    /// Decode a COSE_Key map into this descriptor.
    ///
    /// For asymmetric keys, callers must attach the required wolfCrypt key
    /// object through [`raw`] before decoding, matching the C API contract.
    pub fn decode(&mut self, input: &[u8]) -> Result<()> {
        // SAFETY: descriptor and input slice are valid.
        Error::from_code(unsafe {
            raw::wc_CoseKey_Decode(&mut self.raw, ptr_or_null(input), input.len())
        })
    }

    /// Borrow the raw wolfCOSE key.
    pub fn as_raw(&self) -> &raw::WOLFCOSE_KEY {
        &self.raw
    }

    /// Mutably borrow the raw wolfCOSE key.
    pub fn as_raw_mut(&mut self) -> &mut raw::WOLFCOSE_KEY {
        &mut self.raw
    }

    fn as_mut_ptr(&self) -> *mut raw::WOLFCOSE_KEY {
        (&self.raw as *const raw::WOLFCOSE_KEY).cast_mut()
    }
}

impl Drop for CoseKey {
    fn drop(&mut self) {
        // SAFETY: `raw` was initialized by `wc_CoseKey_Init`. The C function
        // does not free caller-owned underlying key material.
        unsafe { raw::wc_CoseKey_Free(&mut self.raw) }
    }
}

/// Signer descriptor for COSE_Sign.
pub struct Signature<'a> {
    algorithm: Algorithm,
    key: &'a CoseKey,
    kid: Option<&'a [u8]>,
}

impl<'a> Signature<'a> {
    /// Create a signer descriptor.
    pub fn new(algorithm: Algorithm, key: &'a CoseKey) -> Self {
        Self {
            algorithm,
            key,
            kid: None,
        }
    }

    /// Include a key identifier for this signer.
    pub fn with_kid(mut self, kid: &'a [u8]) -> Self {
        self.kid = Some(kid);
        self
    }

    fn to_raw(&self) -> raw::WOLFCOSE_SIGNATURE {
        let kid = self.kid.unwrap_or(&[]);
        raw::WOLFCOSE_SIGNATURE {
            algId: self.algorithm.id(),
            key: self.key.as_mut_ptr(),
            kid: ptr_or_null(kid),
            kidLen: kid.len(),
        }
    }
}

/// Recipient descriptor for COSE_Encrypt and COSE_Mac.
pub struct Recipient<'a> {
    algorithm: Algorithm,
    key: &'a CoseKey,
    kid: Option<&'a [u8]>,
}

impl<'a> Recipient<'a> {
    /// Create a recipient descriptor.
    pub fn new(algorithm: Algorithm, key: &'a CoseKey) -> Self {
        Self {
            algorithm,
            key,
            kid: None,
        }
    }

    /// Include a key identifier for this recipient.
    pub fn with_kid(mut self, kid: &'a [u8]) -> Self {
        self.kid = Some(kid);
        self
    }

    fn to_raw(&self) -> raw::WOLFCOSE_RECIPIENT {
        let kid = self.kid.unwrap_or(&[]);
        raw::WOLFCOSE_RECIPIENT {
            algId: self.algorithm.id(),
            key: self.key.as_mut_ptr(),
            kid: ptr_or_null(kid),
            kidLen: kid.len(),
        }
    }
}

/// Result of signature or MAC verification.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct VerifyOutput<'a> {
    /// Parsed headers.
    pub header: Header,
    /// Attached payload, or `None` for detached payload messages.
    pub payload: Option<&'a [u8]>,
}

/// Result of MAC verification.
pub type MacVerifyOutput<'a> = VerifyOutput<'a>;

/// Result of decryption.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DecryptOutput {
    /// Parsed headers.
    pub header: Header,
    /// Number of plaintext bytes written.
    pub plaintext_len: usize,
}

/// Result of detached Encrypt0 encryption.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Encrypt0DetachedOutput {
    /// Number of COSE message bytes written.
    pub message_len: usize,
    /// Number of detached ciphertext bytes written.
    pub ciphertext_len: usize,
}

/// Sign a payload as COSE_Sign1 into a caller-provided buffer.
pub fn sign1_into<'out>(
    key: &CoseKey,
    algorithm: Algorithm,
    kid: Option<&[u8]>,
    payload: PayloadMode<'_>,
    external_aad: &[u8],
    scratch: &mut [u8],
    out: &'out mut [u8],
    rng: Option<NonNull<raw::WC_RNG>>,
) -> Result<&'out [u8]> {
    let kid = kid.unwrap_or(&[]);
    let (payload_ptr, payload_len, detached_ptr, detached_len) = payload.sign_parts();
    let mut out_len = 0;
    // SAFETY: all pointers are derived from valid slices or are null for absent
    // optional values; output lengths are valid.
    Error::from_code(unsafe {
        raw::wc_CoseSign1_Sign(
            key.as_mut_ptr(),
            algorithm.id(),
            ptr_or_null(kid),
            kid.len(),
            payload_ptr,
            payload_len,
            detached_ptr,
            detached_len,
            ptr_or_null(external_aad),
            external_aad.len(),
            scratch.as_mut_ptr(),
            scratch.len(),
            out.as_mut_ptr(),
            out.len(),
            &mut out_len,
            rng_ptr(rng),
        )
    })?;
    Ok(&out[..out_len])
}

/// Sign a payload as COSE_Sign1 into a new vector.
pub fn sign1_to_vec(
    key: &CoseKey,
    algorithm: Algorithm,
    kid: Option<&[u8]>,
    payload: PayloadMode<'_>,
    external_aad: &[u8],
    scratch: &mut [u8],
    rng: Option<NonNull<raw::WC_RNG>>,
) -> Result<Vec<u8>> {
    with_growing_output(|out| {
        sign1_into(
            key,
            algorithm,
            kid,
            payload,
            external_aad,
            scratch,
            out,
            rng,
        )
        .map(|slice| slice.len())
    })
}

/// Verify a COSE_Sign1 message.
pub fn verify1<'inbuf>(
    key: &CoseKey,
    input: &'inbuf [u8],
    detached_payload: Option<&[u8]>,
    external_aad: &[u8],
    scratch: &mut [u8],
) -> Result<VerifyOutput<'inbuf>> {
    let mut header = raw::WOLFCOSE_HDR::default();
    let mut payload = ptr::null();
    let mut payload_len = 0;
    let detached = detached_payload.unwrap_or(&[]);
    // SAFETY: all pointers are valid for their lengths or null for absent
    // detached payload.
    Error::from_code(unsafe {
        raw::wc_CoseSign1_Verify(
            key.as_mut_ptr(),
            ptr_or_null(input),
            input.len(),
            opt_ptr(detached_payload),
            detached.len(),
            ptr_or_null(external_aad),
            external_aad.len(),
            scratch.as_mut_ptr(),
            scratch.len(),
            &mut header,
            &mut payload,
            &mut payload_len,
        )
    })?;
    Ok(VerifyOutput {
        header: Header::from_raw(&header),
        payload: borrowed_payload(payload, payload_len),
    })
}

/// Encrypt a payload as COSE_Encrypt0 into a caller-provided buffer.
pub fn encrypt0_into<'out>(
    key: &CoseKey,
    algorithm: Algorithm,
    iv: &[u8],
    payload: &[u8],
    external_aad: &[u8],
    scratch: &mut [u8],
    out: &'out mut [u8],
) -> Result<&'out [u8]> {
    let mut out_len = 0;
    let mut detached_len = 0;
    // SAFETY: all slice pointers and output length pointers are valid.
    Error::from_code(unsafe {
        raw::wc_CoseEncrypt0_Encrypt(
            key.as_mut_ptr(),
            algorithm.id(),
            ptr_or_null(iv),
            iv.len(),
            ptr_or_null(payload),
            payload.len(),
            ptr::null_mut(),
            0,
            &mut detached_len,
            ptr_or_null(external_aad),
            external_aad.len(),
            scratch.as_mut_ptr(),
            scratch.len(),
            out.as_mut_ptr(),
            out.len(),
            &mut out_len,
        )
    })?;
    Ok(&out[..out_len])
}

/// Encrypt a payload as COSE_Encrypt0 into a new vector.
pub fn encrypt0_to_vec(
    key: &CoseKey,
    algorithm: Algorithm,
    iv: &[u8],
    payload: &[u8],
    external_aad: &[u8],
    scratch: &mut [u8],
) -> Result<Vec<u8>> {
    with_growing_output(|out| {
        encrypt0_into(key, algorithm, iv, payload, external_aad, scratch, out)
            .map(|slice| slice.len())
    })
}

/// Encrypt as detached COSE_Encrypt0, writing message and ciphertext separately.
pub fn encrypt0_detached_into(
    key: &CoseKey,
    algorithm: Algorithm,
    iv: &[u8],
    plaintext: &[u8],
    external_aad: &[u8],
    scratch: &mut [u8],
    out: &mut [u8],
    detached_ciphertext: &mut [u8],
) -> Result<Encrypt0DetachedOutput> {
    let mut out_len = 0;
    let mut detached_len = 0;
    // SAFETY: all slice pointers and output length pointers are valid.
    Error::from_code(unsafe {
        raw::wc_CoseEncrypt0_Encrypt(
            key.as_mut_ptr(),
            algorithm.id(),
            ptr_or_null(iv),
            iv.len(),
            ptr_or_null(plaintext),
            plaintext.len(),
            detached_ciphertext.as_mut_ptr(),
            detached_ciphertext.len(),
            &mut detached_len,
            ptr_or_null(external_aad),
            external_aad.len(),
            scratch.as_mut_ptr(),
            scratch.len(),
            out.as_mut_ptr(),
            out.len(),
            &mut out_len,
        )
    })?;
    Ok(Encrypt0DetachedOutput {
        message_len: out_len,
        ciphertext_len: detached_len,
    })
}

/// Decrypt a COSE_Encrypt0 message into a caller-provided plaintext buffer.
pub fn verify0_into(
    key: &CoseKey,
    input: &[u8],
    detached_ciphertext: Option<&[u8]>,
    external_aad: &[u8],
    scratch: &mut [u8],
    plaintext: &mut [u8],
) -> Result<DecryptOutput> {
    decrypt0_into(
        key,
        input,
        detached_ciphertext,
        external_aad,
        scratch,
        plaintext,
    )
}

/// Decrypt a COSE_Encrypt0 message into a caller-provided plaintext buffer.
pub fn decrypt0_into(
    key: &CoseKey,
    input: &[u8],
    detached_ciphertext: Option<&[u8]>,
    external_aad: &[u8],
    scratch: &mut [u8],
    plaintext: &mut [u8],
) -> Result<DecryptOutput> {
    let mut header = raw::WOLFCOSE_HDR::default();
    let mut plaintext_len = 0;
    let detached = detached_ciphertext.unwrap_or(&[]);
    // SAFETY: all pointers are valid for their lengths or null for absent
    // detached ciphertext.
    Error::from_code(unsafe {
        raw::wc_CoseEncrypt0_Decrypt(
            key.as_mut_ptr(),
            ptr_or_null(input),
            input.len(),
            opt_ptr(detached_ciphertext),
            detached.len(),
            ptr_or_null(external_aad),
            external_aad.len(),
            scratch.as_mut_ptr(),
            scratch.len(),
            &mut header,
            plaintext.as_mut_ptr(),
            plaintext.len(),
            &mut plaintext_len,
        )
    })?;
    Ok(DecryptOutput {
        header: Header::from_raw(&header),
        plaintext_len,
    })
}

/// Create a COSE_Mac0 message into a caller-provided buffer.
pub fn mac0_into<'out>(
    key: &CoseKey,
    algorithm: Algorithm,
    kid: Option<&[u8]>,
    payload: PayloadMode<'_>,
    external_aad: &[u8],
    scratch: &mut [u8],
    out: &'out mut [u8],
) -> Result<&'out [u8]> {
    let kid = kid.unwrap_or(&[]);
    let (payload_ptr, payload_len, detached_ptr, detached_len) = payload.sign_parts();
    let mut out_len = 0;
    // SAFETY: all pointers are valid for their lengths or null for absent data.
    Error::from_code(unsafe {
        raw::wc_CoseMac0_Create(
            key.as_raw(),
            algorithm.id(),
            ptr_or_null(kid),
            kid.len(),
            payload_ptr,
            payload_len,
            detached_ptr,
            detached_len,
            ptr_or_null(external_aad),
            external_aad.len(),
            scratch.as_mut_ptr(),
            scratch.len(),
            out.as_mut_ptr(),
            out.len(),
            &mut out_len,
        )
    })?;
    Ok(&out[..out_len])
}

/// Create a COSE_Mac0 message into a new vector.
pub fn mac0_to_vec(
    key: &CoseKey,
    algorithm: Algorithm,
    kid: Option<&[u8]>,
    payload: PayloadMode<'_>,
    external_aad: &[u8],
    scratch: &mut [u8],
) -> Result<Vec<u8>> {
    with_growing_output(|out| {
        mac0_into(key, algorithm, kid, payload, external_aad, scratch, out).map(|slice| slice.len())
    })
}

/// Verify a COSE_Mac0 message.
pub fn verify_mac0<'inbuf>(
    key: &CoseKey,
    input: &'inbuf [u8],
    detached_payload: Option<&[u8]>,
    external_aad: &[u8],
    scratch: &mut [u8],
) -> Result<MacVerifyOutput<'inbuf>> {
    let mut header = raw::WOLFCOSE_HDR::default();
    let mut payload = ptr::null();
    let mut payload_len = 0;
    let detached = detached_payload.unwrap_or(&[]);
    // SAFETY: all pointers are valid for their lengths or null for absent data.
    Error::from_code(unsafe {
        raw::wc_CoseMac0_Verify(
            key.as_raw(),
            ptr_or_null(input),
            input.len(),
            opt_ptr(detached_payload),
            detached.len(),
            ptr_or_null(external_aad),
            external_aad.len(),
            scratch.as_mut_ptr(),
            scratch.len(),
            &mut header,
            &mut payload,
            &mut payload_len,
        )
    })?;
    Ok(VerifyOutput {
        header: Header::from_raw(&header),
        payload: borrowed_payload(payload, payload_len),
    })
}

/// Create a multi-signer COSE_Sign message into a caller-provided buffer.
pub fn sign_into<'out>(
    signers: &[Signature<'_>],
    payload: PayloadMode<'_>,
    external_aad: &[u8],
    scratch: &mut [u8],
    out: &'out mut [u8],
    rng: Option<NonNull<raw::WC_RNG>>,
) -> Result<&'out [u8]> {
    let raw_signers: Vec<_> = signers.iter().map(Signature::to_raw).collect();
    let (payload_ptr, payload_len, detached_ptr, detached_len) = payload.sign_parts();
    let mut out_len = 0;
    // SAFETY: raw signer array points to keys borrowed from `signers`; all
    // slices and outputs are valid for this call.
    Error::from_code(unsafe {
        raw::wc_CoseSign_Sign(
            raw_signers.as_ptr(),
            raw_signers.len(),
            payload_ptr,
            payload_len,
            detached_ptr,
            detached_len,
            ptr_or_null(external_aad),
            external_aad.len(),
            scratch.as_mut_ptr(),
            scratch.len(),
            out.as_mut_ptr(),
            out.len(),
            &mut out_len,
            rng_ptr(rng),
        )
    })?;
    Ok(&out[..out_len])
}

/// Create a multi-signer COSE_Sign message into a new vector.
pub fn sign_to_vec(
    signers: &[Signature<'_>],
    payload: PayloadMode<'_>,
    external_aad: &[u8],
    scratch: &mut [u8],
    rng: Option<NonNull<raw::WC_RNG>>,
) -> Result<Vec<u8>> {
    with_growing_output(|out| {
        sign_into(signers, payload, external_aad, scratch, out, rng).map(|s| s.len())
    })
}

/// Verify one signer in a COSE_Sign message.
pub fn verify_sign<'inbuf>(
    key: &CoseKey,
    signer_index: usize,
    input: &'inbuf [u8],
    detached_payload: Option<&[u8]>,
    external_aad: &[u8],
    scratch: &mut [u8],
) -> Result<VerifyOutput<'inbuf>> {
    let mut header = raw::WOLFCOSE_HDR::default();
    let mut payload = ptr::null();
    let mut payload_len = 0;
    let detached = detached_payload.unwrap_or(&[]);
    // SAFETY: all pointers are valid for their lengths or null for absent data.
    Error::from_code(unsafe {
        raw::wc_CoseSign_Verify(
            key.as_raw(),
            signer_index,
            ptr_or_null(input),
            input.len(),
            opt_ptr(detached_payload),
            detached.len(),
            ptr_or_null(external_aad),
            external_aad.len(),
            scratch.as_mut_ptr(),
            scratch.len(),
            &mut header,
            &mut payload,
            &mut payload_len,
        )
    })?;
    Ok(VerifyOutput {
        header: Header::from_raw(&header),
        payload: borrowed_payload(payload, payload_len),
    })
}

/// Create a multi-recipient COSE_Encrypt message into a caller-provided buffer.
pub fn encrypt_into<'out>(
    recipients: &[Recipient<'_>],
    content_algorithm: Algorithm,
    iv: &[u8],
    payload: &[u8],
    external_aad: &[u8],
    scratch: &mut [u8],
    out: &'out mut [u8],
    rng: Option<NonNull<raw::WC_RNG>>,
) -> Result<&'out [u8]> {
    let raw_recipients: Vec<_> = recipients.iter().map(Recipient::to_raw).collect();
    let mut out_len = 0;
    // SAFETY: recipient array and all slices are valid for this call.
    Error::from_code(unsafe {
        raw::wc_CoseEncrypt_Encrypt(
            raw_recipients.as_ptr(),
            raw_recipients.len(),
            content_algorithm.id(),
            ptr_or_null(iv),
            iv.len(),
            ptr_or_null(payload),
            payload.len(),
            ptr::null(),
            0,
            ptr_or_null(external_aad),
            external_aad.len(),
            scratch.as_mut_ptr(),
            scratch.len(),
            out.as_mut_ptr(),
            out.len(),
            &mut out_len,
            rng_ptr(rng),
        )
    })?;
    Ok(&out[..out_len])
}

/// Create a multi-recipient COSE_Encrypt message into a new vector.
pub fn encrypt_to_vec(
    recipients: &[Recipient<'_>],
    content_algorithm: Algorithm,
    iv: &[u8],
    payload: &[u8],
    external_aad: &[u8],
    scratch: &mut [u8],
    rng: Option<NonNull<raw::WC_RNG>>,
) -> Result<Vec<u8>> {
    with_growing_output(|out| {
        encrypt_into(
            recipients,
            content_algorithm,
            iv,
            payload,
            external_aad,
            scratch,
            out,
            rng,
        )
        .map(|slice| slice.len())
    })
}

/// Create a detached multi-recipient COSE_Encrypt message.
pub fn encrypt_detached_into<'out>(
    recipients: &[Recipient<'_>],
    content_algorithm: Algorithm,
    iv: &[u8],
    detached_payload: &[u8],
    external_aad: &[u8],
    scratch: &mut [u8],
    out: &'out mut [u8],
    rng: Option<NonNull<raw::WC_RNG>>,
) -> Result<&'out [u8]> {
    let raw_recipients: Vec<_> = recipients.iter().map(Recipient::to_raw).collect();
    let mut out_len = 0;
    // SAFETY: recipient array and all slices are valid for this call.
    Error::from_code(unsafe {
        raw::wc_CoseEncrypt_Encrypt(
            raw_recipients.as_ptr(),
            raw_recipients.len(),
            content_algorithm.id(),
            ptr_or_null(iv),
            iv.len(),
            ptr::null(),
            0,
            ptr_or_null(detached_payload),
            detached_payload.len(),
            ptr_or_null(external_aad),
            external_aad.len(),
            scratch.as_mut_ptr(),
            scratch.len(),
            out.as_mut_ptr(),
            out.len(),
            &mut out_len,
            rng_ptr(rng),
        )
    })?;
    Ok(&out[..out_len])
}

/// Decrypt a multi-recipient COSE_Encrypt message.
pub fn decrypt_into(
    recipient: &Recipient<'_>,
    recipient_index: usize,
    input: &[u8],
    detached_ciphertext: Option<&[u8]>,
    external_aad: &[u8],
    scratch: &mut [u8],
    plaintext: &mut [u8],
) -> Result<DecryptOutput> {
    let raw_recipient = recipient.to_raw();
    let mut header = raw::WOLFCOSE_HDR::default();
    let mut plaintext_len = 0;
    let detached = detached_ciphertext.unwrap_or(&[]);
    // SAFETY: recipient and all buffers are valid for this call.
    Error::from_code(unsafe {
        raw::wc_CoseEncrypt_Decrypt(
            &raw_recipient,
            recipient_index,
            ptr_or_null(input),
            input.len(),
            opt_ptr(detached_ciphertext),
            detached.len(),
            ptr_or_null(external_aad),
            external_aad.len(),
            scratch.as_mut_ptr(),
            scratch.len(),
            &mut header,
            plaintext.as_mut_ptr(),
            plaintext.len(),
            &mut plaintext_len,
        )
    })?;
    Ok(DecryptOutput {
        header: Header::from_raw(&header),
        plaintext_len,
    })
}

/// Create a multi-recipient COSE_Mac message into a caller-provided buffer.
pub fn mac_into<'out>(
    recipients: &[Recipient<'_>],
    algorithm: Algorithm,
    payload: PayloadMode<'_>,
    external_aad: &[u8],
    scratch: &mut [u8],
    out: &'out mut [u8],
) -> Result<&'out [u8]> {
    let raw_recipients: Vec<_> = recipients.iter().map(Recipient::to_raw).collect();
    let (payload_ptr, payload_len, detached_ptr, detached_len) = payload.sign_parts();
    let mut out_len = 0;
    // SAFETY: recipient array and all slices are valid for this call.
    Error::from_code(unsafe {
        raw::wc_CoseMac_Create(
            raw_recipients.as_ptr(),
            raw_recipients.len(),
            algorithm.id(),
            payload_ptr,
            payload_len,
            detached_ptr,
            detached_len,
            ptr_or_null(external_aad),
            external_aad.len(),
            scratch.as_mut_ptr(),
            scratch.len(),
            out.as_mut_ptr(),
            out.len(),
            &mut out_len,
        )
    })?;
    Ok(&out[..out_len])
}

/// Create a multi-recipient COSE_Mac message into a new vector.
pub fn mac_to_vec(
    recipients: &[Recipient<'_>],
    algorithm: Algorithm,
    payload: PayloadMode<'_>,
    external_aad: &[u8],
    scratch: &mut [u8],
) -> Result<Vec<u8>> {
    with_growing_output(|out| {
        mac_into(recipients, algorithm, payload, external_aad, scratch, out)
            .map(|slice| slice.len())
    })
}

/// Verify a multi-recipient COSE_Mac message.
pub fn verify_mac<'inbuf>(
    recipient: &Recipient<'_>,
    recipient_index: usize,
    input: &'inbuf [u8],
    detached_payload: Option<&[u8]>,
    external_aad: &[u8],
    scratch: &mut [u8],
) -> Result<MacVerifyOutput<'inbuf>> {
    let raw_recipient = recipient.to_raw();
    let mut header = raw::WOLFCOSE_HDR::default();
    let mut payload = ptr::null();
    let mut payload_len = 0;
    let detached = detached_payload.unwrap_or(&[]);
    // SAFETY: recipient and all buffers are valid for this call.
    Error::from_code(unsafe {
        raw::wc_CoseMac_Verify(
            &raw_recipient,
            recipient_index,
            ptr_or_null(input),
            input.len(),
            opt_ptr(detached_payload),
            detached.len(),
            ptr_or_null(external_aad),
            external_aad.len(),
            scratch.as_mut_ptr(),
            scratch.len(),
            &mut header,
            &mut payload,
            &mut payload_len,
        )
    })?;
    Ok(VerifyOutput {
        header: Header::from_raw(&header),
        payload: borrowed_payload(payload, payload_len),
    })
}

fn ptr_or_null(data: &[u8]) -> *const u8 {
    if data.is_empty() {
        ptr::null()
    } else {
        data.as_ptr()
    }
}

fn ptr_len(data: &[u8]) -> (*const u8, usize) {
    (ptr_or_null(data), data.len())
}

fn opt_ptr(data: Option<&[u8]>) -> *const u8 {
    data.map(ptr_or_null).unwrap_or(ptr::null())
}

fn rng_ptr(rng: Option<NonNull<raw::WC_RNG>>) -> *mut raw::WC_RNG {
    rng.map(NonNull::as_ptr).unwrap_or(ptr::null_mut())
}

fn copy_opt(ptr: *const u8, len: usize) -> Vec<u8> {
    if ptr.is_null() || len == 0 {
        Vec::new()
    } else {
        // SAFETY: wolfCOSE reports `ptr` valid for `len` bytes.
        unsafe { slice::from_raw_parts(ptr, len).to_vec() }
    }
}

fn borrowed_payload<'a>(ptr: *const u8, len: usize) -> Option<&'a [u8]> {
    if ptr.is_null() {
        None
    } else {
        // SAFETY: wolfCOSE returns payload pointers into the input buffer for
        // attached payloads; caller input lifetime is used by wrapper APIs.
        Some(unsafe { slice::from_raw_parts(ptr, len) })
    }
}

fn with_growing_output(mut f: impl FnMut(&mut [u8]) -> Result<usize>) -> Result<Vec<u8>> {
    let mut size = 1024;
    loop {
        let mut out = vec![0; size];
        match f(&mut out) {
            Ok(len) => {
                out.truncate(len);
                return Ok(out);
            }
            Err(Error::BufferTooSmall) if size < 16 * 1024 * 1024 => size *= 2,
            Err(err) => return Err(err),
        }
    }
}

#[allow(dead_code)]
struct NotSendSync(PhantomData<*mut ()>);