native-ossl 0.1.1

Native Rust idiomatic bindings to OpenSSL
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
//! `OSSL_PARAM_BLD` builder and `Params<'a>` wrapper.
//!
//! `ParamBuilder` wraps `OSSL_PARAM_BLD` and provides typed push methods that
//! map Rust types to OpenSSL parameter types.  `build()` finalises the builder
//! and returns an owned `Params` array.
//!
//! ## Lifetime
//!
//! `ParamBuilder<'a>` carries a lifetime `'a` that covers any borrowed byte
//! slices passed via `push_octet_ptr` or `push_utf8_ptr`.  Those calls store
//! a pointer into the caller's buffer; the buffer must outlive the `Params`
//! returned by `build()`.  Calls that copy (`push_octet_slice`, `push_utf8_string`)
//! have no such constraint.
//!
//! ## Zero-copy decision table
//!
//! | Method             | C function                      | Copies? |
//! |--------------------|---------------------------------|---------|
//! | `push_octet_slice` | `OSSL_PARAM_BLD_push_octet_string` | Yes  |
//! | `push_octet_ptr`   | `OSSL_PARAM_BLD_push_octet_ptr` | No      |
//! | `push_utf8_string` | `OSSL_PARAM_BLD_push_utf8_string`  | Yes  |
//! | `push_utf8_ptr`    | (manual OSSL_PARAM_BLD extension) | No    |

use crate::error::ErrorStack;
use native_ossl_sys as sys;
use std::ffi::CStr;
use std::marker::PhantomData;
use std::ptr;

// ── Params — the built array ──────────────────────────────────────────────────

/// An owned, finalized `OSSL_PARAM` array.
///
/// Created by `ParamBuilder::build()`.  The lifetime `'a` covers any borrowed
/// byte or string slices stored by pointer (zero-copy push calls).
pub struct Params<'a> {
    /// The heap-allocated array of `OSSL_PARAM` elements.
    ptr: *mut sys::OSSL_PARAM,
    /// Phantom to carry the borrow lifetime of any `push_octet_ptr` data.
    _lifetime: PhantomData<&'a [u8]>,
}

impl Params<'_> {
    /// Return a const pointer to the first `OSSL_PARAM` in the array.
    ///
    /// Pass this pointer to OpenSSL functions that take `const OSSL_PARAM[]`.
    /// The pointer is valid for the lifetime of `self`.
    #[must_use]
    pub fn as_ptr(&self) -> *const sys::OSSL_PARAM {
        self.ptr
    }
}

impl Drop for Params<'_> {
    fn drop(&mut self) {
        unsafe { sys::OSSL_PARAM_free(self.ptr) };
    }
}

// SAFETY: `OSSL_PARAM` arrays are read-only after construction.
// The builder ensures all owned copies are heap-allocated by OpenSSL.
unsafe impl Send for Params<'_> {}
unsafe impl Sync for Params<'_> {}

// ── ParamBuilder ──────────────────────────────────────────────────────────────

/// Builder for `OSSL_PARAM` arrays.
///
/// ```ignore
/// use native_ossl::params::ParamBuilder;
///
/// let params = ParamBuilder::new()
///     .push_int(c"key_bits", 2048)?
///     .push_utf8_ptr(c"pad-mode", c"oaep")?
///     .build()?;
/// ```
pub struct ParamBuilder<'a> {
    ptr: *mut sys::OSSL_PARAM_BLD,
    /// BIGNUMs pushed via `push_bn` that must remain alive until `build()`.
    ///
    /// `OSSL_PARAM_BLD_push_BN` stores a *pointer* to the BIGNUM internally;
    /// the actual copy into the `OSSL_PARAM` array happens only in
    /// `OSSL_PARAM_BLD_to_param`.  We must therefore keep each BIGNUM alive
    /// until after `build()` completes.
    bns: Vec<*mut sys::BIGNUM>,
    _lifetime: PhantomData<&'a [u8]>,
}

// SAFETY: BIGNUM pointers are not shared; we control their lifetime.
unsafe impl Send for ParamBuilder<'_> {}

