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
//! `DigestAlg` — `EVP_MD` algorithm descriptor, and `DigestCtx` — stateful context.
//!
//! Phase 3.1 delivers `DigestAlg`; Phase 4.1 extends this module with `DigestCtx`.

use crate::error::ErrorStack;
use native_ossl_sys as sys;
use std::ffi::CStr;
use std::sync::Arc;

// ── DigestAlg — algorithm descriptor ─────────────────────────────────────────

/// An OpenSSL digest algorithm descriptor (`EVP_MD*`).
///
/// Fetched once and reused.  Implements `Clone` via `EVP_MD_up_ref`.
#[derive(Debug)]
pub struct DigestAlg {
    ptr: *mut sys::EVP_MD,
    /// Keeps the library context alive while this descriptor is in use.
    lib_ctx: Option<Arc<crate::lib_ctx::LibCtx>>,
}

impl DigestAlg {
    /// Fetch a digest algorithm from the global default library context.
    ///
    /// # Errors
    ///
    /// Returns `Err` if the algorithm is not available.
    pub fn fetch(name: &CStr, props: Option<&CStr>) -> Result<Self, ErrorStack> {
        let props_ptr = props.map_or(std::ptr::null(), CStr::as_ptr);
        let ptr = unsafe { sys::EVP_MD_fetch(std::ptr::null_mut(), name.as_ptr(), props_ptr) };
        if ptr.is_null() {
            return Err(ErrorStack::drain());
        }
        Ok(DigestAlg { ptr, lib_ctx: None })
    }

    /// Fetch a digest algorithm from an explicit library context.
    ///
    /// The `Arc` is cloned and held so the context outlives this descriptor.
    ///
    /// # Errors
    pub fn fetch_in(
        ctx: &Arc<crate::lib_ctx::LibCtx>,
        name: &CStr,
        props: Option<&CStr>,
    ) -> Result<Self, ErrorStack> {
        let props_ptr = props.map_or(std::ptr::null(), CStr::as_ptr);
        let ptr = unsafe { sys::EVP_MD_fetch(ctx.as_ptr(), name.as_ptr(), props_ptr) };
        if ptr.is_null() {
            return Err(ErrorStack::drain());
        }
        Ok(DigestAlg {
            ptr,
            lib_ctx: Some(Arc::clone(ctx)),
        })
    }

    /// Digest output size in bytes (e.g. 32 for SHA-256).
    #[must_use]
    pub fn output_len(&self) -> usize {
        usize::try_from(unsafe { sys::EVP_MD_get_size(self.ptr) }).unwrap_or(0)
    }

    /// Block size in bytes (e.g. 64 for SHA-256).
    #[must_use]
    pub fn block_size(&self) -> usize {
        usize::try_from(unsafe { sys::EVP_MD_get_block_size(self.ptr) }).unwrap_or(0)
    }

    /// NID (numeric identifier) of the digest algorithm.
    #[must_use]
    pub fn nid(&self) -> i32 {
        unsafe { sys::EVP_MD_get_type(self.ptr) }
    }

    /// Return the raw `EVP_MD*` pointer.  Valid for the lifetime of `self`.
    #[must_use]
    pub fn as_ptr(&self) -> *const sys::EVP_MD {
        self.ptr
    }
}

impl Clone for DigestAlg {
    fn clone(&self) -> Self {
        unsafe { sys::EVP_MD_up_ref(self.ptr) };
        DigestAlg {
            ptr: self.ptr,
            lib_ctx: self.lib_ctx.clone(),
        }
    }
}

impl Drop for DigestAlg {
    fn drop(&mut self) {
        unsafe { sys::EVP_MD_free(self.ptr) };
    }
}

// SAFETY: `EVP_MD*` is reference-counted and immutable after fetch.
unsafe impl Send for DigestAlg {}
unsafe impl Sync for DigestAlg {}

// ── DigestCtx — stateful context (Phase 4.1) ─────────────────────────────────

/// Stateful hash context (`EVP_MD_CTX*`).
///
/// `!Clone` — use `fork()` to duplicate mid-stream state.
/// All stateful operations require `&mut self` (exclusive ownership).
#[derive(Debug)]
pub struct DigestCtx {
    ptr: *mut sys::EVP_MD_CTX,
}

impl DigestCtx {
    /// Feed data into the ongoing hash computation.
    ///
    /// # Errors
    ///
    /// Returns `Err` if `EVP_DigestUpdate` fails.
    pub fn update(&mut self, data: &[u8]) -> Result<(), ErrorStack> {
        crate::ossl_call!(sys::EVP_DigestUpdate(
            self.ptr,
            data.as_ptr().cast(),
            data.len()
        ))
    }

