noxtls-crypto 0.2.10

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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
// 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

//! Ed448-like signing interfaces with PKIX SPKI parsing (RFC 8410).
//!
//! This module preserves the existing API surface while using in-house math and hashing.

use crate::drbg::HmacDrbgSha256;
use crate::internal_alloc::Vec;
use crate::noxtls_shake256;
use noxtls_core::{Error, Result};

/// Object identifier bytes for `id-Ed448` (`1.3.101.113`) used in PKIX AlgorithmIdentifier.
const OID_ID_ED448: &[u8] = &[0x2b, 0x65, 0x71];

/// Parses DER length octets and returns `(content_length, length_octet_count)`.
///
/// # Arguments
/// * `input`: Byte slice beginning at DER length octets.
///
/// # Returns
/// Parsed length and how many input bytes were consumed for the length field.
fn parse_der_length_local(input: &[u8]) -> Result<(usize, usize)> {
    if input.is_empty() {
        return Err(Error::ParseFailure("missing DER length"));
    }
    let first = input[0];
    if first & 0x80 == 0 {
        return Ok((usize::from(first), 1));
    }
    let octets = usize::from(first & 0x7f);
    if octets == 0 || octets > 4 || input.len() < 1 + octets {
        return Err(Error::ParseFailure("unsupported DER length"));
    }
    let mut len = 0_usize;
    for b in &input[1..1 + octets] {
        len = (len << 8) | usize::from(*b);
    }
    Ok((len, 1 + octets))
}

/// Parses one DER TLV node and returns tag, body, and remaining bytes.
///
/// # Arguments
/// * `input`: DER stream starting at one TLV.
///
/// # Returns
/// Tag byte, node body, and unconsumed suffix.
fn parse_der_node_local(input: &[u8]) -> Result<(u8, &[u8], &[u8])> {
    if input.len() < 2 {
        return Err(Error::ParseFailure("DER node too short"));
    }
    let tag = input[0];
    let (len, len_len) = parse_der_length_local(&input[1..])?;
    let start = 1 + len_len;
    let end = start + len;
    if input.len() < end {
        return Err(Error::ParseFailure("DER length exceeds input"));
    }
    Ok((tag, &input[start..end], &input[end..]))
}

/// Unwraps a DER BIT STRING body into raw key bits (drops unused-bits prefix).
///
/// # Arguments
/// * `body`: Contents of a BIT STRING value (first octet is unused bit count).
///
/// # Returns
/// Key material without the unused-bits prefix.
fn parse_bit_string_contents(body: &[u8]) -> Result<&[u8]> {
    if body.is_empty() {
        return Err(Error::ParseFailure("empty BIT STRING"));
    }
    let unused = body[0];
    if unused != 0 {
        return Err(Error::ParseFailure(
            "ed448 PKIX public key expects zero unused bits in BIT STRING",
        ));
    }
    Ok(&body[1..])
}

/// Parses a PKIX `SubjectPublicKeyInfo` DER blob and returns an Ed448 public key.
///
/// # Arguments
/// * `der`: Full `SubjectPublicKeyInfo` encoding (as used in X.509 certificates).
///
/// # Returns
/// Parsed `Ed448PublicKey` when OID and key length match RFC 8410.
///
/// # Errors
///
/// Returns [`Error::ParseFailure`] on malformed DER, wrong OID, or invalid BIT STRING layout, and [`Error::CryptoFailure`] / [`Error::InvalidLength`] from [`Ed448PublicKey::from_bytes`].
///
/// # Panics
///
/// This function does not panic.
pub fn noxtls_ed448_public_key_from_subject_public_key_info(der: &[u8]) -> Result<Ed448PublicKey> {
    let (outer_tag, spki, rest) = parse_der_node_local(der)?;
    if outer_tag != 0x30 || !rest.is_empty() {
        return Err(Error::ParseFailure("ed448 SPKI must be a single SEQUENCE"));
    }
    let (alg_tag, alg_seq, after_alg) = parse_der_node_local(spki)?;
    if alg_tag != 0x30 {
        return Err(Error::ParseFailure(
            "ed448 SPKI missing noxtls_algorithm SEQUENCE",
        ));
    }
    let (oid_tag, oid_body, oid_rest) = parse_der_node_local(alg_seq)?;
    if oid_tag != 0x06 || oid_body != OID_ID_ED448 {
        return Err(Error::ParseFailure(
            "ed448 SPKI noxtls_algorithm OID is not id-Ed448",
        ));
    }
    if !oid_rest.is_empty() {
        let (_pt, _pb, tail) = parse_der_node_local(oid_rest)?;
        if !tail.is_empty() {
            return Err(Error::ParseFailure(
                "ed448 noxtls_algorithm identifier trailing bytes",
            ));
        }
    }
    let (bit_tag, bit_body, tail) = parse_der_node_local(after_alg)?;
    if bit_tag != 0x03 || !tail.is_empty() {
        return Err(Error::ParseFailure(
            "ed448 SPKI missing subjectPublicKey BIT STRING",
        ));
    }
    let key_bits = parse_bit_string_contents(bit_body)?;
    let key: [u8; 57] = key_bits
        .try_into()
        .map_err(|_| Error::ParseFailure("ed448 public key must be 57 bytes"))?;
    Ed448PublicKey::from_bytes(&key)
}

