x690

1.0.0.post1 · active · verified Thu Apr 16

x690 is a pure Python library that implements the X.690 standard for Basic Encoding Rules (BER) encoding and decoding of ASN.1 data structures. It provides functionalities to encode Python objects into BER-encoded bytes and decode BER-encoded bytes back into Python objects. The current version is 1.0.0.post1, with the last update in September 2022, suggesting a stable but infrequently updated codebase.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to encode basic X.690 types like Integer and Sequence into bytes, and how to decode BER-encoded bytes back into Python objects using the `decode` function. It also shows how to use `pretty()` for human-readable output and how to leverage `expected_type` for type validation during decoding.

import x690.types as t
from x690 import decode

# 1. Encoding a value
my_integer = t.Integer(123)
encoded_bytes = bytes(my_integer)
print(f"Encoded Integer: {encoded_bytes.hex()}")

# 2. Encoding a composite value (Sequence)
my_sequence = t.Sequence([t.Integer(1), t.OctetString(b'hello')])
encoded_sequence_bytes = bytes(my_sequence)
print(f"Encoded Sequence: {encoded_sequence_bytes.hex()}")

# 3. Decoding bytes
decoded_value, next_offset = decode(encoded_bytes)
print(f"Decoded value: {decoded_value.pyvalue} (Type: {type(decoded_value).__name__})")

# 4. Decoding a sequence (multiple values)
data_to_decode = b'0\x06\x02\x01\x01\x04\x01a'
decoded_obj_1, offset_1 = decode(data_to_decode)
decoded_obj_2, offset_2 = decode(data_to_decode, offset_1)
print(f"Decoded obj 1: {decoded_obj_1.pretty()}")
print(f"Decoded obj 2: {decoded_obj_2.pretty()}")

# 5. Decoding with an expected type (optional but good for type checking)
# This helps ensure the decoded type matches expectations and aids type checkers.
from x690.exc import UnexpectedType
try:
    expected_int_value, _ = decode(encoded_bytes, expected_type=t.Integer)
    print(f"Decoded with expected type: {expected_int_value.pyvalue}")
    # This would raise UnexpectedType if encoded_bytes was not an Integer
    # decode(encoded_bytes, expected_type=t.OctetString) 
except UnexpectedType as e:
    print(f"Error decoding with unexpected type: {e}")

view raw JSON →