synta-certificate 0.2.2

X.509 certificate structures for synta ASN.1 library
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
//! Fluent builders for PKCS #5 v2.1 (RFC 8018) parameter structures.
//!
//! Two builders are provided:
//!
//! | Builder | Structure | RFC §|
//! |---------|-----------|------|
//! | [`Pbkdf2ParamsBuilder`] | `Pkcs5Pbkdf2Params` | 5.2 |
//! | [`Pbes2ParamsBuilder`] | `Pkcs5Pbes2Params` | 6.2 |
//!
//! # Example — PBKDF2 parameters
//!
//! ```rust,ignore
//! use synta_certificate::{Pbkdf2ParamsBuilder, pkcs5_types};
//!
//! let params_der = Pbkdf2ParamsBuilder::new()
//!     .salt(&[0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08])
//!     .iteration_count(10_000)
//!     .key_length(32)
//!     .prf(pkcs5_types::ID_HMAC_WITH_SHA256_P5)
//!     .build()
//!     .unwrap();
//! ```
//!
//! # Example — PBES2 parameters
//!
//! ```rust,ignore
//! use synta_certificate::{Pbes2ParamsBuilder, pkcs5_types};
//!
//! let pbkdf2_der = Pbkdf2ParamsBuilder::new()
//!     .salt(&salt_bytes)
//!     .iteration_count(10_000)
//!     .key_length(32)
//!     .prf(pkcs5_types::ID_HMAC_WITH_SHA256_P5)
//!     .build_as_algorithm_identifier(pkcs5_types::ID_PBKDF2)
//!     .unwrap();
//!
//! let aes_iv = [0u8; 16];
//! let pbes2_der = Pbes2ParamsBuilder::new()
//!     .key_derivation_func(&pbkdf2_der)
//!     .encryption_scheme_from_oid(pkcs5_types::AES256_CBC_PAD, &aes_iv)
//!     .build()
//!     .unwrap();
//! ```

use synta::traits::Encode;

use crate::pkcs5_types::{Pkcs5AlgorithmIdentifier, Pkcs5Pbes2Params, Pkcs5Pbkdf2Params};

// ── Pbkdf2ParamsBuilder ───────────────────────────────────────────────────────

/// Fluent builder for `Pkcs5Pbkdf2Params` DER (RFC 8018 §5.2).
///
/// Required fields: `salt` and `iteration_count`.
/// Optional: `key_length`, `prf` (absent means HMAC-SHA-1 per RFC 8018 default).
#[derive(Debug, Default)]
pub struct Pbkdf2ParamsBuilder {
    /// Salt bytes for the OCTET STRING field.
    salt: Option<Vec<u8>>,
    /// Iteration count for the key derivation.
    iteration_count: Option<u64>,
    /// Optional key length in bytes.
    key_length: Option<u64>,
    /// Optional PRF algorithm OID component slice.
    prf_oid: Option<Vec<u32>>,
    /// First error encountered.
    error: Option<String>,
}

impl Pbkdf2ParamsBuilder {
    /// Create a new, empty `Pbkdf2ParamsBuilder`.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the `salt` OCTET STRING.
    ///
    /// RFC 8018 recommends at least 8 bytes of random salt.
    pub fn salt(mut self, salt: &[u8]) -> Self {
        if self.error.is_some() {
            return self;
        }
        self.salt = Some(salt.to_vec());
        self
    }

    /// Set the `iterationCount`.
    ///
    /// RFC 8018 specifies a minimum of 1000 iterations; modern deployments
    /// use at least 10 000.
    pub fn iteration_count(mut self, count: u64) -> Self {
        if self.error.is_some() {
            return self;
        }
        if count == 0 {
            self.error = Some("iteration_count must be at least 1".to_string());
            return self;
        }
        if count > i64::MAX as u64 {
            self.error = Some(format!(
                "iteration_count {} exceeds maximum representable DER INTEGER value",
                count
            ));
            return self;
        }
        self.iteration_count = Some(count);
        self
    }

    /// Set the optional `keyLength` (output key length in bytes).
    pub fn key_length(mut self, len: u64) -> Self {
        if self.error.is_some() {
            return self;
        }
        if len > i64::MAX as u64 {
            self.error = Some(format!(
                "key_length {} exceeds maximum representable DER INTEGER value",
                len
            ));
            return self;
        }
        self.key_length = Some(len);
        self
    }

