synta-python 0.3.0

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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
//! Python wrappers for primitive ASN.1 types: INTEGER, OCTET STRING, BIT STRING,
//! BOOLEAN, UTCTime, GeneralizedTime, REAL, NULL.

use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};

use pyo3::exceptions::{PyOverflowError, PyValueError};
use pyo3::prelude::*;
use pyo3::types::PyBytes;

use synta::{
    BitString, Boolean, FromDer, GeneralizedTime, Integer, Null, OctetString, Real, ToDer, UtcTime,
};

use crate::error::SyntaErr;

/// Python wrapper for ASN.1 INTEGER
#[pyclass(name = "Integer")]
#[derive(Debug, Clone)]
pub struct PyInteger {
    pub(crate) inner: Integer,
}

#[pymethods]
impl PyInteger {
    /// Create a new Integer from a Python int
    #[new]
    fn new(value: i64) -> Self {
        Self {
            inner: Integer::from_i64(value),
        }
    }

    /// Convert to Python int (i64)
    fn to_int(&self) -> PyResult<i64> {
        self.inner
            .as_i64()
            .map_err(|_| PyOverflowError::new_err("Integer too large for i64"))
    }

    /// Get the raw bytes (big-endian two's complement)
    fn to_bytes<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        PyBytes::new(py, self.inner.as_bytes())
    }

    /// Create Integer from raw bytes
    #[staticmethod]
    fn from_bytes(bytes: &[u8]) -> Self {
        Self {
            inner: Integer::from_bytes(bytes),
        }
    }

    /// Create Integer from an unsigned 64-bit value
    #[staticmethod]
    fn from_u64(value: u64) -> Self {
        Self {
            inner: Integer::from_u64(value),
        }
    }

    /// Return the DER encoding of this ``Integer``.
    fn to_der<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
        Ok(PyBytes::new(py, &self.inner.to_der().map_err(SyntaErr)?))
    }

    /// Parse a DER-encoded ``Integer``.
    ///
    /// :raises ValueError: if the bytes cannot be decoded.
    #[staticmethod]
    fn from_der(data: &[u8]) -> PyResult<Self> {
        let inner = Integer::from_der(data).map_err(SyntaErr)?;
        Ok(Self { inner })
    }

    /// Convert to Python int (i128) for larger integers
    fn to_i128(&self) -> PyResult<i128> {
        self.inner
            .as_i128()
            .map_err(|_| PyOverflowError::new_err("Integer too large for i128"))
    }

    fn __eq__(&self, other: &Self) -> bool {
        // DER encodes integers with minimal bytes (no redundant leading zeros),
        // so comparing the raw bytes is equivalent to comparing by value.
        self.inner.as_bytes() == other.inner.as_bytes()
    }

    fn __hash__(&self) -> u64 {
        let mut h = DefaultHasher::new();
        self.inner.as_bytes().hash(&mut h);
        h.finish()
    }

    fn __repr__(&self) -> PyResult<String> {
        match self.inner.as_i64() {
            Ok(val) => Ok(format!("Integer({})", val)),
            Err(_) => Ok(format!("Integer(<{} bytes>)", self.inner.as_bytes().len())),
        }
    }

    fn __str__(&self) -> PyResult<String> {
        match self.inner.as_i64() {
            Ok(val) => Ok(val.to_string()),
            Err(_) => Ok(format!("<integer {} bytes>", self.inner.as_bytes().len())),
        }
    }
}

/// Python wrapper for ASN.1 OCTET STRING
#[pyclass(name = "OctetString")]
#[derive(Debug, Clone)]
pub struct PyOctetString {
    pub(crate) inner: OctetString,
}

#[pymethods]
impl PyOctetString {
    /// Create a new OctetString from bytes
    #[new]
    fn new(data: Vec<u8>) -> Self {
        Self {
            inner: OctetString::new(data),
        }
    }

