Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Quick Start

After installing the package, import synta and start decoding or encoding ASN.1 data.

Decode a single element

import synta

# Decode an INTEGER
data = b'\x02\x01\x2A'  # DER-encoded INTEGER 42
decoder = synta.Decoder(data, synta.Encoding.DER)
integer = decoder.decode_integer()
print(integer.to_int())  # Output: 42

# Decode an OBJECT IDENTIFIER
oid_data = b'\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01\x01'
decoder = synta.Decoder(oid_data, synta.Encoding.DER)
oid = decoder.decode_oid()
print(str(oid))  # Output: 1.2.840.113549.1.1.1

# Decode an OCTET STRING
octet_data = b'\x04\x05hello'
decoder = synta.Decoder(octet_data, synta.Encoding.DER)
octet_string = decoder.decode_octet_string()
print(octet_string.to_bytes())  # Output: b'hello'

Encode a single element

import synta

# Encode an INTEGER
encoder = synta.Encoder(synta.Encoding.DER)
encoder.encode_integer(42)
output = encoder.finish()
print(output.hex())  # Output: 02012a

# Encode an OCTET STRING
encoder = synta.Encoder(synta.Encoding.DER)
encoder.encode_octet_string(b'hello')
output = encoder.finish()
print(output.hex())  # Output: 040568656c6c6f

Encode a SEQUENCE

Encode inner elements into a separate Encoder, then wrap the result in a SEQUENCE using an outer Encoder.

import synta

# Build SEQUENCE { INTEGER 42, BOOLEAN TRUE }
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()
# result == b'\x30\x06\x02\x01\x2a\x01\x01\xff'

Decode a SEQUENCE

Use decode_sequence() to enter a SEQUENCE and get a child Decoder positioned over the content bytes.

import synta

# Encoded SEQUENCE { INTEGER 42, BOOLEAN TRUE }
data = b'\x30\x06\x02\x01\x2a\x01\x01\xff'

decoder = synta.Decoder(data, synta.Encoding.DER)
child = decoder.decode_sequence()    # advances past the outer SEQUENCE TLV
assert decoder.is_empty()

while not child.is_empty():
    obj = child.decode_any()         # INTEGER, then BOOLEAN

Parse an X.509 certificate

import synta

with open('cert.der', 'rb') as f:
    cert = synta.Certificate.from_der(f.read())

print(cert.subject)            # RFC 4514-style DN string
print(cert.issuer)
print(cert.not_before, "–", cert.not_after)
print(cert.signature_algorithm)

See Certificate for the full property list.