cloudproof_cover_crypt 14.0.0

Cosmian Covercrypt Cloudproof 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
use std::{
    collections::HashMap,
    sync::{
        atomic::{AtomicI32, Ordering},
        RwLock,
    },
};

use cosmian_cover_crypt::{
    abe_policy::{AccessPolicy, Policy},
    Covercrypt, EncryptedHeader, MasterPublicKey, UserSecretKey,
};
use cosmian_crypto_core::{
    bytes_ser_de::{Deserializer, Serializable, Serializer},
    Aes256Gcm, FixedSizeCBytes, SymmetricKey,
};
use cosmian_ffi_utils::{
    ffi_bail, ffi_read_bytes, ffi_read_string, ffi_unwrap, ffi_write_bytes, ErrorCode,
};
use lazy_static::lazy_static;

// -------------------------------
//         Encryption
// -------------------------------

// A static cache of the Encryption Caches
lazy_static! {
    static ref ENCRYPTION_CACHE_MAP: RwLock<HashMap<i32, EncryptionCache>> =
        RwLock::new(HashMap::new());
    static ref NEXT_ENCRYPTION_CACHE_ID: std::sync::atomic::AtomicI32 = AtomicI32::new(0);
}

/// An Encryption Cache that will be used to cache Rust side
/// the Public Key and the Policy when doing multiple serial encryptions
pub struct EncryptionCache {
    policy: Policy,
    mpk: MasterPublicKey,
}

#[no_mangle]
/// Creates a cache containing the Public Key and Policy. This cache can be
/// reused when encrypting messages which avoids passing these objects to Rust
/// in each call.
///
/// WARNING: [`h_destroy_encrypt_cache()`](h_destroy_encryption_cache)
/// should be called to reclaim the cache memory.
///
/// # Safety
pub unsafe extern "C" fn h_create_encryption_cache(
    cache_handle: *mut i32,
    policy_ptr: *const i8,
    policy_len: i32,
    mpk_ptr: *const i8,
    mpk_len: i32,
) -> i32 {
    let policy = ffi_read_bytes!("policy", policy_ptr, policy_len);
    let policy = ffi_unwrap!(
        Policy::try_from(policy),
        "error deserializing policy",
        ErrorCode::Serialization
    );
    let mpk = ffi_read_bytes!("public key", mpk_ptr, mpk_len);
    let mpk = ffi_unwrap!(
        MasterPublicKey::deserialize(mpk),
        "error deserializing public key",
        ErrorCode::Serialization
    );

    let cache = EncryptionCache { policy, mpk };
    let id = NEXT_ENCRYPTION_CACHE_ID.fetch_add(1, Ordering::Acquire);
    let mut map = ENCRYPTION_CACHE_MAP
        .write()
        .expect("A write mutex on encryption cache failed");
    map.insert(id, cache);
    *cache_handle = id;

    0
}

#[no_mangle]
/// Reclaims the memory of the cache.
///
/// Cf [`h_create_encrypt_cache()`](h_create_encryption_cache).
///
/// # Safety
pub unsafe extern "C" fn h_destroy_encryption_cache(cache_handle: i32) -> i32 {
    let mut map = ENCRYPTION_CACHE_MAP
        .write()
        .expect("A write mutex on encryption cache failed");
    map.remove(&cache_handle);
    0
}