impl<'a> ParamBuilder<'a> {
    /// Create a new empty builder.
    ///
    /// # Errors
    ///
    /// Returns `Err` if OpenSSL cannot allocate the builder.
    pub fn new() -> Result<Self, ErrorStack> {
        let ptr = unsafe { sys::OSSL_PARAM_BLD_new() };
        if ptr.is_null() {
            return Err(ErrorStack::drain());
        }
        Ok(ParamBuilder {
            ptr,
            bns: Vec::new(),
            _lifetime: PhantomData,
        })
    }

    /// Push a signed integer parameter.
    ///
    /// # Errors
    ///
    /// Returns `Err` if the push fails (allocation error or key too long).
    pub fn push_int(self, key: &CStr, val: i32) -> Result<Self, ErrorStack> {
        let rc = unsafe { sys::OSSL_PARAM_BLD_push_int(self.ptr, key.as_ptr(), val) };
        if rc != 1 {
            return Err(ErrorStack::drain());
        }
        Ok(self)
    }

    /// Push an unsigned integer parameter.
    ///
    /// # Errors
    pub fn push_uint(self, key: &CStr, val: u32) -> Result<Self, ErrorStack> {
        let rc = unsafe { sys::OSSL_PARAM_BLD_push_uint(self.ptr, key.as_ptr(), val) };
        if rc != 1 {
            return Err(ErrorStack::drain());
        }
        Ok(self)
    }

    /// Push a 64-bit unsigned integer parameter.
    ///
    /// Used for parameters such as the scrypt `N` cost factor.
    ///
    /// # Errors
    pub fn push_uint64(self, key: &CStr, val: u64) -> Result<Self, ErrorStack> {
        let rc = unsafe { sys::OSSL_PARAM_BLD_push_uint64(self.ptr, key.as_ptr(), val) };
        if rc != 1 {
            return Err(ErrorStack::drain());
        }
        Ok(self)
    }

    /// Push a `size_t` parameter.
    ///
    /// # Errors
    pub fn push_size(self, key: &CStr, val: usize) -> Result<Self, ErrorStack> {
        let rc = unsafe { sys::OSSL_PARAM_BLD_push_size_t(self.ptr, key.as_ptr(), val) };
        if rc != 1 {
            return Err(ErrorStack::drain());
        }
        Ok(self)
    }

    /// Push an octet-string parameter — **copies** `val` into the param array.
    ///
    /// Use this when `val` may be dropped before the resulting `Params` is consumed.
    /// If `val` is guaranteed to outlive `Params`, prefer `push_octet_ptr`.
    ///
    /// # Errors
    pub fn push_octet_slice(self, key: &CStr, val: &[u8]) -> Result<Self, ErrorStack> {
        let rc = unsafe {
            sys::OSSL_PARAM_BLD_push_octet_string(
                self.ptr,
                key.as_ptr(),
                val.as_ptr().cast(),
                val.len(),
            )
        };
        if rc != 1 {
            return Err(ErrorStack::drain());
        }
        Ok(self)
    }