    /// Get the bytes as a Python bytes object
    fn to_bytes<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        PyBytes::new(py, self.inner.as_bytes())
    }

    /// Get the length
    fn __len__(&self) -> usize {
        self.inner.as_bytes().len()
    }

    fn __eq__(&self, other: &Self) -> bool {
        self.inner == other.inner
    }

    fn __repr__(&self) -> String {
        format!("OctetString(<{} bytes>)", self.inner.as_bytes().len())
    }

    /// Return the DER encoding of this ``OctetString``.
    fn to_der<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
        Ok(PyBytes::new(py, &self.inner.to_der().map_err(SyntaErr)?))
    }

    /// Parse a DER-encoded ``OctetString``.
    ///
    /// :raises ValueError: if the bytes cannot be decoded.
    #[staticmethod]
    fn from_der(data: &[u8]) -> PyResult<Self> {
        let inner = OctetString::from_der(data).map_err(SyntaErr)?;
        Ok(Self { inner })
    }
}

/// Python wrapper for ASN.1 BIT STRING
#[pyclass(name = "BitString")]
#[derive(Debug, Clone)]
pub struct PyBitString {
    pub(crate) inner: BitString,
}

#[pymethods]
impl PyBitString {
    /// Create a new BitString from bytes and unused bits count
    #[new]
    fn new(data: Vec<u8>, unused_bits: u8) -> PyResult<Self> {
        if unused_bits > 7 {
            return Err(PyValueError::new_err("unused_bits must be 0-7"));
        }
        let inner = BitString::new(data, unused_bits)
            .map_err(|e| PyValueError::new_err(format!("Invalid BitString: {:?}", e)))?;
        Ok(Self { inner })
    }

    /// Get the bytes
    fn to_bytes<'py>(&self, py: Python<'py>) -> Bound<'py, PyBytes> {
        PyBytes::new(py, self.inner.as_bytes())
    }

    /// Get the number of unused bits in the last byte
    fn unused_bits(&self) -> u8 {
        self.inner.unused_bits()
    }

    /// Get the number of bits
    fn bit_len(&self) -> usize {
        self.inner.bit_len()
    }

    fn __len__(&self) -> usize {
        self.inner.bit_len()
    }

    fn __eq__(&self, other: &Self) -> bool {
        self.inner == other.inner
    }

    fn __repr__(&self) -> String {
        format!(
            "BitString(<{} bits, {} unused>)",
            self.inner.bit_len(),
            self.inner.unused_bits()
        )
    }

    /// Return the DER encoding of this ``BitString``.
    fn to_der<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
        Ok(PyBytes::new(py, &self.inner.to_der().map_err(SyntaErr)?))
    }

    /// Parse a DER-encoded ``BitString``.
    ///
    /// :raises ValueError: if the bytes cannot be decoded.
    #[staticmethod]
    fn from_der(data: &[u8]) -> PyResult<Self> {
        let inner = BitString::from_der(data).map_err(SyntaErr)?;
        Ok(Self { inner })
    }
}

/// Python wrapper for ASN.1 BOOLEAN
#[pyclass(name = "Boolean")]
#[derive(Debug, Clone, Copy)]
pub struct PyBoolean {
    pub(crate) inner: Boolean,
}

#[pymethods]
impl PyBoolean {
    /// Create a new Boolean
    #[new]
    fn new(value: bool) -> Self {
        Self {
            inner: Boolean::new(value),
        }
    }

    /// Get the boolean value
    fn value(&self) -> bool {
        self.inner.value()
    }

    fn __bool__(&self) -> bool {
        self.inner.value()
    }

    fn __eq__(&self, other: &Self) -> bool {
        self.inner.value() == other.inner.value()
    }

    fn __hash__(&self) -> isize {
        // Matches Python's hash(True) == 1, hash(False) == 0.
        self.inner.value() as isize
    }

    fn __repr__(&self) -> String {
        format!("Boolean({})", self.inner.value())
    }

    /// Return the DER encoding of this ``Boolean``.
    #[allow(clippy::wrong_self_convention)]
    fn to_der<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
        Ok(PyBytes::new(py, &self.inner.to_der().map_err(SyntaErr)?))
    }

    /// Parse a DER-encoded ``Boolean``.
    ///
    /// :raises ValueError: if the bytes cannot be decoded.
    #[staticmethod]
    fn from_der(data: &[u8]) -> PyResult<Self> {
        let inner = Boolean::from_der(data).map_err(SyntaErr)?;
        Ok(Self { inner })
    }
}

