noxtls-crypto 0.2.12

Internal implementation crate for noxtls: hash, symmetric cipher, public-key, and DRBG primitives.
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
// Copyright (c) 2019-2026, Argenox Technologies LLC
// All rights reserved.
//
// SPDX-License-Identifier: GPL-2.0-only OR LicenseRef-Argenox-Commercial-License
//
// This file is part of the NoxTLS Library.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by the
// Free Software Foundation; version 2 of the License.
//
// Alternatively, this file may be used under the terms of a commercial
// license from Argenox Technologies LLC.
//
// See `noxtls/LICENSE` and `noxtls/LICENSE.md` in this repository for full details.
// CONTACT: info@argenox.com

//! Concrete public-key implementations (RSA, ECC, X25519/X448, Ed25519, ML-KEM, ML-DSA).
//!
//! Submodules are private; this module re-exports the supported API and provides
//! [`noxtls_ecc_generate_keypair_auto`] for unified ECC key generation.

mod bignum;
mod ed25519;
mod ed448;
mod mldsa;
mod mlkem;
mod named_curve;
mod p256;
mod p384;
mod pq_selftest;
mod rsa;
mod x25519;
mod x448;

use core::cmp::Ordering;

use crate::drbg::HmacDrbgSha256;
use crate::internal_alloc::Vec;
use bignum::BigUint;
#[cfg(not(feature = "hazardous-legacy-crypto"))]
use noxtls_core::Error;
use noxtls_core::Result;

