ring-native-ossl 0.1.10

A ring-compatible API backed by native-ossl (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
//! Digital signature creation and verification, mirroring `ring::signature`.
//!
//! Covers ECDSA (P-256 and P-384 with SHA-256/384), Ed25519, and RSA (PKCS#1
//! and PSS padding, SHA-256/384/512).  For RSA public key input, callers must
//! supply a full `SubjectPublicKeyInfo` DER blob; for EC and Ed25519 the raw key
//! bytes are accepted and the SPKI wrapper is added internally.

use crate::error::{KeyRejected, Unspecified};
use native_ossl::digest::DigestAlg;
use native_ossl::params::ParamBuilder;
use native_ossl::pkey::{KeygenCtx, Pkey, Private, Public, SignInit, Signer, Verifier};
use std::ffi::CStr;

use crate::spki::{ED25519_SPKI_HEADER, P256_SPKI_HEADER, P384_SPKI_HEADER};

// ── Algorithm descriptor ──────────────────────────────────────────────────────

/// A signature algorithm (mirrors `ring::signature::Algorithm`).
///
/// All algorithm properties live in this struct so callers never have to
/// match on an internal enum — every operation reads the needed value
/// directly from the descriptor.
#[derive(Debug)]
pub struct Algorithm {
    /// Display name used in Debug output.
    pub(crate) name: &'static str,
    /// EC curve (e.g. `c"P-256"`). `None` for RSA and Ed25519.
    pub(crate) ec_curve: Option<&'static CStr>,
    /// SPKI DER prefix that wraps the raw public-key bytes.
    /// `None` for RSA, where the caller supplies full SPKI DER directly.
    pub(crate) spki_header: Option<&'static [u8]>,
    /// Digest algorithm for signing/verifying. `None` for Ed25519 (prehash-free).
    pub(crate) digest_name: Option<&'static CStr>,
    /// `true` for RSA-PSS; `false` for ECDSA, Ed25519, and RSA-PKCS1.
    pub(crate) rsa_pss: bool,
}

pub static ECDSA_P256_SHA256_ASN1: Algorithm = Algorithm {
    name: "ECDSA_P256_SHA256_ASN1",
    ec_curve: Some(c"P-256"),
    spki_header: Some(P256_SPKI_HEADER),
    digest_name: Some(c"SHA2-256"),
    rsa_pss: false,
};
pub static ECDSA_P384_SHA384_ASN1: Algorithm = Algorithm {
    name: "ECDSA_P384_SHA384_ASN1",
    ec_curve: Some(c"P-384"),
    spki_header: Some(P384_SPKI_HEADER),
    digest_name: Some(c"SHA2-384"),
    rsa_pss: false,
};
pub static ED25519: Algorithm = Algorithm {
    name: "ED25519",
    ec_curve: None,
    spki_header: Some(ED25519_SPKI_HEADER),
    digest_name: None,
    rsa_pss: false,
};
pub static RSA_PKCS1_SHA256: Algorithm = Algorithm {
    name: "RSA_PKCS1_SHA256",
    ec_curve: None,
    spki_header: None,
    digest_name: Some(c"SHA2-256"),
    rsa_pss: false,
};
pub static RSA_PKCS1_SHA384: Algorithm = Algorithm {
    name: "RSA_PKCS1_SHA384",
    ec_curve: None,
    spki_header: None,
    digest_name: Some(c"SHA2-384"),
    rsa_pss: false,
};
pub static RSA_PKCS1_SHA512: Algorithm = Algorithm {
    name: "RSA_PKCS1_SHA512",
    ec_curve: None,
    spki_header: None,
    digest_name: Some(c"SHA2-512"),
    rsa_pss: false,
};
pub static RSA_PSS_SHA256: Algorithm = Algorithm {
    name: "RSA_PSS_SHA256",
    ec_curve: None,
    spki_header: None,
    digest_name: Some(c"SHA2-256"),
    rsa_pss: true,
};
pub static RSA_PSS_SHA384: Algorithm = Algorithm {
    name: "RSA_PSS_SHA384",
    ec_curve: None,
    spki_header: None,
    digest_name: Some(c"SHA2-384"),
    rsa_pss: true,
};
pub static RSA_PSS_SHA512: Algorithm = Algorithm {
    name: "RSA_PSS_SHA512",
    ec_curve: None,
    spki_header: None,
    digest_name: Some(c"SHA2-512"),
    rsa_pss: true,
};

// ── Signature output ──────────────────────────────────────────────────────────

/// A DER-encoded signature (mirrors `ring::signature::Signature`).
#[derive(Debug)]
pub struct Signature(Vec<u8>);

impl AsRef<[u8]> for Signature {
    fn as_ref(&self) -> &[u8] {
        &self.0
    }
}

// ── EcdsaKeyPair ─────────────────────────────────────────────────────────────

/// An ECDSA signing key pair (mirrors `ring::signature::EcdsaKeyPair`).
pub struct EcdsaKeyPair {
    alg: &'static Algorithm,
    priv_key: Pkey<Private>,
    pub_key_bytes: Vec<u8>,
}

impl std::fmt::Debug for EcdsaKeyPair {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("EcdsaKeyPair")
            .field("alg", &self.alg.name)
            .finish_non_exhaustive()
    }
}

