synta-python 0.2.5

Python extension module for the 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
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
500
501
502
503
504
//! Python wrapper for ASN.1 encoder

use pyo3::prelude::*;

use synta::Encoder;

use super::error::SyntaErr;

use super::types::{
    PyBitString, PyBmpString, PyBoolean, PyGeneralString, PyGeneralizedTime, PyIA5String,
    PyInteger, PyNull, PyNumericString, PyObjectIdentifier, PyOctetString, PyPrintableString,
    PyReal, PyTeletexString, PyUniversalString, PyUtcTime, PyUtf8String, PyVisibleString,
};
use super::PyEncoding;

/// ASN.1 Encoder
///
/// Encodes ASN.1 data in DER/BER format.
///
/// Example:
///     >>> encoder = Encoder(Encoding.DER)
///     >>> encoder.encode_integer(42)
///     >>> output = encoder.finish()
#[pyclass(name = "Encoder")]
pub struct PyEncoder {
    encoder: Encoder,
}

#[pymethods]
impl PyEncoder {
    /// Create a new encoder
    ///
    /// Args:
    ///     encoding: The encoding type (DER, BER, or CER)
    #[new]
    fn new(encoding: PyEncoding) -> Self {
        Self {
            encoder: Encoder::new(encoding.into()),
        }
    }

    /// Encode an INTEGER
    ///
    /// Accepts any Python ``int`` regardless of magnitude.  Values that fit in
    /// ``i64`` or ``i128`` are encoded via the native typed constructors;
    /// larger values (e.g. 20-byte X.509 serial numbers up to 160 bits) are
    /// converted through Python's ``int.to_bytes()`` using signed two's
    /// complement, then passed directly to the encoder.
    ///
    /// Args:
    ///     value: The integer value to encode (any Python int)
    fn encode_integer(
        &mut self,
        py: Python,
        value: &Bound<'_, pyo3::types::PyAny>,
    ) -> PyResult<()> {
        // Fast path: fits in i64 (covers most ASN.1 integer fields)
        if let Ok(v) = value.extract::<i64>() {
            self.encoder
                .encode(&synta::Integer::from_i64(v))
                .map_err(SyntaErr)?;
            return Ok(());
        }
        // Fits in i128 (covers 8–16 byte random serial numbers)
        if let Ok(v) = value.extract::<i128>() {
            self.encoder
                .encode(&synta::Integer::from_i128(v))
                .map_err(SyntaErr)?;
            return Ok(());
        }
        // Arbitrarily large: convert via Python int methods.
        // ceil((bit_length + 1) / 8) == (bit_length + 8) / 8 bytes are
        // sufficient for signed two's complement encoding of any integer.
        let bit_len: usize = value
            .call_method0(pyo3::intern!(py, "bit_length"))?
            .extract()?;
        let byte_len = ((bit_len + 8) / 8).max(1);
        let kwargs = pyo3::types::PyDict::new(py);
        kwargs.set_item(pyo3::intern!(py, "signed"), true)?;
        let raw: Vec<u8> = value
            .call_method(
                pyo3::intern!(py, "to_bytes"),
                (byte_len, pyo3::intern!(py, "big")),
                Some(&kwargs),
            )?
            .extract()?;
        self.encoder
            .encode(&synta::Integer::from_bytes(&raw))
            .map_err(SyntaErr)?;
        Ok(())
    }

    /// Encode an INTEGER from a PyInteger object
    ///
    /// Args:
    ///     value: The PyInteger object to encode
    fn encode_integer_object(&mut self, value: &PyInteger) -> PyResult<()> {
        self.encoder.encode(&value.inner).map_err(SyntaErr)?;
        Ok(())
    }

    /// Encode an OCTET STRING
    ///
    /// Args:
    ///     data: The bytes to encode
    fn encode_octet_string(&mut self, data: &[u8]) -> PyResult<()> {
        let octet_string = synta::OctetStringRef::new(data);
        self.encoder.encode(&octet_string).map_err(SyntaErr)?;
        Ok(())
    }