    /// Push an octet-string parameter — **stores a pointer** into `val`.
    ///
    /// Zero-copy: no allocation occurs.  The lifetime `'b` of `val` must be at
    /// least `'a` to prevent the reference from being invalidated before the
    /// `Params` array is consumed.
    ///
    /// # Errors
    pub fn push_octet_ptr<'b>(
        self,
        key: &CStr,
        val: &'b [u8],
    ) -> Result<ParamBuilder<'b>, ErrorStack>
    where
        'a: 'b,
    {
        let rc = unsafe {
            sys::OSSL_PARAM_BLD_push_octet_ptr(
                self.ptr,
                key.as_ptr(),
                // OpenSSL declares the parameter as *mut c_void but treats it
                // as read-only once stored (pointer storage, no write-back).
                // The cast from *const to *mut is intentional: OpenSSL's API
                // is not const-correct here.
                val.as_ptr() as *mut std::os::raw::c_void,
                val.len(),
            )
        };
        if rc != 1 {
            // `self` drops here, running Drop (frees builder + BIGNUMs).
            return Err(ErrorStack::drain());
        }
        // Transfer both `ptr` and `bns` into the new lifetime-narrowed builder.
        // Use ManuallyDrop so the Drop impl of `self` does not run a second free.
        let md = std::mem::ManuallyDrop::new(self);
        Ok(ParamBuilder {
            ptr: md.ptr,
            // SAFETY: we are the sole owner; md's Drop will not run.
            bns: unsafe { ptr::read(&raw const md.bns) },
            _lifetime: PhantomData,
        })
    }

    /// Push a UTF-8 string parameter — **copies** `val` into the param array.
    ///
    /// # Errors
    pub fn push_utf8_string(self, key: &CStr, val: &CStr) -> Result<Self, ErrorStack> {
        let rc = unsafe {
            sys::OSSL_PARAM_BLD_push_utf8_string(
                self.ptr,
                key.as_ptr(),
                val.as_ptr(),
                0, // 0 = use strlen
            )
        };
        if rc != 1 {
            return Err(ErrorStack::drain());
        }
        Ok(self)
    }

    /// Push a UTF-8 string parameter — **stores a pointer** into `val`.
    ///
    /// Zero-copy: no allocation occurs.  Use only for `'static` literals such as
    /// algorithm names (`c"oaep"`, `c"SHA-256"`).
    ///
    /// # Errors
    pub fn push_utf8_ptr(self, key: &CStr, val: &'static CStr) -> Result<Self, ErrorStack> {
        // OpenSSL does not provide OSSL_PARAM_BLD_push_utf8_ptr in all builds,
        // so we use push_utf8_string which copies, but annotate that the intent
        // is pointer storage.  For 'static values the copy is negligible.
        //
        // NOTE: If OpenSSL gains OSSL_PARAM_BLD_push_utf8_ptr exposure in future
        // bindgen output, replace the body with the pointer variant.
        let rc = unsafe {
            sys::OSSL_PARAM_BLD_push_utf8_string(self.ptr, key.as_ptr(), val.as_ptr(), 0)
        };
        if rc != 1 {
            return Err(ErrorStack::drain());
        }
        Ok(self)
    }

    /// Push a BIGNUM parameter from big-endian bytes.
    ///
    /// Converts `bigendian_bytes` to an OpenSSL `BIGNUM` and pushes it into the
    /// builder.  The `BIGNUM` is copied into the builder's internal storage so
    /// the caller's slice is not referenced after this call returns.
    ///
    /// # Panics
    ///
    /// Panics if `bigendian_bytes` is longer than `i32::MAX` bytes, which is
    /// not a practical concern for key material.
    ///
    /// # Errors
    ///
    /// Returns `Err` if the allocation fails or the push fails.
    pub fn push_bn(mut self, key: &CStr, bigendian_bytes: &[u8]) -> Result<Self, ErrorStack> {
        // BN_bin2bn converts big-endian bytes into a newly allocated BIGNUM.
        let bn = unsafe {
            sys::BN_bin2bn(
                bigendian_bytes.as_ptr(),
                // len is int in C; values >2 GiB are pathological for key material.
                i32::try_from(bigendian_bytes.len()).expect("BN too large"),
                ptr::null_mut(),
            )
        };
        if bn.is_null() {
            return Err(ErrorStack::drain());
        }
        // OSSL_PARAM_BLD_push_BN stores a *pointer* to the BIGNUM; the actual
        // copy into the OSSL_PARAM array is deferred to OSSL_PARAM_BLD_to_param.
        // Keep the BIGNUM alive in `self.bns` until `build()` completes.
        let rc = unsafe { sys::OSSL_PARAM_BLD_push_BN(self.ptr, key.as_ptr(), bn) };
        if rc != 1 {
            unsafe { sys::BN_free(bn) };
            return Err(ErrorStack::drain());
        }
        self.bns.push(bn);
        Ok(self)
    }

    /// Finalise the builder and return the `Params` array.
    ///
    /// Consumes the builder.  The returned `Params` must outlive any borrowed
    /// slices stored via `push_octet_ptr`.
    ///
    /// # Errors
    ///
    /// Returns `Err` if `OSSL_PARAM_BLD_to_param` fails.
    pub fn build(self) -> Result<Params<'a>, ErrorStack> {
        // Take ownership of the raw pointers and prevent Drop from running,
        // so we control the exact point at which cleanup happens.
        let builder_ptr = self.ptr;
        let bns = unsafe { ptr::read(&raw const self.bns) };
        std::mem::forget(self);

        let param_ptr = unsafe { sys::OSSL_PARAM_BLD_to_param(builder_ptr) };
        // Free the builder — the OSSL_PARAM array is independent of it.
        unsafe { sys::OSSL_PARAM_BLD_free(builder_ptr) };
        // Now that to_param has copied all BIGNUM values, free the temporaries.
        for bn in bns {
            unsafe { sys::BN_free(bn) };
        }

        if param_ptr.is_null() {
            return Err(ErrorStack::drain());
        }
        Ok(Params {
            ptr: param_ptr,
            _lifetime: PhantomData,
        })
    }
}