#[no_mangle]
/// Encrypts a header using an encryption cache.
///
/// # Safety
pub unsafe extern "C" fn h_encrypt_header_using_cache(
    symmetric_key_ptr: *mut i8,
    symmetric_key_len: *mut i32,
    header_bytes_ptr: *mut i8,
    header_bytes_len: *mut i32,
    cache_handle: i32,
    encryption_policy_ptr: *const i8,
    header_metadata_ptr: *const i8,
    header_metadata_len: i32,
    authentication_data_ptr: *const i8,
    authentication_data_len: i32,
) -> i32 {
    let encryption_policy_bytes = ffi_read_string!("encryption policy", encryption_policy_ptr);
    let encryption_policy = ffi_unwrap!(
        AccessPolicy::from_boolean_expression(&encryption_policy_bytes),
        "error parsing encryption policy",
        ErrorCode::CovercryptPolicy
    );

    let header_metadata = if header_metadata_ptr.is_null() || header_metadata_len == 0 {
        None
    } else {
        Some(ffi_read_bytes!(
            "header metadata",
            header_metadata_ptr,
            header_metadata_len
        ))
    };

    let authentication_data = if authentication_data_ptr.is_null() || authentication_data_len == 0 {
        None
    } else {
        Some(ffi_read_bytes!(
            "authentication data",
            authentication_data_ptr,
            authentication_data_len
        ))
    };

    let map = ENCRYPTION_CACHE_MAP
        .read()
        .expect("a read mutex on the encryption cache failed");
    let cache = if let Some(cache) = map.get(&cache_handle) {
        cache
    } else {
        ffi_bail!(format!(
            "Hybrid Cipher: no encryption cache with handle: {cache_handle}"
        ));
    };

    let (symmetric_key, encrypted_header) = ffi_unwrap!(
        EncryptedHeader::generate(
            &Covercrypt::default(),
            &cache.policy,
            &cache.mpk,
            &encryption_policy,
            header_metadata,
            authentication_data,
        ),
        "error encrypting CoverCrypt header",
        ErrorCode::Covercrypt
    );

    let encrypted_header_bytes = ffi_unwrap!(
        encrypted_header.serialize(),
        "error serializing encrypted CoverCrypt header",
        ErrorCode::Serialization
    );

    ffi_write_bytes!(
        "symmetric key",
        &symmetric_key,
        symmetric_key_ptr,
        symmetric_key_len,
        "encrypted header",
        &encrypted_header_bytes,
        header_bytes_ptr,
        header_bytes_len
    );
}

#[no_mangle]
/// Encrypts a header without using an encryption cache.
/// It is slower but does not require destroying any cache when done.
///
/// The symmetric key and header bytes are returned in the first OUT parameters
/// # Safety
pub unsafe extern "C" fn h_encrypt_header(
    symmetric_key_ptr: *mut i8,
    symmetric_key_len: *mut i32,
    header_bytes_ptr: *mut i8,
    header_bytes_len: *mut i32,
    policy_ptr: *const i8,
    policy_len: i32,
    mpk_ptr: *const i8,
    mpk_len: i32,
    encryption_policy_ptr: *const i8,
    header_metadata_ptr: *const i8,
    header_metadata_len: i32,
    authentication_data_ptr: *const i8,
    authentication_data_len: i32,
) -> i32 {
    let policy = ffi_read_bytes!("policy", policy_ptr, policy_len);
    let policy = ffi_unwrap!(
        Policy::try_from(policy),
        "error deserializing policy",
        ErrorCode::Serialization
    );
    let mpk = ffi_read_bytes!("public key", mpk_ptr, mpk_len);
    let mpk = ffi_unwrap!(
        MasterPublicKey::deserialize(mpk),
        "error deserializing public key",
        ErrorCode::Serialization
    );
    let encryption_policy_string = ffi_read_string!("encryption policy", encryption_policy_ptr);
    let encryption_policy = ffi_unwrap!(
        AccessPolicy::from_boolean_expression(&encryption_policy_string),
        "error parsing encryption policy",
        ErrorCode::CovercryptPolicy
    );
    let header_metadata = if header_metadata_ptr.is_null() || header_metadata_len == 0 {
        None
    } else {
        Some(ffi_read_bytes!(
            "header metadata",
            header_metadata_ptr,
            header_metadata_len
        ))
    };

    let authentication_data = if authentication_data_ptr.is_null() || authentication_data_len == 0 {
        None
    } else {
        Some(ffi_read_bytes!(
            "authentication data",
            authentication_data_ptr,
            authentication_data_len
        ))
    };

    let (symmetric_key, encrypted_header) = ffi_unwrap!(
        EncryptedHeader::generate(
            &Covercrypt::default(),
            &policy,
            &mpk,
            &encryption_policy,
            header_metadata,
            authentication_data
        ),
        "error encrypting CoverCrypt header",
        ErrorCode::Encryption
    );

    let encrypted_header_bytes = ffi_unwrap!(
        encrypted_header.serialize(),
        "error serializing encrypted CoverCrypt header",
        ErrorCode::Serialization
    );

    ffi_write_bytes!(
        "symmetric key",
        &symmetric_key,
        symmetric_key_ptr,
        symmetric_key_len,
        "encrypted header",
        &encrypted_header_bytes,
        header_bytes_ptr,
        header_bytes_len
    );
}