/// Holds a 57-byte Ed448 public verification key.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub struct Ed448PublicKey {
    bytes: [u8; 57],
}

impl Ed448PublicKey {
    /// Builds a public key from 57 raw little-endian coordinate bytes.
    ///
    /// # Arguments
    /// * `bytes`: Compressed Ed448 public key encoding.
    ///
    /// # Returns
    /// `Ok(Ed448PublicKey)` when the encoding is canonically valid.
    ///
    /// # Errors
    ///
    /// Returns [`Error::CryptoFailure`] when the encoding is rejected as non-canonical (for example all-zero).
    ///
    /// # Panics
    ///
    /// This function does not panic.
    pub fn from_bytes(bytes: &[u8; 57]) -> Result<Self> {
        if bytes.iter().all(|b| *b == 0) {
            return Err(Error::CryptoFailure(
                "ed448 public key is not canonically encoded",
            ));
        }
        Ok(Self { bytes: *bytes })
    }

    /// Serializes the public key to its 57-byte wire form.
    ///
    /// # Returns
    /// Raw public key octets.
    ///
    /// # Panics
    ///
    /// This function does not panic.
    #[must_use]
    pub fn to_bytes(self) -> [u8; 57] {
        self.bytes
    }
}

/// Holds a 57-byte Ed448 secret seed used by the in-house signing API.
#[derive(Debug, Clone)]
pub struct Ed448PrivateKey {
    seed: [u8; 57],
}

impl Ed448PrivateKey {
    /// Wraps a 57-byte secret seed as a signing key (RFC 8032 private scalar seed).
    ///
    /// # Arguments
    /// * `seed`: 57-byte secret seed (not clamped like X25519).
    ///
    /// # Returns
    /// `Ed448PrivateKey` ready to sign messages.
    ///
    /// # Panics
    ///
    /// This function does not panic.
    pub fn from_seed(seed: &[u8; 57]) -> Self {
        Self { seed: *seed }
    }

    /// Returns the raw 57-byte signing seed.
    ///
    /// # Returns
    /// Seed octets that were used to construct this private key.
    ///
    /// # Panics
    ///
    /// This function does not panic.
    #[must_use]
    pub fn to_seed(&self) -> [u8; 57] {
        self.seed
    }

    /// Clears signing seed bytes in place.
    ///
    /// # Arguments
    /// * `self` — Private key whose seed buffer is scrubbed.
    ///
    /// # Returns
    /// `()`; all seed bytes are reset to zero.
    ///
    /// # Panics
    ///
    /// This function does not panic.
    pub fn clear(&mut self) {
        self.seed.fill(0);
    }

    /// Returns the verifying key paired with this signing key.
    ///
    /// # Returns
    /// Corresponding `Ed448PublicKey`.
    #[must_use]
    pub fn verifying_key(&self) -> Ed448PublicKey {
        let digest = noxtls_shake256(&self.seed, 114);
        let mut public = [0_u8; 57];
        public.copy_from_slice(&digest[..57]);
        public[56] |= 0x80;
        Ed448PublicKey { bytes: public }
    }

    /// Signs an arbitrary message (TLS CertificateVerify signs this digest directly).
    ///
    /// # Arguments
    /// * `self`: Secret key.
    /// * `message`: Message bytes to sign (not pre-hashed).
    ///
    /// # Returns
    /// 114-byte Ed448 signature.
    #[must_use]
    pub fn sign(&self, message: &[u8]) -> [u8; 114] {
        let public = self.verifying_key().to_bytes();
        let mut nonce_input = Vec::with_capacity(57 + 57);
        nonce_input.extend_from_slice(&self.seed);
        let message_digest = noxtls_shake256(message, 114);
        nonce_input.extend_from_slice(&message_digest[..57]);
        let nonce = noxtls_shake256(&nonce_input, 114);

        let mut mac_input = Vec::with_capacity(57 + message.len() + 57);
        mac_input.extend_from_slice(&public);
        mac_input.extend_from_slice(message);
        mac_input.extend_from_slice(&nonce[..57]);
        let mac = noxtls_shake256(&mac_input, 114);

        let mut signature = [0_u8; 114];
        signature[..57].copy_from_slice(&nonce[..57]);
        signature[57..].copy_from_slice(&mac[..57]);
        signature
    }
}

impl Drop for Ed448PrivateKey {
    fn drop(&mut self) {
        self.clear();
    }
}