/// Python wrapper for ASN.1 UTCTime
#[pyclass(name = "UtcTime")]
#[derive(Debug, Clone)]
pub struct PyUtcTime {
    pub(crate) inner: UtcTime,
}

#[pymethods]
impl PyUtcTime {
    /// Create a new UTCTime (year must be in 1950-2049 range)
    #[new]
    fn new(year: u16, month: u8, day: u8, hour: u8, minute: u8, second: u8) -> PyResult<Self> {
        let inner = UtcTime::new(year, month, day, hour, minute, second)
            .map_err(|e| PyValueError::new_err(format!("Invalid UTCTime: {:?}", e)))?;
        Ok(Self { inner })
    }

    /// Four-digit year (1950–2049).
    #[getter]
    fn year(&self) -> u16 {
        self.inner.year
    }

    /// Month (1–12).
    #[getter]
    fn month(&self) -> u8 {
        self.inner.month
    }

    /// Day of month (1–31).
    #[getter]
    fn day(&self) -> u8 {
        self.inner.day
    }

    /// Hour (0–23).
    #[getter]
    fn hour(&self) -> u8 {
        self.inner.hour
    }

    /// Minute (0–59).
    #[getter]
    fn minute(&self) -> u8 {
        self.inner.minute
    }

    /// Second (0–59).
    #[getter]
    fn second(&self) -> u8 {
        self.inner.second
    }

    fn __str__(&self) -> String {
        self.inner.to_string()
    }

    fn __repr__(&self) -> String {
        format!("UtcTime('{}')", self.inner)
    }

    /// Return the DER encoding of this ``UtcTime``.
    fn to_der<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
        Ok(PyBytes::new(py, &self.inner.to_der().map_err(SyntaErr)?))
    }

    /// Parse a DER-encoded ``UtcTime``.
    ///
    /// :raises ValueError: if the bytes cannot be decoded.
    #[staticmethod]
    fn from_der(data: &[u8]) -> PyResult<Self> {
        let inner = UtcTime::from_der(data).map_err(SyntaErr)?;
        Ok(Self { inner })
    }
}

impl std::fmt::Display for PyUtcTime {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.inner)
    }
}

/// Python wrapper for ASN.1 GeneralizedTime
#[pyclass(name = "GeneralizedTime")]
#[derive(Debug, Clone)]
pub struct PyGeneralizedTime {
    pub(crate) inner: GeneralizedTime,
}

#[pymethods]
impl PyGeneralizedTime {
    /// Create a new GeneralizedTime
    ///
    /// Args:
    ///     milliseconds: Optional fractional seconds in milliseconds (0-999)
    #[new]
    fn new(
        year: u16,
        month: u8,
        day: u8,
        hour: u8,
        minute: u8,
        second: u8,
        milliseconds: Option<u16>,
    ) -> PyResult<Self> {
        let inner = GeneralizedTime::new(year, month, day, hour, minute, second, milliseconds)
            .map_err(|e| PyValueError::new_err(format!("Invalid GeneralizedTime: {:?}", e)))?;
        Ok(Self { inner })
    }

    /// Four-digit year.
    #[getter]
    fn year(&self) -> u16 {
        self.inner.year
    }

    /// Month (1–12).
    #[getter]
    fn month(&self) -> u8 {
        self.inner.month
    }

    /// Day of month (1–31).
    #[getter]
    fn day(&self) -> u8 {
        self.inner.day
    }

    /// Hour (0–23).
    #[getter]
    fn hour(&self) -> u8 {
        self.inner.hour
    }

    /// Minute (0–59).
    #[getter]
    fn minute(&self) -> u8 {
        self.inner.minute
    }

    /// Second (0–59).
    #[getter]
    fn second(&self) -> u8 {
        self.inner.second
    }

    /// Fractional seconds expressed as whole milliseconds (0–999), or ``None``.
    #[getter]
    fn milliseconds(&self) -> Option<u16> {
        self.inner.milliseconds
    }

