asn1tools

0.167.0 · active · verified Mon Apr 13

asn1tools is a Python package for ASN.1 parsing, encoding, and decoding. It provides functionality to compile ASN.1 specifications and then encode and decode data using various encoding rules such as Basic Encoding Rules (BER), Distinguished Encoding Rules (DER), Packed Encoding Rules (PER), Unaligned Packed Encoding Rules (UPER), and XML Encoding Rules (XER), among others. The library is currently at version 0.167.0 and is actively maintained with frequent releases addressing bug fixes and performance improvements.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to compile an ASN.1 specification from a file, then encode Python dictionaries into ASN.1 binary format using the BER codec, and decode the binary data back into Python dictionaries.

import asn1tools
import os
import tempfile

# Define an example ASN.1 specification
asn1_spec = """
Foo DEFINITIONS ::= BEGIN
  Question ::= SEQUENCE {
    id        INTEGER,
    question  IA5String
  }
  Answer ::= SEQUENCE {
    id      INTEGER,
    answer  BOOLEAN
  }
END
"""

# Create a temporary .asn file for the specification
with tempfile.NamedTemporaryFile(mode='w', suffix='.asn', delete=False) as f:
    f.write(asn1_spec)
    asn_filepath = f.name

try:
    # Compile the ASN.1 specification using the default BER codec
    # You can specify other codecs like 'per', 'uper', 'xer', etc.
    foo = asn1tools.compile_files(asn_filepath, 'ber')

    # Encode a Question message
    question_data = {'id': 1, 'question': 'Is 1+1=3?'}
    encoded_question = foo.encode('Question', question_data)

    print(f"Encoded (BER): {encoded_question.hex()}")

    # Decode the Question message
    decoded_question = foo.decode('Question', encoded_question)

    print(f"Decoded: {decoded_question}")

    # Example with another message type (Answer)
    answer_data = {'id': 1, 'answer': False}
    encoded_answer = foo.encode('Answer', answer_data)
    print(f"Encoded Answer (BER): {encoded_answer.hex()}")
    decoded_answer = foo.decode('Answer', encoded_answer)
    print(f"Decoded Answer: {decoded_answer}")

finally:
    # Clean up the temporary file
    os.remove(asn_filepath)

view raw JSON →