// -------------------------------
//         Decryption
// -------------------------------

// A cache of the decryption caches
lazy_static! {
    static ref DECRYPTION_CACHE_MAP: RwLock<HashMap<i32, DecryptionCache>> =
        RwLock::new(HashMap::new());
    static ref NEXT_DECRYPTION_CACHE_ID: std::sync::atomic::AtomicI32 = AtomicI32::new(0);
}

/// Cache used to store the user secret key on the Rust side.
pub struct DecryptionCache {
    usk: UserSecretKey,
}

#[no_mangle]
/// Creates a cache containing the user secret key. This cache can be reused
/// when decrypting messages which avoids passing this key to Rust in each call.
///
/// Cf [`h_decrypt_header_using_cache()`](h_decrypt_header_using_cache).
///
/// WARNING: [`h_destroy_decryption_cache()`](h_destroy_decryption_cache)
/// should be called to reclaim the cache memory.
///
/// # Safety
pub unsafe extern "C" fn h_create_decryption_cache(
    cache_handle: *mut i32,
    usk_ptr: *const i8,
    usk_len: i32,
) -> i32 {
    let usk_bytes = ffi_read_bytes!("user secret key", usk_ptr, usk_len);
    let usk = ffi_unwrap!(
        UserSecretKey::deserialize(usk_bytes),
        "error deserializing user secret key",
        ErrorCode::Serialization
    );

    let cache = DecryptionCache { usk };
    let id = NEXT_DECRYPTION_CACHE_ID.fetch_add(1, Ordering::Acquire);
    let mut map = DECRYPTION_CACHE_MAP
        .write()
        .expect("A write mutex on decryption cache failed");
    map.insert(id, cache);
    *cache_handle = id;

    0
}

#[no_mangle]
/// Reclaims decryption cache memory.
///
/// # Safety
pub unsafe extern "C" fn h_destroy_decryption_cache(cache_handle: i32) -> i32 {
    let mut map = DECRYPTION_CACHE_MAP
        .write()
        .expect("A write mutex on decryption cache failed");
    map.remove(&cache_handle);
    0
}

#[no_mangle]
/// Decrypts an encrypted header using a cache. Returns the symmetric key and
/// header metadata if any.
///
/// No header metadata is returned if `header_metadata_ptr` is `NULL`.
///
/// # Safety
pub unsafe extern "C" fn h_decrypt_header_using_cache(
    symmetric_key_ptr: *mut i8,
    symmetric_key_len: *mut i32,
    header_metadata_ptr: *mut i8,
    header_metadata_len: *mut i32,
    encrypted_header_ptr: *const i8,
    encrypted_header_len: i32,
    authentication_data_ptr: *const i8,
    authentication_data_len: i32,
    cache_handle: i32,
) -> i32 {
    let encrypted_header_bytes = ffi_read_bytes!(
        "encrypted header",
        encrypted_header_ptr,
        encrypted_header_len
    );
    let encrypted_header = ffi_unwrap!(
        EncryptedHeader::deserialize(encrypted_header_bytes),
        "error deserializing encrypted header",
        ErrorCode::Serialization
    );
    let authentication_data = if authentication_data_ptr.is_null() || authentication_data_len == 0 {
        None
    } else {
        Some(ffi_read_bytes!(
            "authentication data",
            authentication_data_ptr,
            authentication_data_len
        ))
    };

    let map = DECRYPTION_CACHE_MAP
        .read()
        .expect("a read mutex on the decryption cache failed");
    let cache = if let Some(cache) = map.get(&cache_handle) {
        cache
    } else {
        ffi_bail!(format!(
            "Hybrid Cipher: no decryption cache with handle: {cache_handle}",
        ));
    };

    let header = ffi_unwrap!(
        encrypted_header.decrypt(&Covercrypt::default(), &cache.usk, authentication_data),
        "error decrypting CoverCrypt header",
        ErrorCode::Decryption
    );

    if header_metadata_ptr.is_null() {
        *header_metadata_len = 0;
        ffi_write_bytes!(
            "symmetric key",
            &header.symmetric_key,
            symmetric_key_ptr,
            symmetric_key_len
        );
    } else {
        let metadata = header.metadata.unwrap_or_default();
        ffi_write_bytes!(
            "symmetric key",
            &header.symmetric_key,
            symmetric_key_ptr,
            symmetric_key_len,
            "header metadata",
            &metadata,
            header_metadata_ptr,
            header_metadata_len
        );
    }
}