pub use ed25519::{
    noxtls_ed25519_generate_private_key_auto,
    noxtls_ed25519_public_key_from_subject_public_key_info, noxtls_ed25519_verify,
    Ed25519PrivateKey, Ed25519PublicKey,
};
pub use ed448::{
    noxtls_ed448_generate_private_key_auto, noxtls_ed448_public_key_from_subject_public_key_info,
    noxtls_ed448_verify, Ed448PrivateKey, Ed448PublicKey,
};
pub use mldsa::{
    noxtls_mldsa_generate_keypair_auto, noxtls_mldsa_public_key_from_subject_public_key_info,
    noxtls_mldsa_verify, MlDsaPrivateKey, MlDsaPublicKey, OID_ID_MLDSA65,
};
pub use mlkem::{
    noxtls_mlkem_decapsulate, noxtls_mlkem_encapsulate_auto, noxtls_mlkem_generate_keypair_auto,
    noxtls_mlkem_generate_keypair_auto_for_parameter_set, MlKemParameterSet, MlKemPrivateKey,
    MlKemPublicKey, MLKEM1024_CIPHERTEXT_LEN, MLKEM1024_PRIVATE_KEY_LEN, MLKEM1024_PUBLIC_KEY_LEN,
    MLKEM512_CIPHERTEXT_LEN, MLKEM512_PRIVATE_KEY_LEN, MLKEM512_PUBLIC_KEY_LEN,
    MLKEM_CIPHERTEXT_LEN, MLKEM_PRIVATE_KEY_LEN, MLKEM_PUBLIC_KEY_LEN, MLKEM_SHARED_SECRET_LEN,
};
pub use named_curve::{
    noxtls_named_curve_from_mbedtls_name, noxtls_named_curve_info,
    noxtls_named_ec_generate_private_key_auto, noxtls_named_ecdh_shared_secret,
    noxtls_named_ecdsa_sign_digest, noxtls_named_ecdsa_verify_digest,
    noxtls_secp256k1_ecdsa_sign_sha256, noxtls_secp521r1_ecdsa_sign_sha512, NamedCurve,
    NamedCurveInfo, NamedEcPrivateKey, NamedEcPublicKey, NOXTLS_MBEDTLS_ECC_CURVES,
};
pub use p256::{
    noxtls_p256_ecdh_shared_secret, noxtls_p256_ecdsa_sign_digest,
    noxtls_p256_ecdsa_sign_digest_auto, noxtls_p256_ecdsa_sign_sha256,
    noxtls_p256_ecdsa_sign_sha256_auto, noxtls_p256_ecdsa_verify_digest,
    noxtls_p256_ecdsa_verify_sha256, noxtls_p256_generate_private_key_auto, P256PrivateKey,
    P256PublicKey,
};
pub use p384::{
    noxtls_p384_ecdh_shared_secret, noxtls_p384_ecdsa_sign_digest,
    noxtls_p384_ecdsa_sign_digest_auto, noxtls_p384_ecdsa_sign_sha384,
    noxtls_p384_ecdsa_sign_sha384_auto, noxtls_p384_ecdsa_verify_digest,
    noxtls_p384_ecdsa_verify_sha384, noxtls_p384_generate_private_key_auto, P384PrivateKey,
    P384PublicKey,
};
pub use pq_selftest::noxtls_run_pq_self_tests;
#[cfg(feature = "hazardous-legacy-crypto")]
pub use rsa::{noxtls_rsa_generate_keypair_auto, noxtls_rsa_generate_keypair_with_exponent_auto};
pub use rsa::{
    noxtls_rsa_generate_keypair_secure_auto, noxtls_rsa_generate_keypair_with_policy_auto,
    noxtls_rsaes_oaep_sha256_decrypt, noxtls_rsaes_oaep_sha256_decrypt_crt_only,
    noxtls_rsaes_oaep_sha256_encrypt_auto, noxtls_rsaes_pkcs1_v15_decrypt,
    noxtls_rsaes_pkcs1_v15_decrypt_crt_only, noxtls_rsaes_pkcs1_v15_encrypt_auto,
    noxtls_rsassa_pss_sha256_sign, noxtls_rsassa_pss_sha256_sign_auto,
    noxtls_rsassa_pss_sha256_verify, noxtls_rsassa_pss_sha384_sign,
    noxtls_rsassa_pss_sha384_sign_auto, noxtls_rsassa_pss_sha384_verify, noxtls_rsassa_pss_sign,
    noxtls_rsassa_pss_verify, noxtls_rsassa_sha1_sign, noxtls_rsassa_sha1_verify,
    noxtls_rsassa_sha256_sign, noxtls_rsassa_sha256_verify, noxtls_rsassa_sha384_sign,
    noxtls_rsassa_sha384_verify, noxtls_rsassa_sha512_sign, noxtls_rsassa_sha512_verify,
    RsaKeySizePolicy, RsaPrivateKey, RsaPssHashAlgorithm, RsaPublicKey,
};
pub use x25519::{
    noxtls_x25519, noxtls_x25519_basepoint, noxtls_x25519_generate_private_key_auto,
    noxtls_x25519_shared_secret, X25519PrivateKey, X25519PublicKey,
};
#[cfg(feature = "hazardous-legacy-crypto")]
pub use x448::noxtls_x448_generate_private_key_auto;
#[cfg(feature = "hazardous-legacy-crypto")]
pub use x448::{noxtls_x448, noxtls_x448_basepoint, noxtls_x448_shared_secret};
pub use x448::{X448PrivateKey, X448PublicKey};

fn noxtls_parse_ffdhe_value(value: &[u8], label: &'static str) -> Result<BigUint> {
    if value.is_empty() {
        return Err(Error::InvalidLength(label));
    }
    Ok(BigUint::from_be_bytes(value))
}

fn noxtls_validate_ffdhe_prime(prime: &BigUint) -> Result<()> {
    if prime.cmp(&BigUint::from_u128(3)) != Ordering::Greater || !prime.is_odd() {
        return Err(Error::CryptoFailure(
            "ffdhe prime must be an odd integer greater than 3",
        ));
    }
    Ok(())
}

fn noxtls_validate_ffdhe_private(private_key: &BigUint, prime: &BigUint) -> Result<()> {
    if private_key.cmp(&BigUint::from_u128(1)) != Ordering::Greater {
        return Err(Error::CryptoFailure(
            "ffdhe private key must be greater than 1",
        ));
    }
    let upper = prime.sub(&BigUint::from_u128(1));
    if private_key.cmp(&upper) != Ordering::Less {
        return Err(Error::CryptoFailure(
            "ffdhe private key must be less than p - 1",
        ));
    }
    Ok(())
}