impl EcdsaKeyPair {
    /// Generate a new ECDSA key pair.
    ///
    /// # Errors
    ///
    /// Returns `Unspecified` if OpenSSL key generation fails or the algorithm has no EC curve.
    pub fn generate(alg: &'static Algorithm) -> Result<Self, Unspecified> {
        let curve = alg.ec_curve.ok_or(Unspecified)?;
        let spki_header = alg.spki_header.ok_or(Unspecified)?;

        let mut ctx = KeygenCtx::new(c"EC").map_err(|_| Unspecified)?;
        let params = ParamBuilder::new()
            .and_then(|b| b.push_utf8_string(c"group", curve))
            .and_then(ParamBuilder::build)
            .map_err(|_| Unspecified)?;
        ctx.set_params(&params).map_err(|_| Unspecified)?;
        let priv_key = ctx.generate().map_err(|_| Unspecified)?;

        let spki = priv_key.public_key_to_der().map_err(|_| Unspecified)?;
        let raw_pub = spki.get(spki_header.len()..).ok_or(Unspecified)?.to_vec();

        Ok(Self {
            alg,
            priv_key,
            pub_key_bytes: raw_pub,
        })
    }

    /// Load an ECDSA key pair from a PKCS#8 DER-encoded private key.
    ///
    /// # Errors
    ///
    /// Returns `KeyRejected` if the DER is malformed, the key is not EC, or the curve mismatches.
    pub fn from_pkcs8(
        alg: &'static Algorithm,
        pkcs8: &[u8],
        _rng: &dyn crate::rand::SecureRandom,
    ) -> Result<Self, KeyRejected> {
        let spki_header = alg
            .spki_header
            .ok_or_else(|| KeyRejected::new("wrong algorithm kind for ECDSA"))?;

        let priv_key =
            Pkey::<Private>::from_der(pkcs8).map_err(|_| KeyRejected::new("bad PKCS8 DER"))?;
        if !priv_key.is_a(c"EC") {
            return Err(KeyRejected::new("not an EC key"));
        }
        // Verify the curve matches by checking the SPKI DER header.
        let spki = priv_key
            .public_key_to_der()
            .map_err(|_| KeyRejected::new("public_key_to_der failed"))?;
        if !spki.starts_with(spki_header) {
            return Err(KeyRejected::new("wrong EC curve"));
        }
        let raw_pub = spki[spki_header.len()..].to_vec();

        Ok(Self {
            alg,
            priv_key,
            pub_key_bytes: raw_pub,
        })
    }

    #[must_use]
    pub fn public_key(&self) -> &[u8] {
        &self.pub_key_bytes
    }

    /// Sign `message` with this key pair.
    ///
    /// # Errors
    ///
    /// Returns `Unspecified` if the signing operation fails.
    pub fn sign(
        &self,
        _rng: &dyn crate::rand::SecureRandom,
        message: &[u8],
    ) -> Result<Signature, Unspecified> {
        let digest_name = self.alg.digest_name.ok_or(Unspecified)?;
        let digest_alg = DigestAlg::fetch(digest_name, None).map_err(|_| Unspecified)?;
        let init = SignInit {
            digest: Some(&digest_alg),
            params: None,
        };
        let mut signer = Signer::new(&self.priv_key, &init).map_err(|_| Unspecified)?;
        let sig = signer.sign_oneshot(message).map_err(|_| Unspecified)?;
        Ok(Signature(sig))
    }
}

// ── Ed25519KeyPair ────────────────────────────────────────────────────────────

/// An Ed25519 signing key pair (mirrors `ring::signature::Ed25519KeyPair`).
pub struct Ed25519KeyPair {
    priv_key: Pkey<Private>,
    pub_key_bytes: Vec<u8>,
}

impl std::fmt::Debug for Ed25519KeyPair {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Ed25519KeyPair").finish_non_exhaustive()
    }
}

impl Ed25519KeyPair {
    /// Generate a new Ed25519 key pair.
    ///
    /// # Errors
    ///
    /// Returns `Unspecified` if OpenSSL key generation fails.
    pub fn generate() -> Result<Self, Unspecified> {
        let mut ctx = KeygenCtx::new(c"ED25519").map_err(|_| Unspecified)?;
        let priv_key = ctx.generate().map_err(|_| Unspecified)?;
        let spki = priv_key.public_key_to_der().map_err(|_| Unspecified)?;
        let raw_pub = spki
            .get(ED25519_SPKI_HEADER.len()..)
            .ok_or(Unspecified)?
            .to_vec();
        Ok(Self {
            priv_key,
            pub_key_bytes: raw_pub,
        })
    }