#[no_mangle]
/// Decrypts an encrypted header, returning the symmetric key and header
/// metadata if any.
///
/// No header metadata is returned if `header_metadata_ptr` is `NULL`.
///
/// # Safety
pub unsafe extern "C" fn h_decrypt_header(
    symmetric_key_ptr: *mut i8,
    symmetric_key_len: *mut i32,
    header_metadata_ptr: *mut i8,
    header_metadata_len: *mut i32,
    encrypted_header_ptr: *const i8,
    encrypted_header_len: i32,
    authentication_data_ptr: *const i8,
    authentication_data_len: i32,
    usk_ptr: *const i8,
    usk_len: i32,
) -> i32 {
    let usk_bytes = ffi_read_bytes!("user secret key", usk_ptr, usk_len);
    let usk = ffi_unwrap!(
        UserSecretKey::deserialize(usk_bytes),
        "error deserializing user secret key",
        ErrorCode::Serialization
    );
    let encrypted_header_bytes = ffi_read_bytes!(
        "encrypted header",
        encrypted_header_ptr,
        encrypted_header_len
    );
    let encrypted_header = ffi_unwrap!(
        EncryptedHeader::deserialize(encrypted_header_bytes),
        "encrypted header",
        ErrorCode::Serialization
    );

    let authentication_data = if authentication_data_ptr.is_null() || authentication_data_len == 0 {
        None
    } else {
        Some(ffi_read_bytes!(
            "authentication data",
            authentication_data_ptr,
            authentication_data_len
        ))
    };

    let decrypted_header = ffi_unwrap!(
        encrypted_header.decrypt(&Covercrypt::default(), &usk, authentication_data),
        "error decrypting CoverCrypt header",
        ErrorCode::Decryption
    );

    if header_metadata_ptr.is_null() {
        *header_metadata_len = 0;
        ffi_write_bytes!(
            "symmetric key",
            &decrypted_header.symmetric_key,
            symmetric_key_ptr,
            symmetric_key_len
        );
    } else {
        let metadata = decrypted_header.metadata.unwrap_or_default();
        ffi_write_bytes!(
            "symmetric key",
            &decrypted_header.symmetric_key,
            symmetric_key_ptr,
            symmetric_key_len,
            "header metadata",
            &metadata,
            header_metadata_ptr,
            header_metadata_len
        );
    }
}

#[no_mangle]
///
/// # Safety
pub unsafe extern "C" fn h_symmetric_encryption_overhead() -> i32 {
    (Aes256Gcm::NONCE_LENGTH + Aes256Gcm::MAC_LENGTH) as i32
}

