How to use the asn1crypto.core function in asn1crypto

To help you get started, we’ve selected a few asn1crypto examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github wbond / asn1crypto / tests / test_core.py View on Github external
class ApplicationTaggedInner(core.Sequence):
    """
    TESTCASE DEFINITIONS EXPLICIT TAGS ::=
    BEGIN

    INNERSEQ ::= SEQUENCE {
        innernumber       [21] INTEGER
    }

    INNER ::= [APPLICATION 20] INNERSEQ
    """

    explicit = (1, 20)

    _fields = [
        ('innernumber', core.Integer, {'explicit': 21}),
    ]


class ApplicationTaggedOuter(core.Sequence):
    """
    OUTERSEQ ::= SEQUENCE {
        outernumber  [11] INTEGER,
        inner        [12] INNER
    }

    OUTER ::= [APPLICATION 10] OUTERSEQ
    END
    """

    explicit = (1, 10)
github wbond / asn1crypto / tests / test_core.py View on Github external
def test_large_tag_encode(self):
        # https://misc.daniel-marschall.de/asn.1/oid_facts.html
        v = core.Primitive(tag=31, contents=b'')
        self.assertEqual(b'\x1f\x1f\x00', v.dump())

        v = core.Primitive(tag=36, contents=b'')
        self.assertEqual(b'\x1f\x24\x00', v.dump())

        # One extra byte
        v = core.Primitive(
            class_="application",
            method="constructed",
            tag=73,
            contents=b''
        )
        self.assertEqual(b'\x7f\x49\x00', v.dump())

        # Two extra bytes
        v = core.Primitive(
            class_="application",
            method="constructed",
            tag=201,
github wbond / asn1crypto / tests / test_core.py View on Github external
('one', core.Integer, {'tag_type': 'implicit', 'tag': 1}),
    ]


class SetTestOldApi(core.Set):
    _fields = [
        ('two', core.Integer, {'implicit': 2}),
        ('one', core.Integer, {'implicit': 1}),
    ]


class SetOfTest(core.SetOf):
    _child_spec = core.Integer


class ConcatTest(core.Concat):
    _child_specs = [Seq, core.Integer]


class IntegerConcats(core.Concat):
    _child_specs = [core.Integer, core.Integer]


class MyOids(core.ObjectIdentifier):
    _map = {
        '1.2.3': 'abc',
        '4.5.6': 'def',
    }


class ApplicationTaggedInteger(core.Integer):
    # This class attribute may be a 2-element tuple of integers,
github wbond / asn1crypto / tests / test_core.py View on Github external
self.assertEqual(False, v2._indefinite)
        self.assertEqual(4, v2.native)
        self.assertEqual(b'\x04\x01\x04', v2.dump())

        v = core.ParsableOctetString.load(b'\x24\x80\x04\x03\x02\x01\x04\x00\x00')
        self.assertEqual(4, v.parsed.native)
        self.assertEqual(True, v._indefinite)
        v2 = v.copy()
        self.assertEqual(0, v2.method)
        self.assertEqual(4, v2.tag)
        self.assertEqual(False, v2._indefinite)
        self.assertEqual(4, v2.parsed.native)
        self.assertEqual(b'\x02\x01\x04', v2.__bytes__())
        self.assertEqual(b'\x04\x03\x02\x01\x04', v2.dump())

        v = core.UTF8String.load(b'\x2C\x80\x0C\x03foo\x00\x00')
        self.assertEqual(True, v._indefinite)
        v2 = v.copy()
        self.assertEqual(0, v2.method)
        self.assertEqual(12, v2.tag)
        self.assertEqual(False, v2._indefinite)
        self.assertEqual('foo', v2.native)
        self.assertEqual(b'\x0C\x03foo', v2.dump())
github theupdateframework / tuf / tests / test_asn1_convert.py View on Github external
def test_baseline(self):
    """
    Fail if basic asn1crypto functionality is broken.
    Use Integer and VisibleString.
    """

    i = asn1_core.Integer(5)
    self.assertEqual(5, i.native)

    i_der = i.dump()
    self.assertEqual(b'\x02\x01\x05', i_der)

    # Convert back and test.
    self.assertEqual(5, asn1_core.load(i_der).native)
    self.assertEqual(5, asn1_core.Integer.load(i_der).native)


    s = 'testword'
    expected_der_of_string = b'\x1a\x08testword'

    s_asn1 = asn1_core.VisibleString(s)
    self.assertEqual(s, s_asn1.native)