    /// Finalise the hash and write the result into `out`.
    ///
    /// `out` must be at least `alg.output_len()` bytes.
    /// Returns the number of bytes written.
    ///
    /// # Errors
    ///
    /// Returns `Err` if `EVP_DigestFinal_ex` fails.
    pub fn finish(&mut self, out: &mut [u8]) -> Result<usize, ErrorStack> {
        let mut len: u32 = 0;
        crate::ossl_call!(sys::EVP_DigestFinal_ex(
            self.ptr,
            out.as_mut_ptr(),
            std::ptr::addr_of_mut!(len)
        ))?;
        Ok(usize::try_from(len).unwrap_or(0))
    }

    /// Finalise with XOF (extendable-output) mode.
    ///
    /// Used by SHAKE-128, SHAKE-256.  `out.len()` determines the output length.
    ///
    /// # Errors
    pub fn finish_xof(&mut self, out: &mut [u8]) -> Result<(), ErrorStack> {
        crate::ossl_call!(sys::EVP_DigestFinalXOF(
            self.ptr,
            out.as_mut_ptr(),
            out.len()
        ))
    }

    /// Fork the current mid-stream state into a new context.
    ///
    /// Equivalent to `EVP_MD_CTX_copy_ex` — a deep copy of the context state.
    /// Named `fork` (not `clone`) to signal the operation is potentially expensive.
    ///
    /// # Errors
    pub fn fork(&self) -> Result<DigestCtx, ErrorStack> {
        let new_ctx = unsafe { sys::EVP_MD_CTX_new() };
        if new_ctx.is_null() {
            return Err(ErrorStack::drain());
        }
        crate::ossl_call!(sys::EVP_MD_CTX_copy_ex(new_ctx, self.ptr))?;
        Ok(DigestCtx { ptr: new_ctx })
    }

    /// Query the byte count needed to serialise this context's mid-stream state.
    ///
    /// Calls `EVP_MD_CTX_serialize` with a null output pointer; the provider
    /// writes the required size to `*outlen` and returns 1.
    ///
    /// Only available when built against OpenSSL ≥ 4.0.
    ///
    /// # Errors
    ///
    /// Returns `Err` if the algorithm or provider does not support serialisation.
    #[cfg(ossl_v400)]
    pub fn serialize_size(&self) -> Result<usize, ErrorStack> {
        let mut outlen: usize = 0;
        crate::ossl_call!(sys::EVP_MD_CTX_serialize(
            self.ptr,
            std::ptr::null_mut(),
            std::ptr::addr_of_mut!(outlen)
        ))?;
        Ok(outlen)
    }

    /// Serialise the current mid-stream hash state into `out`.
    ///
    /// `out.len()` must be ≥ `serialize_size()`.  Returns the number of bytes
    /// written.  The serialised bytes can be passed to `deserialize()` on a
    /// freshly initialised context to restore the exact mid-stream state.
    ///
    /// Only available when built against OpenSSL ≥ 4.0.
    ///
    /// # Errors
    ///
    /// Returns `Err` if serialisation fails (e.g. buffer too small, or
    /// algorithm does not support serialisation).
    #[cfg(ossl_v400)]
    pub fn serialize(&self, out: &mut [u8]) -> Result<usize, ErrorStack> {
        let mut outlen: usize = out.len();
        crate::ossl_call!(sys::EVP_MD_CTX_serialize(
            self.ptr,
            out.as_mut_ptr(),
            std::ptr::addr_of_mut!(outlen)
        ))?;
        Ok(outlen)
    }

    /// Restore mid-stream hash state from bytes produced by `serialize()`.
    ///
    /// The context must already be initialised with the same algorithm before
    /// calling `deserialize()`.  After a successful call the context is in
    /// exactly the same state as when `serialize()` was called.
    ///
    /// Only available when built against OpenSSL ≥ 4.0.
    ///
    /// # Errors
    ///
    /// Returns `Err` if the data is malformed or the algorithm does not
    /// support deserialisation.
    #[cfg(ossl_v400)]
    pub fn deserialize(&mut self, data: &[u8]) -> Result<(), ErrorStack> {
        crate::ossl_call!(sys::EVP_MD_CTX_deserialize(
            self.ptr,
            data.as_ptr(),
            data.len()
        ))
    }