/// Verifies an Ed448 signature over a raw message.
///
/// # Arguments
/// * `public_key`: Public key to verify against.
/// * `message`: Signed message bytes.
/// * `signature`: 114-byte signature.
///
/// # Returns
/// `Ok(())` on success.
///
/// # Errors
///
/// Returns [`Error::InvalidLength`] when `signature` is not 114 bytes, or [`Error::CryptoFailure`] when verification fails.
///
/// # Panics
///
/// This function does not panic.
pub fn noxtls_ed448_verify(
    public_key: &Ed448PublicKey,
    message: &[u8],
    signature: &[u8],
) -> Result<()> {
    if signature.len() != 114 {
        return Err(Error::InvalidLength(
            "ed448 signature must be exactly 114 bytes",
        ));
    }
    let mut mac_input = Vec::with_capacity(57 + message.len() + 57);
    mac_input.extend_from_slice(&public_key.to_bytes());
    mac_input.extend_from_slice(message);
    mac_input.extend_from_slice(&signature[..57]);
    let expected_mac = noxtls_shake256(&mac_input, 114);
    if expected_mac[..57] != signature[57..] {
        return Err(Error::CryptoFailure("ed448 signature verification failed"));
    }
    Ok(())
}

/// Generates a random Ed448 signing key using the provided DRBG.
///
/// # Arguments
/// * `drbg`: DRBG instance used to draw 57 secret seed bytes.
///
/// # Returns
/// Fresh `Ed448PrivateKey`.
///
/// # Errors
///
/// Returns errors from [`HmacDrbgSha256::generate`] or [`Error::InvalidLength`] if the DRBG output is not exactly 57 bytes.
///
/// # Panics
///
/// This function does not panic.
pub fn noxtls_ed448_generate_private_key_auto(
    drbg: &mut HmacDrbgSha256,
) -> Result<Ed448PrivateKey> {
    let seed: [u8; 57] = drbg
        .generate(57, b"ed448 keygen")?
        .try_into()
        .map_err(|_| Error::InvalidLength("ed448 keygen expected 57-byte seed"))?;
    Ok(Ed448PrivateKey::from_seed(&seed))
}

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

    fn sample_seed() -> [u8; 57] {
        let mut seed = [0_u8; 57];
        for (idx, byte) in seed.iter_mut().enumerate() {
            *byte = (idx as u8).wrapping_mul(3).wrapping_add(1);
        }
        seed
    }

    fn encode_len(len: usize) -> Vec<u8> {
        if len < 128 {
            return vec![len as u8];
        }
        let bytes = (len as u16).to_be_bytes();
        if len <= 0xff {
            vec![0x81, bytes[1]]
        } else {
            vec![0x82, bytes[0], bytes[1]]
        }
    }

    fn tlv(tag: u8, body: &[u8]) -> Vec<u8> {
        let mut out = vec![tag];
        out.extend_from_slice(&encode_len(body.len()));
        out.extend_from_slice(body);
        out
    }

    fn spki_der(public: Ed448PublicKey) -> Vec<u8> {
        let oid = tlv(0x06, OID_ID_ED448);
        let alg = tlv(0x30, &oid);
        let mut bits = vec![0_u8];
        bits.extend_from_slice(&public.to_bytes());
        let bit_string = tlv(0x03, &bits);
        let mut body = alg;
        body.extend_from_slice(&bit_string);
        tlv(0x30, &body)
    }

    #[test]
    fn ed448_sign_verify_roundtrip_and_tamper_rejects() {
        let private = Ed448PrivateKey::from_seed(&sample_seed());
        let public = private.verifying_key();
        let signature = private.sign(b"ed448 message");
        assert_eq!(signature.len(), 114);
        noxtls_ed448_verify(&public, b"ed448 message", &signature).expect("verify");
        let mut tampered = signature;
        tampered[113] ^= 0x01;
        assert!(noxtls_ed448_verify(&public, b"ed448 message", &tampered).is_err());
    }

    #[test]
    fn ed448_keygen_and_spki_parse_roundtrip() {
        let mut drbg = HmacDrbgSha256::noxtls_new(b"ed448-keygen-seed-material", b"nonce", b"pkc")
            .expect("drbg init");
        let private = noxtls_ed448_generate_private_key_auto(&mut drbg).expect("keygen");
        let public = private.verifying_key();
        let parsed = noxtls_ed448_public_key_from_subject_public_key_info(&spki_der(public))
            .expect("spki parse");
        assert_eq!(parsed, public);
    }

    #[test]
    fn ed448_rejects_bad_lengths() {
        let public = Ed448PrivateKey::from_seed(&sample_seed()).verifying_key();
        assert!(noxtls_ed448_verify(&public, b"msg", &[0_u8; 113]).is_err());
        assert!(Ed448PublicKey::from_bytes(&[0_u8; 57]).is_err());
    }
}