    /// Encode an OCTET STRING from a PyOctetString object
    ///
    /// Args:
    ///     value: The PyOctetString object to encode
    fn encode_octet_string_object(&mut self, value: &PyOctetString) -> PyResult<()> {
        self.encoder.encode(&value.inner).map_err(SyntaErr)?;
        Ok(())
    }

    /// Encode an OBJECT IDENTIFIER
    ///
    /// Args:
    ///     value: The PyObjectIdentifier to encode
    fn encode_oid(&mut self, value: &PyObjectIdentifier) -> PyResult<()> {
        self.encoder.encode(&value.inner).map_err(SyntaErr)?;
        Ok(())
    }

    /// Encode an OBJECT IDENTIFIER from a PyObjectIdentifier object (alias for encode_oid)
    fn encode_oid_object(&mut self, value: &PyObjectIdentifier) -> PyResult<()> {
        self.encoder.encode(&value.inner).map_err(SyntaErr)?;
        Ok(())
    }

    /// Encode a BIT STRING
    ///
    /// Args:
    ///     value: The PyBitString to encode
    fn encode_bit_string(&mut self, value: &PyBitString) -> PyResult<()> {
        self.encoder.encode(&value.inner).map_err(SyntaErr)?;
        Ok(())
    }

    /// Encode a BIT STRING from a PyBitString object (alias for encode_bit_string)
    fn encode_bit_string_object(&mut self, value: &PyBitString) -> PyResult<()> {
        self.encoder.encode(&value.inner).map_err(SyntaErr)?;
        Ok(())
    }

    /// Encode a BOOLEAN
    ///
    /// Args:
    ///     value: The boolean value to encode
    fn encode_boolean(&mut self, value: bool) -> PyResult<()> {
        let boolean = synta::Boolean::new(value);
        self.encoder.encode(&boolean).map_err(SyntaErr)?;
        Ok(())
    }

    /// Encode a BOOLEAN from a PyBoolean object
    ///
    /// Args:
    ///     value: The PyBoolean object to encode
    fn encode_boolean_object(&mut self, value: &PyBoolean) -> PyResult<()> {
        self.encoder.encode(&value.inner).map_err(SyntaErr)?;
        Ok(())
    }

    /// Encode a UTCTime
    ///
    /// Args:
    ///     value: The PyUtcTime to encode
    fn encode_utc_time(&mut self, value: &PyUtcTime) -> PyResult<()> {
        self.encoder.encode(&value.inner).map_err(SyntaErr)?;
        Ok(())
    }

    /// Encode a UTCTime from a PyUtcTime object (alias for encode_utc_time)
    fn encode_utc_time_object(&mut self, value: &PyUtcTime) -> PyResult<()> {
        self.encoder.encode(&value.inner).map_err(SyntaErr)?;
        Ok(())
    }

    /// Encode a GeneralizedTime
    ///
    /// Args:
    ///     value: The PyGeneralizedTime to encode
    fn encode_generalized_time(&mut self, value: &PyGeneralizedTime) -> PyResult<()> {
        self.encoder.encode(&value.inner).map_err(SyntaErr)?;
        Ok(())
    }

    /// Encode a GeneralizedTime from a PyGeneralizedTime object (alias for encode_generalized_time)
    fn encode_generalized_time_object(&mut self, value: &PyGeneralizedTime) -> PyResult<()> {
        self.encoder.encode(&value.inner).map_err(SyntaErr)?;
        Ok(())
    }

    /// Encode a REAL
    ///
    /// Args:
    ///     value: The float value to encode
    fn encode_real(&mut self, value: f64) -> PyResult<()> {
        let real = synta::Real::new(value);
        self.encoder.encode(&real).map_err(SyntaErr)?;
        Ok(())
    }

    /// Encode a REAL from a PyReal object
    ///
    /// Args:
    ///     value: The PyReal object to encode
    fn encode_real_object(&mut self, value: &PyReal) -> PyResult<()> {
        self.encoder.encode(&value.inner).map_err(SyntaErr)?;
        Ok(())
    }