    /// Set the optional `prf` algorithm OID.
    ///
    /// Use one of the HMAC OID constants from [`crate::pkcs5_types`], e.g.
    /// [`crate::pkcs5_types::ID_HMAC_WITH_SHA256_P5`].  When absent, the
    /// default HMAC-SHA-1 (`algid-hmacWithSHA1`) is used per RFC 8018 §5.2.
    pub fn prf(mut self, prf_oid: &[u32]) -> Self {
        if self.error.is_some() {
            return self;
        }
        self.prf_oid = Some(prf_oid.to_vec());
        self
    }

    /// Build the DER-encoded `Pkcs5Pbkdf2Params` SEQUENCE.
    ///
    /// Returns `Err` if `salt` or `iteration_count` are missing, or if DER
    /// encoding fails.
    pub fn build(self) -> Result<Vec<u8>, String> {
        self.build_inner()
    }

    /// Build the `Pkcs5Pbkdf2Params` and wrap it as an `AlgorithmIdentifier`
    /// with the given algorithm OID.
    ///
    /// This is a convenience method for producing the complete
    /// `AlgorithmIdentifier { id-PBKDF2, PBKDF2-params }` DER needed as
    /// the `keyDerivationFunc` field in `Pkcs5Pbes2Params`.
    ///
    /// Pass [`crate::pkcs5_types::ID_PBKDF2`] as `alg_oid`.
    pub fn build_as_algorithm_identifier(self, alg_oid: &[u32]) -> Result<Vec<u8>, String> {
        let params_bytes = self.build_inner()?;
        encode_alg_id_with_params(alg_oid, &params_bytes)
    }

    fn build_inner(self) -> Result<Vec<u8>, String> {
        if let Some(e) = self.error {
            return Err(e);
        }

        let salt_bytes = self.salt.ok_or_else(|| "salt is required".to_string())?;
        let iter_count = self
            .iteration_count
            .ok_or_else(|| "iteration_count is required".to_string())?;

        let salt_ref = synta::OctetStringRef::new(&salt_bytes);
        // Both values were validated to be ≤ i64::MAX at setter time.
        let iteration_count = synta::Integer::from(iter_count as i64);
        let key_length = self.key_length.map(|n| synta::Integer::from(n as i64));

        let prf_bytes: Option<Vec<u8>> = if let Some(ref oid_comps) = self.prf_oid {
            let oid = synta::ObjectIdentifier::new(oid_comps)
                .map_err(|e| format!("invalid PRF OID: {e}"))?;
            let prf_alg = Pkcs5AlgorithmIdentifier {
                algorithm: oid,
                parameters: None,
            };
            let mut enc = synta::Encoder::new(synta::Encoding::Der);
            prf_alg
                .encode(&mut enc)
                .map_err(|e| format!("PRF AlgorithmIdentifier encode failed: {e}"))?;
            Some(
                enc.finish()
                    .map_err(|e| format!("PRF AlgorithmIdentifier finish failed: {e}"))?,
            )
        } else {
            None
        };

        let prf: Option<Pkcs5AlgorithmIdentifier<'_>> = if let Some(ref bytes) = prf_bytes {
            Some(
                synta::Decoder::new(bytes, synta::Encoding::Der)
                    .decode::<Pkcs5AlgorithmIdentifier<'_>>()
                    .map_err(|e| format!("PRF AlgorithmIdentifier re-decode failed: {e}"))?,
            )
        } else {
            None
        };

        let params = Pkcs5Pbkdf2Params {
            salt: salt_ref,
            iteration_count,
            key_length,
            prf,
        };

        let mut enc = synta::Encoder::new(synta::Encoding::Der);
        params
            .encode(&mut enc)
            .map_err(|e| format!("Pkcs5Pbkdf2Params DER encoding failed: {e}"))?;
        enc.finish().map_err(|e| format!("DER finish failed: {e}"))
    }
}

// ── Pbes2ParamsBuilder ────────────────────────────────────────────────────────