fn noxtls_validate_ffdhe_public(public_key: &BigUint, prime: &BigUint) -> Result<()> {
    if public_key.cmp(&BigUint::from_u128(1)) != Ordering::Greater {
        return Err(Error::CryptoFailure(
            "ffdhe public key must be greater than 1",
        ));
    }
    let upper = prime.sub(&BigUint::from_u128(1));
    if public_key.cmp(&upper) != Ordering::Less {
        return Err(Error::CryptoFailure(
            "ffdhe public key must be less than p - 1",
        ));
    }
    Ok(())
}

/// Computes a finite-field Diffie-Hellman public key for TLS DHE suites.
pub fn noxtls_ffdhe_public_key(
    private_key: &[u8],
    generator: &[u8],
    prime: &[u8],
) -> Result<Vec<u8>> {
    let p = noxtls_parse_ffdhe_value(prime, "ffdhe prime must not be empty")?;
    let g = noxtls_parse_ffdhe_value(generator, "ffdhe generator must not be empty")?;
    let x = noxtls_parse_ffdhe_value(private_key, "ffdhe private key must not be empty")?;
    noxtls_validate_ffdhe_prime(&p)?;
    noxtls_validate_ffdhe_private(&x, &p)?;
    noxtls_validate_ffdhe_public(&g, &p)?;
    Ok(BigUint::mod_exp(&g, &x, &p).to_be_bytes())
}

/// Computes the TLS DHE pre-master secret from a peer public key.
pub fn noxtls_ffdhe_shared_secret(
    private_key: &[u8],
    peer_public_key: &[u8],
    prime: &[u8],
) -> Result<Vec<u8>> {
    let p = noxtls_parse_ffdhe_value(prime, "ffdhe prime must not be empty")?;
    let x = noxtls_parse_ffdhe_value(private_key, "ffdhe private key must not be empty")?;
    let y = noxtls_parse_ffdhe_value(peer_public_key, "ffdhe peer public key must not be empty")?;
    noxtls_validate_ffdhe_prime(&p)?;
    noxtls_validate_ffdhe_private(&x, &p)?;
    noxtls_validate_ffdhe_public(&y, &p)?;
    Ok(BigUint::mod_exp(&y, &x, &p).to_be_bytes())
}

/// Selects one supported elliptic-curve key noxtls_algorithm for unified key generation.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum EccKeyAlgorithm {
    /// NIST P-192 (secp192r1) key material.
    Secp192R1,
    /// NIST P-224 (secp224r1) key material.
    Secp224R1,
    /// NIST P-256 (secp256r1) key material.
    P256,
    /// NIST P-384 (secp384r1) key material.
    P384,
    /// NIST P-521 (secp521r1) key material.
    P521,
    /// Koblitz secp192k1 key material.
    Secp192K1,
    /// Koblitz secp224k1 key material.
    Secp224K1,
    /// Koblitz secp256k1 key material.
    Secp256K1,
    /// BrainpoolP256r1 key material.
    BrainpoolP256R1,
    /// BrainpoolP384r1 key material.
    BrainpoolP384R1,
    /// BrainpoolP512r1 key material.
    BrainpoolP512R1,
    /// Curve25519 X25519 key-exchange key material.
    X25519,
    /// Curve448 X448 key-exchange key material.
    X448,
    /// Ed25519 signing key material.
    Ed25519,
    /// Ed448 signing key material.
    Ed448,
}

/// Wraps one generated ECC private key variant.
#[derive(Debug, Clone)]
pub enum EccPrivateKey {
    /// P-256 private scalar.
    P256(P256PrivateKey),
    /// P-384 private scalar.
    P384(P384PrivateKey),
    /// Generic named-curve private scalar.
    Named(NamedEcPrivateKey),
    /// X25519 private scalar.
    X25519(X25519PrivateKey),
    /// X448 private scalar.
    X448(X448PrivateKey),
    /// Ed25519 signing seed/key.
    Ed25519(Ed25519PrivateKey),
    /// Ed448 signing seed/key.
    Ed448(Ed448PrivateKey),
}