    /// Encode a NULL
    fn encode_null(&mut self) -> PyResult<()> {
        self.encoder.encode(&synta::Null).map_err(SyntaErr)?;
        Ok(())
    }

    /// Encode a NULL from a PyNull object
    fn encode_null_object(&mut self, _value: &PyNull) -> PyResult<()> {
        self.encoder.encode(&synta::Null).map_err(SyntaErr)?;
        Ok(())
    }

    /// Encode a UTF8String
    ///
    /// Args:
    ///     value: The string to encode
    fn encode_utf8_string(&mut self, value: &str) -> PyResult<()> {
        let s = synta::Utf8String::new(value.to_string());
        self.encoder.encode(&s).map_err(SyntaErr)?;
        Ok(())
    }

    /// Encode a UTF8String from a PyUtf8String object
    fn encode_utf8_string_object(&mut self, value: &PyUtf8String) -> PyResult<()> {
        self.encoder.encode(&value.inner).map_err(SyntaErr)?;
        Ok(())
    }

    /// Encode a PrintableString
    ///
    /// Args:
    ///     value: The string to encode (must contain only PrintableString-valid characters)
    fn encode_printable_string(&mut self, value: &str) -> PyResult<()> {
        let s = synta::PrintableString::new(value.to_string()).map_err(|e| {
            pyo3::exceptions::PyValueError::new_err(format!("Invalid PrintableString: {:?}", e))
        })?;
        self.encoder.encode(&s).map_err(SyntaErr)?;
        Ok(())
    }

    /// Encode a PrintableString from a PyPrintableString object
    fn encode_printable_string_object(&mut self, value: &PyPrintableString) -> PyResult<()> {
        self.encoder.encode(&value.inner).map_err(SyntaErr)?;
        Ok(())
    }

    /// Encode an IA5String
    ///
    /// Args:
    ///     value: The string to encode (must be ASCII only)
    fn encode_ia5_string(&mut self, value: &str) -> PyResult<()> {
        let s = synta::IA5String::new(value.to_string()).map_err(|e| {
            pyo3::exceptions::PyValueError::new_err(format!("Invalid IA5String: {:?}", e))
        })?;
        self.encoder.encode(&s).map_err(SyntaErr)?;
        Ok(())
    }

    /// Encode an IA5String from a PyIA5String object
    fn encode_ia5_string_object(&mut self, value: &PyIA5String) -> PyResult<()> {
        self.encoder.encode(&value.inner).map_err(SyntaErr)?;
        Ok(())
    }

    /// Encode a NumericString (tag 18)
    fn encode_numeric_string(&mut self, value: &str) -> PyResult<()> {
        let s = synta::NumericString::new(value.to_string()).map_err(|e| {
            pyo3::exceptions::PyValueError::new_err(format!("Invalid NumericString: {:?}", e))
        })?;
        self.encoder.encode(&s).map_err(SyntaErr)?;
        Ok(())
    }

    /// Encode a NumericString from a PyNumericString object
    fn encode_numeric_string_object(&mut self, value: &PyNumericString) -> PyResult<()> {
        self.encoder.encode(&value.inner).map_err(SyntaErr)?;
        Ok(())
    }

    /// Encode a TeletexString / T61String (tag 20) from raw bytes
    fn encode_teletex_string(&mut self, data: &[u8]) -> PyResult<()> {
        let s = synta::TeletexString::new(data.to_vec());
        self.encoder.encode(&s).map_err(SyntaErr)?;
        Ok(())
    }

    /// Encode a TeletexString from a PyTeletexString object
    fn encode_teletex_string_object(&mut self, value: &PyTeletexString) -> PyResult<()> {
        self.encoder.encode(&value.inner).map_err(SyntaErr)?;
        Ok(())
    }