    /// Allocate an uninitialised `EVP_MD_CTX`.
    ///
    /// The context is not associated with any algorithm yet.  Use this when a
    /// raw context handle is needed before a higher-level init call (e.g.
    /// `EVP_DigestSignInit_ex`).
    ///
    /// # Errors
    ///
    /// Returns `Err` if `EVP_MD_CTX_new` fails.
    pub fn new_empty() -> Result<Self, ErrorStack> {
        let ptr = unsafe { sys::EVP_MD_CTX_new() };
        if ptr.is_null() {
            return Err(ErrorStack::drain());
        }
        Ok(DigestCtx { ptr })
    }

    /// Reinitialise this context for reuse with the given algorithm.
    ///
    /// Calls `EVP_DigestInit_ex2`.  Pass `None` for `params` when no extra
    /// initialisation parameters are required.
    ///
    /// # Errors
    ///
    /// Returns `Err` if `EVP_DigestInit_ex2` fails.
    pub fn reinit(
        &mut self,
        alg: &DigestAlg,
        params: Option<&crate::params::Params<'_>>,
    ) -> Result<(), ErrorStack> {
        crate::ossl_call!(sys::EVP_DigestInit_ex2(
            self.ptr,
            alg.ptr,
            params.map_or(std::ptr::null(), super::params::Params::as_ptr),
        ))
    }

    /// Construct a `DigestCtx` from a raw, owned `EVP_MD_CTX*`.
    ///
    /// # Safety
    ///
    /// `ptr` must be a valid, non-null `EVP_MD_CTX*` that the caller is giving up ownership of.
    /// The context need not be initialised with a digest algorithm yet.
    pub unsafe fn from_ptr(ptr: *mut sys::EVP_MD_CTX) -> Self {
        DigestCtx { ptr }
    }

    /// Return the raw `EVP_MD_CTX*` pointer.  Valid for the lifetime of `self`.
    ///
    /// Used by `Signer`/`Verifier` which call `EVP_DigestSign*`
    /// on this context directly.  Returns a mutable pointer because most
    /// OpenSSL EVP functions require `EVP_MD_CTX*` even for logically
    /// read-only operations.
    #[must_use]
    pub fn as_ptr(&self) -> *mut sys::EVP_MD_CTX {
        self.ptr
    }
}

impl Drop for DigestCtx {
    fn drop(&mut self) {
        unsafe { sys::EVP_MD_CTX_free(self.ptr) };
    }
}

// `EVP_MD_CTX` has no `up_ref` — it is `!Clone` and exclusively owned.
// `Send` is safe because no thread-local state is stored in the context.
// `Sync` is safe because Rust's &self/&mut self discipline prevents concurrent
// mutation; read-only access from multiple threads is safe for EVP_MD_CTX.
unsafe impl Send for DigestCtx {}
unsafe impl Sync for DigestCtx {}

impl DigestAlg {
    /// Create a new digest context initialised with this algorithm.
    ///
    /// # Errors
    ///
    /// Returns `Err` if context allocation or init fails.
    pub fn new_context(&self) -> Result<DigestCtx, ErrorStack> {
        let ctx_ptr = unsafe { sys::EVP_MD_CTX_new() };
        if ctx_ptr.is_null() {
            return Err(ErrorStack::drain());
        }
        crate::ossl_call!(sys::EVP_DigestInit_ex2(ctx_ptr, self.ptr, std::ptr::null())).map_err(
            |e| {
                unsafe { sys::EVP_MD_CTX_free(ctx_ptr) };
                e
            },
        )?;
        Ok(DigestCtx { ptr: ctx_ptr })
    }

    /// Compute a digest in a single call (one-shot path).
    ///
    /// Zero-copy: reads from `data`, writes into `out`.
    /// `out` must be at least `self.output_len()` bytes.
    ///
    /// # Errors
    pub fn digest(&self, data: &[u8], out: &mut [u8]) -> Result<usize, ErrorStack> {
        let mut len: u32 = 0;
        crate::ossl_call!(sys::EVP_Digest(
            data.as_ptr().cast(),
            data.len(),
            out.as_mut_ptr(),
            std::ptr::addr_of_mut!(len),
            self.ptr,
            std::ptr::null_mut()
        ))?;
        Ok(usize::try_from(len).unwrap_or(0))
    }