/// Wraps one generated ECC public key variant.
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum EccPublicKey {
    /// P-256 public point.
    P256(P256PublicKey),
    /// P-384 public point.
    P384(P384PublicKey),
    /// Generic named-curve public point.
    Named(NamedEcPublicKey),
    /// X25519 public u-coordinate.
    X25519(X25519PublicKey),
    /// X448 public u-coordinate.
    X448(X448PublicKey),
    /// Ed25519 verifying key.
    Ed25519(Ed25519PublicKey),
    /// Ed448 verifying key.
    Ed448(Ed448PublicKey),
}

/// Generates one ECC private/public keypair for the selected noxtls_algorithm using DRBG entropy.
///
/// # Arguments
/// * `noxtls_algorithm`: ECC noxtls_algorithm to generate.
/// * `drbg`: DRBG source used for private-key randomness.
///
/// # Returns
/// `(private_key, public_key)` pair wrapped by enum variants matching `noxtls_algorithm`.
///
/// # Errors
///
/// Returns any error produced by the noxtls_algorithm-specific DRBG-driven generators (for example P-256 field validation, DRBG state errors, or malformed lengths from underlying calls).
///
/// # Panics
///
/// This function does not panic.
pub fn noxtls_ecc_generate_keypair_auto(
    noxtls_algorithm: EccKeyAlgorithm,
    drbg: &mut HmacDrbgSha256,
) -> Result<(EccPrivateKey, EccPublicKey)> {
    match noxtls_algorithm {
        EccKeyAlgorithm::Secp192R1 => {
            let private = noxtls_named_ec_generate_private_key_auto(NamedCurve::Secp192R1, drbg)?;
            let public = private.public_key()?;
            Ok((EccPrivateKey::Named(private), EccPublicKey::Named(public)))
        }
        EccKeyAlgorithm::Secp224R1 => {
            let private = noxtls_named_ec_generate_private_key_auto(NamedCurve::Secp224R1, drbg)?;
            let public = private.public_key()?;
            Ok((EccPrivateKey::Named(private), EccPublicKey::Named(public)))
        }
        EccKeyAlgorithm::P256 => {
            let private = noxtls_p256_generate_private_key_auto(drbg)?;
            let public = private.public_key()?;
            Ok((EccPrivateKey::P256(private), EccPublicKey::P256(public)))
        }
        EccKeyAlgorithm::P384 => {
            let private = noxtls_p384_generate_private_key_auto(drbg)?;
            let public = private.public_key()?;
            Ok((EccPrivateKey::P384(private), EccPublicKey::P384(public)))
        }
        EccKeyAlgorithm::P521 => {
            let private = noxtls_named_ec_generate_private_key_auto(NamedCurve::Secp521R1, drbg)?;
            let public = private.public_key()?;
            Ok((EccPrivateKey::Named(private), EccPublicKey::Named(public)))
        }
        EccKeyAlgorithm::Secp192K1 => {
            let private = noxtls_named_ec_generate_private_key_auto(NamedCurve::Secp192K1, drbg)?;
            let public = private.public_key()?;
            Ok((EccPrivateKey::Named(private), EccPublicKey::Named(public)))
        }
        EccKeyAlgorithm::Secp224K1 => {
            let private = noxtls_named_ec_generate_private_key_auto(NamedCurve::Secp224K1, drbg)?;
            let public = private.public_key()?;
            Ok((EccPrivateKey::Named(private), EccPublicKey::Named(public)))
        }
        EccKeyAlgorithm::Secp256K1 => {
            let private = noxtls_named_ec_generate_private_key_auto(NamedCurve::Secp256K1, drbg)?;
            let public = private.public_key()?;
            Ok((EccPrivateKey::Named(private), EccPublicKey::Named(public)))
        }
        EccKeyAlgorithm::BrainpoolP256R1 => {
            let private = noxtls_named_ec_generate_private_key_auto(NamedCurve::BrainpoolP256R1, drbg)?;
            let public = private.public_key()?;
            Ok((EccPrivateKey::Named(private), EccPublicKey::Named(public)))
        }
        EccKeyAlgorithm::BrainpoolP384R1 => {
            let private = noxtls_named_ec_generate_private_key_auto(NamedCurve::BrainpoolP384R1, drbg)?;
            let public = private.public_key()?;
            Ok((EccPrivateKey::Named(private), EccPublicKey::Named(public)))
        }
        EccKeyAlgorithm::BrainpoolP512R1 => {
            let private = noxtls_named_ec_generate_private_key_auto(NamedCurve::BrainpoolP512R1, drbg)?;
            let public = private.public_key()?;
            Ok((EccPrivateKey::Named(private), EccPublicKey::Named(public)))
        }
        EccKeyAlgorithm::X25519 => {
            let private = noxtls_x25519_generate_private_key_auto(drbg)?;
            let public = private.clone().public_key();
            Ok((EccPrivateKey::X25519(private), EccPublicKey::X25519(public)))
        }
        #[cfg(feature = "hazardous-legacy-crypto")]
        EccKeyAlgorithm::X448 => {
            let private = noxtls_x448_generate_private_key_auto(drbg)?;
            let public = private.clone().public_key();
            Ok((EccPrivateKey::X448(private), EccPublicKey::X448(public)))
        }
        #[cfg(not(feature = "hazardous-legacy-crypto"))]
        EccKeyAlgorithm::X448 => Err(Error::StateError(
            "x448 operations are disabled by default; enable `hazardous-legacy-crypto` to use non-constant-time x448 implementation",
        )),
        EccKeyAlgorithm::Ed25519 => {
            let private = noxtls_ed25519_generate_private_key_auto(drbg)?;
            let public = private.verifying_key();
            Ok((
                EccPrivateKey::Ed25519(private),
                EccPublicKey::Ed25519(public),
            ))
        }
        EccKeyAlgorithm::Ed448 => {
            let private = noxtls_ed448_generate_private_key_auto(drbg)?;
            let public = private.verifying_key();
            Ok((
                EccPrivateKey::Ed448(private),
                EccPublicKey::Ed448(public),
            ))
        }
    }
}

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

    #[test]
    fn ecc_keygen_includes_standard_named_weierstrass_curves() {
        let algorithms = [
            EccKeyAlgorithm::Secp192R1,
            EccKeyAlgorithm::Secp224R1,
            EccKeyAlgorithm::P384,
            EccKeyAlgorithm::P521,
            EccKeyAlgorithm::Secp192K1,
            EccKeyAlgorithm::Secp224K1,
            EccKeyAlgorithm::Secp256K1,
            EccKeyAlgorithm::BrainpoolP256R1,
            EccKeyAlgorithm::BrainpoolP384R1,
            EccKeyAlgorithm::BrainpoolP512R1,
            EccKeyAlgorithm::Ed448,
        ];

        for algorithm in algorithms {
            let mut drbg =
                HmacDrbgSha256::noxtls_new(b"ecc-standard-curves-keygen-seed", b"nonce", b"pkc")
                    .expect("drbg init");
            let (private, public) =
                noxtls_ecc_generate_keypair_auto(algorithm, &mut drbg).expect("curve keygen");
            match algorithm {
                EccKeyAlgorithm::P384 => {
                    assert!(matches!(private, EccPrivateKey::P384(_)));
                    assert!(matches!(public, EccPublicKey::P384(_)));
                }
                EccKeyAlgorithm::Ed448 => {
                    assert!(matches!(private, EccPrivateKey::Ed448(_)));
                    assert!(matches!(public, EccPublicKey::Ed448(_)));
                }
                _ => {
                    assert!(matches!(private, EccPrivateKey::Named(_)));
                    assert!(matches!(public, EccPublicKey::Named(_)));
                }
            }
        }
    }
}