    /// Encode a VisibleString (tag 26)
    fn encode_visible_string(&mut self, value: &str) -> PyResult<()> {
        let s = synta::VisibleString::new(value.to_string()).map_err(|e| {
            pyo3::exceptions::PyValueError::new_err(format!("Invalid VisibleString: {:?}", e))
        })?;
        self.encoder.encode(&s).map_err(SyntaErr)?;
        Ok(())
    }

    /// Encode a VisibleString from a PyVisibleString object
    fn encode_visible_string_object(&mut self, value: &PyVisibleString) -> PyResult<()> {
        self.encoder.encode(&value.inner).map_err(SyntaErr)?;
        Ok(())
    }

    /// Encode a GeneralString (tag 27) from raw bytes
    fn encode_general_string(&mut self, data: &[u8]) -> PyResult<()> {
        let s = synta::GeneralString::new(data.to_vec());
        self.encoder.encode(&s).map_err(SyntaErr)?;
        Ok(())
    }

    /// Encode a GeneralString from a PyGeneralString object
    fn encode_general_string_object(&mut self, value: &PyGeneralString) -> PyResult<()> {
        self.encoder.encode(&value.inner).map_err(SyntaErr)?;
        Ok(())
    }

    /// Encode a UniversalString (tag 28)
    fn encode_universal_string(&mut self, value: &str) -> PyResult<()> {
        let s = synta::UniversalString::new(value.to_string());
        self.encoder.encode(&s).map_err(SyntaErr)?;
        Ok(())
    }

    /// Encode a UniversalString from a PyUniversalString object
    fn encode_universal_string_object(&mut self, value: &PyUniversalString) -> PyResult<()> {
        self.encoder.encode(&value.inner).map_err(SyntaErr)?;
        Ok(())
    }

    /// Encode a BMPString (tag 30)
    ///
    /// Raises ValueError if the string contains code points outside the BMP (> U+FFFF).
    fn encode_bmp_string(&mut self, value: &str) -> PyResult<()> {
        let s = synta::BmpString::new(value.to_string()).map_err(|e| {
            pyo3::exceptions::PyValueError::new_err(format!("Invalid BMPString: {:?}", e))
        })?;
        self.encoder.encode(&s).map_err(SyntaErr)?;
        Ok(())
    }

    /// Encode a BMPString from a PyBmpString object
    fn encode_bmp_string_object(&mut self, value: &PyBmpString) -> PyResult<()> {
        self.encoder.encode(&value.inner).map_err(SyntaErr)?;
        Ok(())
    }

    /// Wrap pre-encoded bytes in a SEQUENCE TLV (tag 0x30) and append to the output.
    ///
    /// Use this to build SEQUENCE structures: encode the inner elements into a
    /// separate Encoder, call ``finish()`` to get the inner bytes, then pass those
    /// bytes to ``encode_sequence()`` on the outer Encoder.
    ///
    /// Example::
    ///
    ///     inner = synta.Encoder(synta.Encoding.DER)
    ///     inner.encode_integer(42)
    ///     inner.encode_boolean(True)
    ///     outer = synta.Encoder(synta.Encoding.DER)
    ///     outer.encode_sequence(inner.finish())
    ///     result = outer.finish()
    fn encode_sequence(&mut self, inner_bytes: &[u8]) -> PyResult<()> {
        use synta::tag::TAG_SEQUENCE;
        self.encoder
            .write_tag(synta::Tag::universal_constructed(TAG_SEQUENCE))
            .map_err(SyntaErr)?;
        self.encoder
            .write_length(inner_bytes.len())
            .map_err(SyntaErr)?;
        self.encoder.write_bytes(inner_bytes);
        Ok(())
    }

    /// Wrap pre-encoded bytes in a SET TLV (tag 0x31) and append to the output.
    fn encode_set(&mut self, inner_bytes: &[u8]) -> PyResult<()> {
        use synta::tag::TAG_SET;
        self.encoder
            .write_tag(synta::Tag::universal_constructed(TAG_SET))
            .map_err(SyntaErr)?;
        self.encoder
            .write_length(inner_bytes.len())
            .map_err(SyntaErr)?;
        self.encoder.write_bytes(inner_bytes);
        Ok(())
    }