#[no_mangle]
///
/// # Safety
pub unsafe extern "C" fn h_dem_encrypt(
    ciphertext_ptr: *mut i8,
    ciphertext_len: *mut i32,
    symmetric_key_ptr: *const i8,
    symmetric_key_len: i32,
    authentication_data_ptr: *const i8,
    authentication_data_len: i32,
    plaintext_ptr: *const i8,
    plaintext_len: i32,
) -> i32 {
    let plaintext = ffi_read_bytes!("plaintext", plaintext_ptr, plaintext_len);
    let symmetric_key_bytes =
        ffi_read_bytes!("symmetric key", symmetric_key_ptr, symmetric_key_len);
    let symmetric_key_fixed_length = ffi_unwrap!(
        symmetric_key_bytes.try_into(),
        "error converting to fixed length",
        ErrorCode::Serialization
    );
    let symmetric_key = ffi_unwrap!(
        SymmetricKey::try_from_bytes(symmetric_key_fixed_length),
        "error parsing symmetric key",
        ErrorCode::Serialization
    );
    let authentication_data = if authentication_data_ptr.is_null() || authentication_data_len == 0 {
        None
    } else {
        Some(ffi_read_bytes!(
            "authentication data",
            authentication_data_ptr,
            authentication_data_len
        ))
    };

    let ciphertext = ffi_unwrap!(
        Covercrypt::default().encrypt(&symmetric_key, plaintext, authentication_data),
        "error encrypting plaintext",
        ErrorCode::Encryption
    );

    ffi_write_bytes!("ciphertext", &ciphertext, ciphertext_ptr, ciphertext_len);
}

#[no_mangle]
///
/// # Safety
pub unsafe extern "C" fn h_dem_decrypt(
    plaintext_ptr: *mut i8,
    plaintext_len: *mut i32,
    symmetric_key_ptr: *const i8,
    symmetric_key_len: i32,
    authentication_data_ptr: *const i8,
    authentication_data_len: i32,
    ciphertext_ptr: *const i8,
    ciphertext_len: i32,
) -> i32 {
    let ciphertext = ffi_read_bytes!("ciphertext", ciphertext_ptr, ciphertext_len);
    let symmetric_key_bytes =
        ffi_read_bytes!("symmetric key", symmetric_key_ptr, symmetric_key_len);
    let symmetric_key_fixed_length = ffi_unwrap!(
        symmetric_key_bytes.try_into(),
        "error converting to fixed length",
        ErrorCode::Serialization
    );
    let symmetric_key = ffi_unwrap!(
        SymmetricKey::try_from_bytes(symmetric_key_fixed_length),
        "error parsing symmetric key",
        ErrorCode::Serialization
    );
    let authentication_data = if authentication_data_ptr.is_null() || authentication_data_len == 0 {
        None
    } else {
        Some(ffi_read_bytes!(
            "authentication data",
            authentication_data_ptr,
            authentication_data_len
        ))
    };

    let plaintext = ffi_unwrap!(
        Covercrypt::default().decrypt(&symmetric_key, ciphertext, authentication_data),
        "error decrypting symmetric ciphertext",
        ErrorCode::Decryption
    );

    ffi_write_bytes!("plaintext", &plaintext, plaintext_ptr, plaintext_len);
}

#[no_mangle]
/// Hybrid encrypt some content
///
/// # Safety
pub unsafe extern "C" fn h_hybrid_encrypt(
    ciphertext_ptr: *mut i8,
    ciphertext_len: *mut i32,
    policy_ptr: *const i8,
    policy_len: i32,
    mpk_ptr: *const i8,
    mpk_len: i32,
    encryption_policy_ptr: *const i8,
    plaintext_ptr: *const i8,
    plaintext_len: i32,
    header_metadata_ptr: *const i8,
    header_metadata_len: i32,
    authentication_data_ptr: *const i8,
    authentication_data_len: i32,
) -> i32 {
    let policy_bytes = ffi_read_bytes!("policy", policy_ptr, policy_len);
    let policy = ffi_unwrap!(
        Policy::parse_and_convert(policy_bytes),
        "error deserializing policy",
        ErrorCode::Serialization
    );
    let encryption_policy_string = ffi_read_string!("encryption policy", encryption_policy_ptr);
    let encryption_policy = ffi_unwrap!(
        AccessPolicy::from_boolean_expression(&encryption_policy_string),
        "error parsing encryption policy",
        ErrorCode::Serialization
    );
    let plaintext = ffi_read_bytes!("plaintext", plaintext_ptr, plaintext_len);
    let mpk_bytes = ffi_read_bytes!("public key", mpk_ptr, mpk_len);
    let mpk = ffi_unwrap!(
        MasterPublicKey::deserialize(mpk_bytes),
        "error deserializing public key",
        ErrorCode::Serialization
    );
    let header_metadata = if header_metadata_ptr.is_null() || header_metadata_len == 0 {
        None
    } else {
        Some(ffi_read_bytes!(
            "header metadata",
            header_metadata_ptr,
            header_metadata_len
        ))
    };

    let authentication_data = if authentication_data_ptr.is_null() || authentication_data_len == 0 {
        None
    } else {
        Some(ffi_read_bytes!(
            "authentication data",
            authentication_data_ptr,
            authentication_data_len
        ))
    };

    let (symmetric_key, encrypted_header) = ffi_unwrap!(
        EncryptedHeader::generate(
            &Covercrypt::default(),
            &policy,
            &mpk,
            &encryption_policy,
            header_metadata,
            authentication_data
        ),
        "error encrypting CoverCrypt header",
        ErrorCode::Encryption
    );

    let ciphertext = ffi_unwrap!(
        Covercrypt::default().encrypt(&symmetric_key, plaintext, authentication_data,),
        "error encrypting plaintext",
        ErrorCode::Encryption
    );

    let mut ser = Serializer::with_capacity(encrypted_header.length() + ciphertext.len());
    ffi_unwrap!(
        ser.write(&encrypted_header),
        "error serializing encrypted CoverCrypt header",
        ErrorCode::Serialization
    );
    ffi_unwrap!(
        ser.write_array(&ciphertext),
        "error deserializing symmetric ciphertext",
        ErrorCode::Serialization
    );
    let bytes = ser.finalize();

    ffi_write_bytes!("ciphertext", &bytes, ciphertext_ptr, ciphertext_len);
}