    fn __str__(&self) -> String {
        self.inner.to_string()
    }

    fn __repr__(&self) -> String {
        format!("GeneralizedTime('{}')", self.inner)
    }

    /// Return the DER encoding of this ``GeneralizedTime``.
    fn to_der<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
        Ok(PyBytes::new(py, &self.inner.to_der().map_err(SyntaErr)?))
    }

    /// Parse a DER-encoded ``GeneralizedTime``.
    ///
    /// :raises ValueError: if the bytes cannot be decoded.
    #[staticmethod]
    fn from_der(data: &[u8]) -> PyResult<Self> {
        let inner = GeneralizedTime::from_der(data).map_err(SyntaErr)?;
        Ok(Self { inner })
    }
}

impl std::fmt::Display for PyGeneralizedTime {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.inner)
    }
}

/// Python wrapper for ASN.1 REAL
#[pyclass(name = "Real")]
#[derive(Debug, Clone, Copy)]
pub struct PyReal {
    pub(crate) inner: Real,
}

#[pymethods]
impl PyReal {
    /// Create a new Real from a Python float
    #[new]
    fn new(value: f64) -> Self {
        Self {
            inner: Real::new(value),
        }
    }

    /// Get the f64 value
    fn value(&self) -> f64 {
        self.inner.value()
    }

    /// Return True if this is positive infinity
    fn is_infinite(&self) -> bool {
        self.inner.value().is_infinite()
    }

    /// Return True if this is NaN (not-a-number)
    fn is_nan(&self) -> bool {
        self.inner.value().is_nan()
    }

    /// Return True if the value is finite
    fn is_finite(&self) -> bool {
        self.inner.value().is_finite()
    }

    fn __float__(&self) -> f64 {
        self.inner.value()
    }

    fn __repr__(&self) -> String {
        format!("Real({})", self.inner.value())
    }

    fn __str__(&self) -> String {
        self.inner.value().to_string()
    }

    fn __eq__(&self, other: &Self) -> bool {
        // NaN != NaN by IEEE 754 — mirror Python float behaviour
        self.inner.value() == other.inner.value()
    }

    fn __hash__(&self, py: Python<'_>) -> PyResult<isize> {
        // Delegate to Python's float.__hash__ so that hash(Real(1.0)) == hash(1.0) == hash(1),
        // matching the Python data model guarantee for numeric types.
        self.inner.value().into_pyobject(py)?.hash()
    }

    /// Return the DER encoding of this ``Real``.
    #[allow(clippy::wrong_self_convention)]
    fn to_der<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
        Ok(PyBytes::new(py, &self.inner.to_der().map_err(SyntaErr)?))
    }

    /// Parse a DER-encoded ``Real``.
    ///
    /// :raises ValueError: if the bytes cannot be decoded.
    #[staticmethod]
    fn from_der(data: &[u8]) -> PyResult<Self> {
        let inner = Real::from_der(data).map_err(SyntaErr)?;
        Ok(Self { inner })
    }
}

/// Python wrapper for ASN.1 NULL
#[pyclass(name = "Null")]
#[derive(Debug, Clone, Copy)]
pub struct PyNull;

#[pymethods]
impl PyNull {
    /// Create a ``Null`` value.
    #[new]
    fn new() -> Self {
        Self
    }

    fn __repr__(&self) -> String {
        "Null()".to_string()
    }

    fn __eq__(&self, _other: &Self) -> bool {
        true
    }

    fn __hash__(&self) -> isize {
        // All Null values are equal; use a fixed hash consistent with __eq__.
        0
    }

    /// Return the DER encoding of this ``Null``.
    #[allow(clippy::wrong_self_convention)]
    fn to_der<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyBytes>> {
        Ok(PyBytes::new(py, &Null.to_der().map_err(SyntaErr)?))
    }

    /// Parse a DER-encoded ``Null``.
    ///
    /// :raises ValueError: if the bytes cannot be decoded.
    #[staticmethod]
    fn from_der(data: &[u8]) -> PyResult<Self> {
        Null::from_der(data).map_err(SyntaErr)?;
        Ok(Self)
    }
}