    /// Wrap pre-encoded bytes with an explicit context tag ``[tag_num]`` and append
    /// to the output.
    ///
    /// ``tag_class`` must be one of ``"Context"`` (default for ``[N]`` notation),
    /// ``"Application"``, or ``"Private"``.
    ///
    /// Example — encode ``[1] EXPLICIT SEQUENCE { ... }``::
    ///
    ///     enc.encode_explicit_tag(1, "Context", sequence_bytes)
    fn encode_explicit_tag(
        &mut self,
        tag_num: u32,
        tag_class: &str,
        inner_bytes: &[u8],
    ) -> PyResult<()> {
        use pyo3::exceptions::PyValueError;
        use synta::tag::TagClass;

        let class = match tag_class {
            "Context" => TagClass::ContextSpecific,
            "Application" => TagClass::Application,
            "Private" => TagClass::Private,
            other => {
                return Err(PyValueError::new_err(format!(
                    "Unknown tag class '{}'; expected 'Context', 'Application', or 'Private'",
                    other
                )))
            }
        };
        // Explicit tags are always constructed (they wrap another TLV)
        let tag = synta::Tag::new(class, true, tag_num);
        self.encoder.write_tag(tag).map_err(SyntaErr)?;
        self.encoder
            .write_length(inner_bytes.len())
            .map_err(SyntaErr)?;
        self.encoder.write_bytes(inner_bytes);
        Ok(())
    }

    /// Wrap pre-encoded value bytes with an implicit tag and append to the output.
    ///
    /// For implicit tagging, the original type tag is replaced with the given
    /// tag; the value bytes (the content, *not* the full original TLV) are
    /// written as-is.  Set ``is_constructed=True`` when the underlying type is
    /// a SEQUENCE, SET, or other constructed type.
    ///
    /// ``tag_class`` must be one of ``"Context"`` (default for ``[N]`` notation),
    /// ``"Application"``, or ``"Private"``.
    ///
    /// Example — encode ``[1] IMPLICIT INTEGER`` with value bytes ``b'\\x2a'``:
    ///
    ///     enc.encode_implicit_tag(1, "Context", False, b'\\x2a')
    fn encode_implicit_tag(
        &mut self,
        tag_num: u32,
        tag_class: &str,
        is_constructed: bool,
        value_bytes: &[u8],
    ) -> PyResult<()> {
        use pyo3::exceptions::PyValueError;
        use synta::tag::TagClass;

        let class = match tag_class {
            "Context" => TagClass::ContextSpecific,
            "Application" => TagClass::Application,
            "Private" => TagClass::Private,
            other => {
                return Err(PyValueError::new_err(format!(
                    "Unknown tag class '{other}'; expected 'Context', 'Application', or 'Private'",
                )))
            }
        };
        let tag = synta::Tag::new(class, is_constructed, tag_num);
        self.encoder.write_tag(tag).map_err(SyntaErr)?;
        self.encoder
            .write_length(value_bytes.len())
            .map_err(SyntaErr)?;
        self.encoder.write_bytes(value_bytes);
        Ok(())
    }

    /// Finish encoding and return the encoded bytes
    ///
    /// Returns:
    ///     The encoded ASN.1 data as bytes
    fn finish<'py>(&mut self, py: Python<'py>) -> PyResult<Bound<'py, pyo3::types::PyBytes>> {
        // Capture encoding before the move so the replacement uses the same rules.
        let encoding = self.encoder.encoding();
        let encoder = std::mem::replace(&mut self.encoder, Encoder::new(encoding));
        let bytes = encoder.finish().map_err(SyntaErr)?;
        Ok(pyo3::types::PyBytes::new(py, &bytes))
    }

    fn __repr__(&self) -> String {
        format!("Encoder(encoding={:?})", self.encoder.encoding())
    }
}