#[no_mangle]
/// Hybrid decrypt some content.
///
/// No header metadata is returned if `header_metadata_ptr` is `NULL`.
///
/// # Safety
pub unsafe extern "C" fn h_hybrid_decrypt(
    plaintext_ptr: *mut i8,
    plaintext_len: *mut i32,
    header_metadata_ptr: *mut i8,
    header_metadata_len: *mut i32,
    ciphertext_ptr: *const i8,
    ciphertext_len: i32,
    authentication_data_ptr: *const i8,
    authentication_data_len: i32,
    usk_ptr: *const i8,
    usk_len: i32,
) -> i32 {
    let usk_bytes = ffi_read_bytes!("user secret key", usk_ptr, usk_len);
    let usk = ffi_unwrap!(
        UserSecretKey::deserialize(usk_bytes),
        "error deserializing user secret key",
        ErrorCode::Serialization
    );
    let authentication_data = if authentication_data_ptr.is_null() || authentication_data_len == 0 {
        None
    } else {
        Some(ffi_read_bytes!(
            "authentication data",
            authentication_data_ptr,
            authentication_data_len
        ))
    };

    let ciphertext = ffi_read_bytes!("ciphertext", ciphertext_ptr, ciphertext_len);
    let mut de = Deserializer::new(ciphertext);
    let encrypted_header = ffi_unwrap!(
        // this will read the exact header size
        de.read::<EncryptedHeader>(),
        "error deserializing encrypted CoverCrypt header",
        ErrorCode::Serialization
    );
    // the rest is the symmetric ciphertext
    let encrypted_content = de.finalize();

    // Decrypt header
    let decrypted_header = ffi_unwrap!(
        encrypted_header.decrypt(&Covercrypt::default(), &usk, authentication_data),
        "error decrypting CoverCrypt header",
        ErrorCode::Decryption
    );

    let plaintext = ffi_unwrap!(
        Covercrypt::default().decrypt(
            &decrypted_header.symmetric_key,
            &encrypted_content,
            authentication_data,
        ),
        "error decrypting symmetric ciphertext",
        ErrorCode::Decryption
    );

    if header_metadata_ptr.is_null() {
        *header_metadata_len = 0;
        ffi_write_bytes!("plaintext", &plaintext, plaintext_ptr, plaintext_len);
    } else {
        let metadata = decrypted_header.metadata.unwrap_or_default();
        ffi_write_bytes!(
            "plaintext",
            &plaintext,
            plaintext_ptr,
            plaintext_len,
            "header metadata",
            &metadata,
            header_metadata_ptr,
            header_metadata_len
        );
    }
}