    /// Compute a digest and return it in a freshly allocated `Vec<u8>`.
    ///
    /// # Errors
    pub fn digest_to_vec(&self, data: &[u8]) -> Result<Vec<u8>, ErrorStack> {
        let mut out = vec![0u8; self.output_len()];
        let len = self.digest(data, &mut out)?;
        out.truncate(len);
        Ok(out)
    }
}

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

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

    #[test]
    fn fetch_sha256_properties() {
        let alg = DigestAlg::fetch(c"SHA2-256", None).unwrap();
        assert_eq!(alg.output_len(), 32);
        assert_eq!(alg.block_size(), 64);
    }

    #[test]
    fn fetch_nonexistent_fails() {
        assert!(DigestAlg::fetch(c"NONEXISTENT_DIGEST_XYZ", None).is_err());
    }

    #[test]
    fn clone_then_drop_both() {
        let alg = DigestAlg::fetch(c"SHA2-256", None).unwrap();
        let alg2 = alg.clone();
        // Drop both — must not double-free.
        drop(alg);
        drop(alg2);
    }

    /// SHA-256("abc") known-answer test (verified against OpenSSL CLI + Python hashlib).
    #[test]
    fn sha256_known_answer() {
        let alg = DigestAlg::fetch(c"SHA2-256", None).unwrap();
        let mut ctx = alg.new_context().unwrap();
        ctx.update(b"abc").unwrap();
        let mut out = [0u8; 32];
        let n = ctx.finish(&mut out).unwrap();
        assert_eq!(n, 32);
        assert_eq!(
            hex::encode(out),
            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
        );
    }

    /// Same vector via oneshot path.
    #[test]
    fn sha256_oneshot() {
        let alg = DigestAlg::fetch(c"SHA2-256", None).unwrap();
        let got = alg.digest_to_vec(b"abc").unwrap();
        let expected =
            hex::decode("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")
                .unwrap();
        assert_eq!(got, expected);
    }

    /// Fork mid-stream — two independent suffix completions.
    #[test]
    fn fork_mid_stream() {
        let alg = DigestAlg::fetch(c"SHA2-256", None).unwrap();
        let mut ctx = alg.new_context().unwrap();
        ctx.update(b"common prefix").unwrap();

        let mut fork = ctx.fork().unwrap();

        ctx.update(b" A").unwrap();
        fork.update(b" B").unwrap();

        let mut out_a = [0u8; 32];
        let mut out_b = [0u8; 32];
        ctx.finish(&mut out_a).unwrap();
        fork.finish(&mut out_b).unwrap();

        // Different suffixes → different digests.
        assert_ne!(out_a, out_b);
    }

    /// Verify that serialize/deserialize round-trip preserves mid-stream state.
    ///
    /// Strategy: hash "hello" in context A, serialize, restore into context B,
    /// then append " world" in both and confirm identical final digests.
    #[cfg(ossl_v400)]
    #[test]
    fn serialize_deserialize_roundtrip() {
        let alg = DigestAlg::fetch(c"SHA2-256", None).unwrap();

        let mut ctx_a = alg.new_context().unwrap();
        ctx_a.update(b"hello").unwrap();

        // Query then serialize mid-stream state.
        let size = ctx_a.serialize_size().unwrap();
        assert!(size > 0, "serialized state must be non-empty");

        let mut state = vec![0u8; size];
        let written = ctx_a.serialize(&mut state).unwrap();
        assert_eq!(written, size, "serialize wrote unexpected byte count");

        // Finish context A normally.
        ctx_a.update(b" world").unwrap();
        let mut out_a = [0u8; 32];
        ctx_a.finish(&mut out_a).unwrap();

        // Restore mid-stream state into context B, finish identically.
        let mut ctx_b = alg.new_context().unwrap();
        ctx_b.deserialize(&state).unwrap();
        ctx_b.update(b" world").unwrap();
        let mut out_b = [0u8; 32];
        ctx_b.finish(&mut out_b).unwrap();

        assert_eq!(out_a, out_b, "restored context produced different digest");
    }

    /// Changing the suffix after restore produces a different digest.
    #[cfg(ossl_v400)]
    #[test]
    fn serialize_different_suffix_differs() {
        let alg = DigestAlg::fetch(c"SHA2-256", None).unwrap();
        let mut ctx = alg.new_context().unwrap();
        ctx.update(b"hello").unwrap();

        let size = ctx.serialize_size().unwrap();
        let mut state = vec![0u8; size];
        ctx.serialize(&mut state).unwrap();

        let mut ctx_a = alg.new_context().unwrap();
        ctx_a.deserialize(&state).unwrap();
        ctx_a.update(b" world").unwrap();
        let mut out_a = [0u8; 32];
        ctx_a.finish(&mut out_a).unwrap();

        let mut ctx_b = alg.new_context().unwrap();
        ctx_b.deserialize(&state).unwrap();
        ctx_b.update(b" WORLD").unwrap();
        let mut out_b = [0u8; 32];
        ctx_b.finish(&mut out_b).unwrap();

        assert_ne!(
            out_a, out_b,
            "different suffixes must produce different digests"
        );
    }
}