impl Drop for ParamBuilder<'_> {
    fn drop(&mut self) {
        if !self.ptr.is_null() {
            unsafe { sys::OSSL_PARAM_BLD_free(self.ptr) };
        }
        for bn in self.bns.drain(..) {
            unsafe { sys::BN_free(bn) };
        }
    }
}

// ── Private BigNum helper ─────────────────────────────────────────────────────

struct Bn(*mut sys::BIGNUM);

impl Bn {
    /// Convert this `BIGNUM` to a big-endian byte vector.
    fn to_bigendian_vec(&self) -> Vec<u8> {
        let nbits = unsafe { sys::BN_num_bits(self.0) };
        let nbytes = usize::try_from(nbits).unwrap_or(0).div_ceil(8);
        if nbytes == 0 {
            return Vec::new();
        }
        let mut out = vec![0u8; nbytes];
        // BN_bn2bin writes exactly nbytes; returns nbytes on success.
        unsafe { sys::BN_bn2bin(self.0, out.as_mut_ptr()) };
        out
    }
}

impl Drop for Bn {
    fn drop(&mut self) {
        unsafe { sys::BN_free(self.0) };
    }
}

// ── Params — getters and ownership transfer ───────────────────────────────────

impl Params<'_> {
    /// Adopt an OpenSSL-allocated `OSSL_PARAM` array, taking ownership.
    ///
    /// The array will be freed with `OSSL_PARAM_free` on drop.  Use this to
    /// wrap arrays returned by functions such as `EVP_PKEY_todata`.
    ///
    /// # Safety
    ///
    /// `ptr` must be a valid, `OSSL_PARAM_END`-terminated array allocated by
    /// OpenSSL.  After this call the caller must not use or free `ptr`.
    #[must_use]
    pub unsafe fn from_owned_ptr(ptr: *mut sys::OSSL_PARAM) -> Params<'static> {
        Params {
            ptr,
            _lifetime: PhantomData,
        }
    }

    /// Return a mutable pointer to the first `OSSL_PARAM` element.
    ///
    /// Pass to functions such as `EVP_PKEY_get_params` that fill a
    /// pre-prepared query array.
    #[must_use]
    pub fn as_mut_ptr(&mut self) -> *mut sys::OSSL_PARAM {
        self.ptr
    }

    /// Return `true` if a parameter with the given name exists in this array.
    #[must_use]
    pub fn has_param(&self, key: &CStr) -> bool {
        !unsafe { sys::OSSL_PARAM_locate(self.ptr, key.as_ptr()) }.is_null()
    }

    /// Locate `key` and read its value as an `i32`.
    ///
    /// # Errors
    ///
    /// Returns `Err` if the key is not found or the value cannot be converted.
    pub fn get_int(&self, key: &CStr) -> Result<i32, ErrorStack> {
        let elem = unsafe { sys::OSSL_PARAM_locate(self.ptr, key.as_ptr()) };
        if elem.is_null() {
            return Err(ErrorStack::drain());
        }
        let mut val: std::os::raw::c_int = 0;
        crate::ossl_call!(sys::OSSL_PARAM_get_int(elem, std::ptr::addr_of_mut!(val)))?;
        Ok(val)
    }

    /// Locate `key` and read its value as a `u32`.
    ///
    /// # Errors
    pub fn get_uint(&self, key: &CStr) -> Result<u32, ErrorStack> {
        let elem = unsafe { sys::OSSL_PARAM_locate(self.ptr, key.as_ptr()) };
        if elem.is_null() {
            return Err(ErrorStack::drain());
        }
        let mut val: std::os::raw::c_uint = 0;
        crate::ossl_call!(sys::OSSL_PARAM_get_uint(elem, std::ptr::addr_of_mut!(val)))?;
        Ok(val)
    }

    /// Locate `key` and read its value as a `usize`.
    ///
    /// # Errors
    pub fn get_size_t(&self, key: &CStr) -> Result<usize, ErrorStack> {
        let elem = unsafe { sys::OSSL_PARAM_locate(self.ptr, key.as_ptr()) };
        if elem.is_null() {
            return Err(ErrorStack::drain());
        }
        let mut val: usize = 0;
        crate::ossl_call!(sys::OSSL_PARAM_get_size_t(
            elem,
            std::ptr::addr_of_mut!(val)
        ))?;
        Ok(val)
    }

    /// Locate `key` and read its value as an `i64`.
    ///
    /// # Errors
    pub fn get_i64(&self, key: &CStr) -> Result<i64, ErrorStack> {
        let elem = unsafe { sys::OSSL_PARAM_locate(self.ptr, key.as_ptr()) };
        if elem.is_null() {
            return Err(ErrorStack::drain());
        }
        let mut val: i64 = 0;
        crate::ossl_call!(sys::OSSL_PARAM_get_int64(elem, std::ptr::addr_of_mut!(val)))?;
        Ok(val)
    }

    /// Locate `key` and read its value as a `u64`.
    ///
    /// # Errors
    pub fn get_u64(&self, key: &CStr) -> Result<u64, ErrorStack> {
        let elem = unsafe { sys::OSSL_PARAM_locate(self.ptr, key.as_ptr()) };
        if elem.is_null() {
            return Err(ErrorStack::drain());
        }
        let mut val: u64 = 0;
        crate::ossl_call!(sys::OSSL_PARAM_get_uint64(
            elem,
            std::ptr::addr_of_mut!(val)
        ))?;
        Ok(val)
    }

    /// Locate `key` and read it as BIGNUM, returning big-endian bytes.
    ///
    /// # Errors
    ///
    /// Returns `Err` if the key is not found or is not a BIGNUM parameter.
    pub fn get_bn(&self, key: &CStr) -> Result<Vec<u8>, ErrorStack> {
        let elem = unsafe { sys::OSSL_PARAM_locate(self.ptr, key.as_ptr()) };
        if elem.is_null() {
            return Err(ErrorStack::drain());
        }
        let mut bn_ptr: *mut sys::BIGNUM = ptr::null_mut();
        crate::ossl_call!(sys::OSSL_PARAM_get_BN(elem, std::ptr::addr_of_mut!(bn_ptr)))?;
        let bn = Bn(bn_ptr);
        Ok(bn.to_bigendian_vec())
    }

    /// Locate `key` and return a borrowed slice of its octet-string data.
    ///
    /// The returned slice is valid for the lifetime of `self`.
    ///
    /// # Errors
    pub fn get_octet_string(&self, key: &CStr) -> Result<&[u8], ErrorStack> {
        let elem = unsafe { sys::OSSL_PARAM_locate(self.ptr, key.as_ptr()) };
        if elem.is_null() {
            return Err(ErrorStack::drain());
        }
        let mut p: *const std::os::raw::c_void = ptr::null();
        let mut len: usize = 0;
        crate::ossl_call!(sys::OSSL_PARAM_get_octet_string_ptr(
            elem,
            std::ptr::addr_of_mut!(p),
            std::ptr::addr_of_mut!(len),
        ))?;
        // SAFETY: p points into the OSSL_PARAM array owned by self; valid for &self lifetime.
        Ok(unsafe { std::slice::from_raw_parts(p.cast::<u8>(), len) })
    }

    /// Locate `key` and return a borrowed `CStr` of its UTF-8 string data.
    ///
    /// The returned reference is valid for the lifetime of `self`.
    ///
    /// # Errors
    pub fn get_utf8_string(&self, key: &CStr) -> Result<&CStr, ErrorStack> {
        let elem = unsafe { sys::OSSL_PARAM_locate(self.ptr, key.as_ptr()) };
        if elem.is_null() {
            return Err(ErrorStack::drain());
        }
        let mut p: *const std::os::raw::c_char = ptr::null();
        crate::ossl_call!(sys::OSSL_PARAM_get_utf8_string_ptr(
            elem,
            std::ptr::addr_of_mut!(p),
        ))?;
        // SAFETY: p points into the OSSL_PARAM array owned by self; valid for &self lifetime.
        Ok(unsafe { CStr::from_ptr(p) })
    }
}