github snowflakedb / snowflake-connector-python / tool / dump_ocsp_response_cache.py View on Github external
def custom_key(k):
        # third element is Serial Number for the subject
        serial_number = core.Integer.load(k[2])
        return int(serial_number.native)
github theupdateframework / tuf / tuf / encoding / asn1_convert.py View on Github external
def is_structlike_datatype(datatype):
  """
  True if provided datatype has attribute _fields and is either a subclass of
  Sequence or Set.

  Raises ValueError if datatype is not a type.

  See module docstring and to_asn1 docstring for discussions of list-like and
  struct-like ASN.1 objects.
  """
  check_datatype(datatype)

  if hasattr(datatype, '_fields') and (
      issubclass(datatype, asn1_core.Sequence)
      or issubclass(datatype, asn1_core.Set)):

    # Sanity check to make sure definition for a structlike dict doesn't set
    # _from_listlike_dict.
    if (hasattr(datatype, '_from_listlike_dict')
        and datatype._from_listlike_dict):
      # TODO: Decide on an appropriate exception class.
      raise Exception('Definition for class ' + str(datatype) + ' appears to '
          'incorrectly set _from_listlike_dict, even though it is a '
          'struct-like asn1crypto object.')

    return True

  else:
    return False
github theupdateframework / tuf / tuf / encoding / asn1_metadata_definitions.py View on Github external
containing key-value pairs. For example, see RoleLongInfoContainers in
    Timestamp metadata, or Hashes. Look for _from_listlike_dict below for more
    examples.
"""

import asn1crypto.core as ac


# Common types, for use in the various metadata types

# Normally, one would use SequenceOf in place, rather than define a class
# for each type of SequenceOf that we want to use, but, for now, the way we
# parse these definitions chokes on those sorts of definitions, so we'll just
# create a class for each type of SequenceOf we need.
class OctetStrings(ac.SequenceOf):  # Hopefully temporary
  _child_spec = ac.OctetString
class VisibleStrings(ac.SequenceOf): # Hopefully temporary
  _child_spec = ac.VisibleString



class Signature(ac.Sequence):
  _fields = [
      ('keyid', ac.OctetString),
      ('sig', ac.OctetString)]


class Signatures(ac.SequenceOf):
  _child_spec = Signature


class Hash(ac.Sequence):
github theupdateframework / tuf / tuf / encoding / asn1_convert.py View on Github external
an asn1 representation of this:
            {'0':     b'1234...', '1':      'rsa...', '2':     'abcd...'}
          instead of an asn1 representation of this:
            {'keyid': b'1234...', 'method': 'rsa...', 'value': 'abcd...'}

  """
  # Make sure der_obj is bytes or bytes-like:
  if not hasattr(der_obj, 'decode'):
    raise TypeError(
        'asn1_from_der expects argument der_obj to be a bytes or bytes-like '
        'object, providing method "decode".  Provided object has no "decode" '
        'method.  der_obj is of type: ' + str(type(der_obj)))

  if datatype is None:
    # Generic load DER as asn1
    return asn1_core.load(der_obj)

  else:
    # Load DER as asn1, interpreting it as a particular structure.
    return datatype.load(der_obj)
github wbond / ocspbuilder / ocspbuilder / __init__.py View on Github external
)

        if not single_response_extensions:
            single_response_extensions = None

        responder_key_hash = getattr(responder_certificate.public_key, self._key_hash_algo)

        if self._certificate_status == 'good':
            cert_status = ocsp.CertStatus(
                name='good',
                value=core.Null()
            )
        elif self._certificate_status == 'unknown':
            cert_status = ocsp.CertStatus(
                name='unknown',
                value=core.Null()
            )
        else:
            status = self._certificate_status
            reason = status if status != 'revoked' else 'unspecified'
            cert_status = ocsp.CertStatus(
                name='revoked',
                value={
                    'revocation_time': self._revocation_date,
                    'revocation_reason': reason,
                }
            )

        issuer = self._certificate_issuer if self._certificate_issuer else responder_certificate
        if issuer.subject != self._certificate.issuer:
            raise ValueError(_pretty_message(
                '''