    /// Load an Ed25519 key pair from a PKCS#8 DER-encoded private key.
    ///
    /// # Errors
    ///
    /// Returns `KeyRejected` if the DER is malformed or the key is not Ed25519.
    pub fn from_pkcs8(pkcs8: &[u8]) -> Result<Self, KeyRejected> {
        let priv_key =
            Pkey::<Private>::from_der(pkcs8).map_err(|_| KeyRejected::new("bad PKCS8 DER"))?;
        if !priv_key.is_a(c"ED25519") {
            return Err(KeyRejected::new("not an Ed25519 key"));
        }
        let spki = priv_key
            .public_key_to_der()
            .map_err(|_| KeyRejected::new("public_key_to_der failed"))?;
        let raw_pub = spki
            .get(ED25519_SPKI_HEADER.len()..)
            .ok_or_else(|| KeyRejected::new("unexpected SPKI layout"))?
            .to_vec();
        Ok(Self {
            priv_key,
            pub_key_bytes: raw_pub,
        })
    }

    #[must_use]
    pub fn public_key(&self) -> &[u8] {
        &self.pub_key_bytes
    }

    /// Sign `message`.
    ///
    /// # Errors
    ///
    /// Returns `Unspecified` if the signing operation fails.
    pub fn sign(&self, message: &[u8]) -> Result<Signature, Unspecified> {
        let init = SignInit {
            digest: None,
            params: None,
        };
        let mut signer = Signer::new(&self.priv_key, &init).map_err(|_| Unspecified)?;
        let sig = signer.sign_oneshot(message).map_err(|_| Unspecified)?;
        Ok(Signature(sig))
    }
}

// ── UnparsedPublicKey + verify ────────────────────────────────────────────────

/// A raw public key paired with its algorithm (mirrors `ring::signature::UnparsedPublicKey`).
pub struct UnparsedPublicKey<'a> {
    alg: &'static Algorithm,
    bytes: &'a [u8],
}

impl<'a> UnparsedPublicKey<'a> {
    #[must_use]
    pub fn new(algorithm: &'static Algorithm, bytes: &'a [u8]) -> Self {
        Self {
            alg: algorithm,
            bytes,
        }
    }
}

/// Verify `signature` over `message` using `public_key` and `algorithm`.
///
/// # Errors
///
/// Returns `Unspecified` if verification fails or the public key is invalid.
pub fn verify(
    algorithm: &'static Algorithm,
    public_key: &[u8],
    message: &[u8],
    signature: &[u8],
) -> Result<(), Unspecified> {
    UnparsedPublicKey::new(algorithm, public_key).verify(message, signature)
}

impl UnparsedPublicKey<'_> {
    /// # Errors
    ///
    /// Returns `Unspecified` if verification fails or the public key is invalid.
    pub fn verify(&self, message: &[u8], signature: &[u8]) -> Result<(), Unspecified> {
        let pub_key = load_public_key(self.alg, self.bytes)?;
        verify_with_key(self.alg, &pub_key, message, signature)
    }
}

fn load_public_key(alg: &'static Algorithm, raw: &[u8]) -> Result<Pkey<Public>, Unspecified> {
    let spki = match alg.spki_header {
        Some(header) => {
            let mut v = header.to_vec();
            v.extend_from_slice(raw);
            v
        }
        // RSA: caller supplies full SubjectPublicKeyInfo DER.
        None => raw.to_vec(),
    };
    Pkey::<Public>::from_der(&spki).map_err(|_| Unspecified)
}

fn verify_with_key(
    alg: &'static Algorithm,
    pub_key: &Pkey<Public>,
    message: &[u8],
    signature: &[u8],
) -> Result<(), Unspecified> {
    match alg.digest_name {
        None => {
            // Ed25519: no pre-hashing.
            let init = SignInit {
                digest: None,
                params: None,
            };
            let mut verifier = Verifier::new(pub_key, &init).map_err(|_| Unspecified)?;
            let ok = verifier
                .verify_oneshot(message, signature)
                .map_err(|_| Unspecified)?;
            if ok {
                Ok(())
            } else {
                Err(Unspecified)
            }
        }
        Some(digest_name) => verify_digest(pub_key, digest_name, alg.rsa_pss, message, signature),
    }
}

fn verify_digest(
    pub_key: &Pkey<Public>,
    digest_name: &'static CStr,
    rsa_pss: bool,
    message: &[u8],
    signature: &[u8],
) -> Result<(), Unspecified> {
    let digest_alg = DigestAlg::fetch(digest_name, None).map_err(|_| Unspecified)?;

    let params = if rsa_pss {
        let p = ParamBuilder::new()
            .and_then(|b| b.push_utf8_string(c"pad-mode", c"pss"))
            .and_then(ParamBuilder::build)
            .map_err(|_| Unspecified)?;
        Some(p)
    } else {
        None
    };

    let init = SignInit {
        digest: Some(&digest_alg),
        params: params.as_ref(),
    };
    let mut verifier = Verifier::new(pub_key, &init).map_err(|_| Unspecified)?;
    let ok = verifier
        .verify_oneshot(message, signature)
        .map_err(|_| Unspecified)?;
    if ok {
        Ok(())
    } else {
        Err(Unspecified)
    }
}