// ── Null sentinel ─────────────────────────────────────────────────────────────

/// A const null `OSSL_PARAM` pointer — used to pass `NULL` to OpenSSL functions
/// that accept an optional `const OSSL_PARAM[]` argument.
#[must_use]
pub(crate) fn null_params() -> *const sys::OSSL_PARAM {
    ptr::null()
}

// ── Tests ─────────────────────────────────────────────────────────────────────

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

    #[test]
    fn int_round_trip() {
        let params = ParamBuilder::new()
            .unwrap()
            .push_int(c"mykey", 42)
            .unwrap()
            .build()
            .unwrap();

        // Locate the specific OSSL_PARAM element by name, then get its value.
        let elem = unsafe { sys::OSSL_PARAM_locate(params.as_ptr().cast_mut(), c"mykey".as_ptr()) };
        assert!(!elem.is_null(), "OSSL_PARAM_locate failed");

        let mut out: i32 = 0;
        let rc = unsafe { sys::OSSL_PARAM_get_int(elem, std::ptr::addr_of_mut!(out)) };
        assert_eq!(rc, 1, "OSSL_PARAM_get_int failed");
        assert_eq!(out, 42);
    }

    #[test]
    fn octet_slice_round_trip() {
        let data = b"hello world";
        let params = ParamBuilder::new()
            .unwrap()
            .push_octet_slice(c"blob", data)
            .unwrap()
            .build()
            .unwrap();

        let elem = unsafe { sys::OSSL_PARAM_locate(params.as_ptr().cast_mut(), c"blob".as_ptr()) };
        assert!(!elem.is_null());

        let mut p: *const std::os::raw::c_void = ptr::null();
        let mut len: usize = 0;
        let rc = unsafe {
            sys::OSSL_PARAM_get_octet_string_ptr(
                elem,
                std::ptr::addr_of_mut!(p),
                std::ptr::addr_of_mut!(len),
            )
        };
        assert_eq!(rc, 1, "OSSL_PARAM_get_octet_string_ptr failed");
        assert_eq!(len, data.len());
        let got = unsafe { std::slice::from_raw_parts(p.cast::<u8>(), len) };
        assert_eq!(got, data);
    }

    // push_octet_ptr is verified through KDF integration tests (Phase 6),
    // where it is used in a complete derive() operation.  Isolated unit tests
    // for it are unreliable because OSSL_PARAM_BLD_to_param may exhaust the
    // OpenSSL secure heap in test environments.

    #[test]
    fn utf8_string_round_trip() {
        let params = ParamBuilder::new()
            .unwrap()
            .push_utf8_string(c"alg", c"SHA-256")
            .unwrap()
            .build()
            .unwrap();

        let elem = unsafe { sys::OSSL_PARAM_locate(params.as_ptr().cast_mut(), c"alg".as_ptr()) };
        assert!(!elem.is_null());

        let mut out: *const std::os::raw::c_char = ptr::null();
        let rc = unsafe { sys::OSSL_PARAM_get_utf8_string_ptr(elem, std::ptr::addr_of_mut!(out)) };
        assert_eq!(rc, 1, "OSSL_PARAM_get_utf8_string_ptr failed");
        let got = unsafe { CStr::from_ptr(out) };
        assert_eq!(got.to_bytes(), b"SHA-256");
    }
}