/// Fluent builder for `Pkcs5Pbes2Params` DER (RFC 8018 §6.2).
///
/// `Pkcs5Pbes2Params` contains two `AlgorithmIdentifier` fields stored as
/// opaque `RawDer` blobs.  Both are required.
///
/// Typical usage:
/// 1. Build the PBKDF2 key derivation `AlgorithmIdentifier` with
///    [`Pbkdf2ParamsBuilder::build_as_algorithm_identifier`].
/// 2. Set the encryption scheme `AlgorithmIdentifier` (AES-CBC-PAD or similar)
///    with [`encryption_scheme_from_oid`](Self::encryption_scheme_from_oid).
/// 3. Call [`build`](Self::build).
#[derive(Debug, Default)]
pub struct Pbes2ParamsBuilder {
    /// Pre-encoded `keyDerivationFunc` AlgorithmIdentifier DER bytes.
    kdf_der: Option<Vec<u8>>,
    /// Pre-encoded `encryptionScheme` AlgorithmIdentifier DER bytes.
    enc_scheme_der: Option<Vec<u8>>,
    /// First error encountered.
    error: Option<String>,
}

impl Pbes2ParamsBuilder {
    /// Create a new, empty `Pbes2ParamsBuilder`.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the `keyDerivationFunc` from a pre-encoded `AlgorithmIdentifier` DER.
    ///
    /// Use [`Pbkdf2ParamsBuilder::build_as_algorithm_identifier`] to produce
    /// this DER blob.
    pub fn key_derivation_func(mut self, alg_id_der: &[u8]) -> Self {
        if self.error.is_some() {
            return self;
        }
        self.kdf_der = Some(alg_id_der.to_vec());
        self
    }

    /// Set the `encryptionScheme` from a pre-encoded `AlgorithmIdentifier` DER.
    pub fn encryption_scheme(mut self, alg_id_der: &[u8]) -> Self {
        if self.error.is_some() {
            return self;
        }
        self.enc_scheme_der = Some(alg_id_der.to_vec());
        self
    }

    /// Set the `encryptionScheme` from an OID component slice and an IV OCTET
    /// STRING value.
    ///
    /// This convenience method builds the `AlgorithmIdentifier { oid, OCTET STRING iv }`
    /// structure used by AES-CBC-PAD (`aes128-CBC-PAD`, `aes256-CBC-PAD`, etc.).
    ///
    /// `enc_oid` is the encryption algorithm OID, e.g.
    /// [`crate::pkcs5_types::AES256_CBC_PAD`].
    /// `iv` is the 16-byte initialization vector (must be exactly 16 bytes for
    /// AES-CBC-PAD algorithms).
    /// `iv` is the 16-byte initialization vector.
    pub fn encryption_scheme_from_oid(mut self, enc_oid: &[u32], iv: &[u8]) -> Self {
        if self.error.is_some() {
            return self;
        }
        if iv.len() != 16 {
            self.error = Some(format!(
                "IV must be exactly 16 bytes for AES-CBC-PAD; got {} bytes",
                iv.len()
            ));
            return self;
        }
        match encode_alg_id_with_octet_string_param(enc_oid, iv) {
            Ok(bytes) => self.enc_scheme_der = Some(bytes),
            Err(e) => self.error = Some(e),
        }
        self
    }

    /// Build the DER-encoded `Pkcs5Pbes2Params` SEQUENCE.
    ///
    /// Returns `Err` if either field was not set or if DER encoding fails.
    pub fn build(self) -> Result<Vec<u8>, String> {
        if let Some(e) = self.error {
            return Err(e);
        }

        let kdf_bytes = self
            .kdf_der
            .ok_or_else(|| "key_derivation_func is required".to_string())?;
        let enc_bytes = self
            .enc_scheme_der
            .ok_or_else(|| "encryption_scheme is required".to_string())?;

        let params = Pkcs5Pbes2Params {
            key_derivation_func: synta::RawDer(&kdf_bytes),
            encryption_scheme: synta::RawDer(&enc_bytes),
        };

        let mut enc = synta::Encoder::new(synta::Encoding::Der);
        params
            .encode(&mut enc)
            .map_err(|e| format!("Pkcs5Pbes2Params DER encoding failed: {e}"))?;
        enc.finish().map_err(|e| format!("DER finish failed: {e}"))
    }
}

// ── helpers ───────────────────────────────────────────────────────────────────

/// Encode `AlgorithmIdentifier { algorithm OID, parameters <params_der> }`.
fn encode_alg_id_with_params(oid_comps: &[u32], params_der: &[u8]) -> Result<Vec<u8>, String> {
    let oid = synta::ObjectIdentifier::new(oid_comps)
        .map_err(|e| format!("invalid algorithm OID: {e}"))?;
    let alg = Pkcs5AlgorithmIdentifier {
        algorithm: oid,
        parameters: Some(synta::RawDer(params_der)),
    };
    let mut enc = synta::Encoder::new(synta::Encoding::Der);
    alg.encode(&mut enc)
        .map_err(|e| format!("AlgorithmIdentifier encode failed: {e}"))?;
    enc.finish()
        .map_err(|e| format!("AlgorithmIdentifier finish failed: {e}"))
}

/// Encode `AlgorithmIdentifier { algorithm OID, parameters OCTET STRING iv }`.
fn encode_alg_id_with_octet_string_param(oid_comps: &[u32], iv: &[u8]) -> Result<Vec<u8>, String> {
    // Encode the OCTET STRING first.
    let os = synta::OctetString::new(iv.to_vec());
    let mut iv_enc = synta::Encoder::new(synta::Encoding::Der);
    os.encode(&mut iv_enc)
        .map_err(|e| format!("IV OCTET STRING encode failed: {e}"))?;
    let iv_der = iv_enc
        .finish()
        .map_err(|e| format!("IV OCTET STRING finish failed: {e}"))?;

    encode_alg_id_with_params(oid_comps, &iv_der)
}

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

    const TEST_SALT: &[u8] = &[0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08];
    const TEST_IV: &[u8] = &[0u8; 16];

    #[test]
    fn pbkdf2_params_minimal() {
        let der = Pbkdf2ParamsBuilder::new()
            .salt(TEST_SALT)
            .iteration_count(1000)
            .build()
            .expect("build should succeed");

        let decoded =
            pkcs5_types::Pkcs5Pbkdf2Params::from_der(&der).expect("round-trip decode failed");
        assert_eq!(decoded.iteration_count.as_i64().ok(), Some(1000));
        assert!(decoded.key_length.is_none());
        assert!(decoded.prf.is_none());
    }

    #[test]
    fn pbkdf2_params_with_sha256_prf() {
        let der = Pbkdf2ParamsBuilder::new()
            .salt(TEST_SALT)
            .iteration_count(10_000)
            .key_length(32)
            .prf(pkcs5_types::ID_HMAC_WITH_SHA256_P5)
            .build()
            .expect("build with SHA-256 PRF should succeed");

        let decoded =
            pkcs5_types::Pkcs5Pbkdf2Params::from_der(&der).expect("round-trip decode failed");
        assert_eq!(decoded.iteration_count.as_i64().ok(), Some(10_000));
        assert_eq!(
            decoded.key_length.as_ref().and_then(|n| n.as_i64().ok()),
            Some(32)
        );
        assert!(decoded.prf.is_some());
    }

    #[test]
    fn pbkdf2_params_missing_salt_returns_error() {
        let err = Pbkdf2ParamsBuilder::new().iteration_count(1000).build();
        assert!(err.is_err());
        assert!(err.unwrap_err().contains("salt"));
    }

    #[test]
    fn pbkdf2_params_zero_count_returns_error() {
        let err = Pbkdf2ParamsBuilder::new()
            .salt(TEST_SALT)
            .iteration_count(0)
            .build();
        assert!(err.is_err());
    }

    #[test]
    fn pbes2_params_round_trip() {
        let kdf_der = Pbkdf2ParamsBuilder::new()
            .salt(TEST_SALT)
            .iteration_count(10_000)
            .prf(pkcs5_types::ID_HMAC_WITH_SHA256_P5)
            .build_as_algorithm_identifier(pkcs5_types::ID_PBKDF2)
            .expect("PBKDF2 AlgorithmIdentifier build should succeed");

        let pbes2_der = Pbes2ParamsBuilder::new()
            .key_derivation_func(&kdf_der)
            .encryption_scheme_from_oid(pkcs5_types::AES256_CBC_PAD, TEST_IV)
            .build()
            .expect("PBES2 params build should succeed");

        // Round-trip decode.
        let _decoded =
            pkcs5_types::Pkcs5Pbes2Params::from_der(&pbes2_der).expect("round-trip decode failed");
    }

    #[test]
    fn pbes2_params_missing_kdf_returns_error() {
        let err = Pbes2ParamsBuilder::new()
            .encryption_scheme_from_oid(pkcs5_types::AES256_CBC_PAD, TEST_IV)
            .build();
        assert!(err.is_err());
        assert!(err.unwrap_err().contains("key_derivation_func"));
    }
}