encoder.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. #
  2. # This file is part of pyasn1 software.
  3. #
  4. # Copyright (c) 2005-2020, Ilya Etingof <etingof@gmail.com>
  5. # License: https://pyasn1.readthedocs.io/en/latest/license.html
  6. #
  7. from collections import OrderedDict
  8. import warnings
  9. from pyasn1 import debug
  10. from pyasn1 import error
  11. from pyasn1.compat import _MISSING
  12. from pyasn1.type import base
  13. from pyasn1.type import char
  14. from pyasn1.type import tag
  15. from pyasn1.type import univ
  16. from pyasn1.type import useful
  17. __all__ = ['encode']
  18. LOG = debug.registerLoggee(__name__, flags=debug.DEBUG_ENCODER)
  19. class AbstractItemEncoder(object):
  20. def encode(self, value, encodeFun, **options):
  21. raise error.PyAsn1Error('Not implemented')
  22. class BooleanEncoder(AbstractItemEncoder):
  23. def encode(self, value, encodeFun, **options):
  24. return bool(value)
  25. class IntegerEncoder(AbstractItemEncoder):
  26. def encode(self, value, encodeFun, **options):
  27. return int(value)
  28. class BitStringEncoder(AbstractItemEncoder):
  29. def encode(self, value, encodeFun, **options):
  30. return str(value)
  31. class OctetStringEncoder(AbstractItemEncoder):
  32. def encode(self, value, encodeFun, **options):
  33. return value.asOctets()
  34. class TextStringEncoder(AbstractItemEncoder):
  35. def encode(self, value, encodeFun, **options):
  36. return str(value)
  37. class NullEncoder(AbstractItemEncoder):
  38. def encode(self, value, encodeFun, **options):
  39. return None
  40. class ObjectIdentifierEncoder(AbstractItemEncoder):
  41. def encode(self, value, encodeFun, **options):
  42. return str(value)
  43. class RelativeOIDEncoder(AbstractItemEncoder):
  44. def encode(self, value, encodeFun, **options):
  45. return str(value)
  46. class RealEncoder(AbstractItemEncoder):
  47. def encode(self, value, encodeFun, **options):
  48. return float(value)
  49. class SetEncoder(AbstractItemEncoder):
  50. protoDict = dict
  51. def encode(self, value, encodeFun, **options):
  52. inconsistency = value.isInconsistent
  53. if inconsistency:
  54. raise error.PyAsn1Error(
  55. f"ASN.1 object {value.__class__.__name__} is inconsistent")
  56. namedTypes = value.componentType
  57. substrate = self.protoDict()
  58. for idx, (key, subValue) in enumerate(value.items()):
  59. if namedTypes and namedTypes[idx].isOptional and not value[idx].isValue:
  60. continue
  61. substrate[key] = encodeFun(subValue, **options)
  62. return substrate
  63. class SequenceEncoder(SetEncoder):
  64. protoDict = OrderedDict
  65. class SequenceOfEncoder(AbstractItemEncoder):
  66. def encode(self, value, encodeFun, **options):
  67. inconsistency = value.isInconsistent
  68. if inconsistency:
  69. raise error.PyAsn1Error(
  70. f"ASN.1 object {value.__class__.__name__} is inconsistent")
  71. return [encodeFun(x, **options) for x in value]
  72. class ChoiceEncoder(SequenceEncoder):
  73. pass
  74. class AnyEncoder(AbstractItemEncoder):
  75. def encode(self, value, encodeFun, **options):
  76. return value.asOctets()
  77. TAG_MAP = {
  78. univ.Boolean.tagSet: BooleanEncoder(),
  79. univ.Integer.tagSet: IntegerEncoder(),
  80. univ.BitString.tagSet: BitStringEncoder(),
  81. univ.OctetString.tagSet: OctetStringEncoder(),
  82. univ.Null.tagSet: NullEncoder(),
  83. univ.ObjectIdentifier.tagSet: ObjectIdentifierEncoder(),
  84. univ.RelativeOID.tagSet: RelativeOIDEncoder(),
  85. univ.Enumerated.tagSet: IntegerEncoder(),
  86. univ.Real.tagSet: RealEncoder(),
  87. # Sequence & Set have same tags as SequenceOf & SetOf
  88. univ.SequenceOf.tagSet: SequenceOfEncoder(),
  89. univ.SetOf.tagSet: SequenceOfEncoder(),
  90. univ.Choice.tagSet: ChoiceEncoder(),
  91. # character string types
  92. char.UTF8String.tagSet: TextStringEncoder(),
  93. char.NumericString.tagSet: TextStringEncoder(),
  94. char.PrintableString.tagSet: TextStringEncoder(),
  95. char.TeletexString.tagSet: TextStringEncoder(),
  96. char.VideotexString.tagSet: TextStringEncoder(),
  97. char.IA5String.tagSet: TextStringEncoder(),
  98. char.GraphicString.tagSet: TextStringEncoder(),
  99. char.VisibleString.tagSet: TextStringEncoder(),
  100. char.GeneralString.tagSet: TextStringEncoder(),
  101. char.UniversalString.tagSet: TextStringEncoder(),
  102. char.BMPString.tagSet: TextStringEncoder(),
  103. # useful types
  104. useful.ObjectDescriptor.tagSet: OctetStringEncoder(),
  105. useful.GeneralizedTime.tagSet: OctetStringEncoder(),
  106. useful.UTCTime.tagSet: OctetStringEncoder()
  107. }
  108. # Put in ambiguous & non-ambiguous types for faster codec lookup
  109. TYPE_MAP = {
  110. univ.Boolean.typeId: BooleanEncoder(),
  111. univ.Integer.typeId: IntegerEncoder(),
  112. univ.BitString.typeId: BitStringEncoder(),
  113. univ.OctetString.typeId: OctetStringEncoder(),
  114. univ.Null.typeId: NullEncoder(),
  115. univ.ObjectIdentifier.typeId: ObjectIdentifierEncoder(),
  116. univ.RelativeOID.typeId: RelativeOIDEncoder(),
  117. univ.Enumerated.typeId: IntegerEncoder(),
  118. univ.Real.typeId: RealEncoder(),
  119. # Sequence & Set have same tags as SequenceOf & SetOf
  120. univ.Set.typeId: SetEncoder(),
  121. univ.SetOf.typeId: SequenceOfEncoder(),
  122. univ.Sequence.typeId: SequenceEncoder(),
  123. univ.SequenceOf.typeId: SequenceOfEncoder(),
  124. univ.Choice.typeId: ChoiceEncoder(),
  125. univ.Any.typeId: AnyEncoder(),
  126. # character string types
  127. char.UTF8String.typeId: OctetStringEncoder(),
  128. char.NumericString.typeId: OctetStringEncoder(),
  129. char.PrintableString.typeId: OctetStringEncoder(),
  130. char.TeletexString.typeId: OctetStringEncoder(),
  131. char.VideotexString.typeId: OctetStringEncoder(),
  132. char.IA5String.typeId: OctetStringEncoder(),
  133. char.GraphicString.typeId: OctetStringEncoder(),
  134. char.VisibleString.typeId: OctetStringEncoder(),
  135. char.GeneralString.typeId: OctetStringEncoder(),
  136. char.UniversalString.typeId: OctetStringEncoder(),
  137. char.BMPString.typeId: OctetStringEncoder(),
  138. # useful types
  139. useful.ObjectDescriptor.typeId: OctetStringEncoder(),
  140. useful.GeneralizedTime.typeId: OctetStringEncoder(),
  141. useful.UTCTime.typeId: OctetStringEncoder()
  142. }
  143. class SingleItemEncoder(object):
  144. TAG_MAP = TAG_MAP
  145. TYPE_MAP = TYPE_MAP
  146. def __init__(self, tagMap=_MISSING, typeMap=_MISSING, **ignored):
  147. self._tagMap = tagMap if tagMap is not _MISSING else self.TAG_MAP
  148. self._typeMap = typeMap if typeMap is not _MISSING else self.TYPE_MAP
  149. def __call__(self, value, **options):
  150. if not isinstance(value, base.Asn1Item):
  151. raise error.PyAsn1Error(
  152. 'value is not valid (should be an instance of an ASN.1 Item)')
  153. if LOG:
  154. debug.scope.push(type(value).__name__)
  155. LOG('encoder called for type %s '
  156. '<%s>' % (type(value).__name__, value.prettyPrint()))
  157. tagSet = value.tagSet
  158. try:
  159. concreteEncoder = self._typeMap[value.typeId]
  160. except KeyError:
  161. # use base type for codec lookup to recover untagged types
  162. baseTagSet = tag.TagSet(
  163. value.tagSet.baseTag, value.tagSet.baseTag)
  164. try:
  165. concreteEncoder = self._tagMap[baseTagSet]
  166. except KeyError:
  167. raise error.PyAsn1Error('No encoder for %s' % (value,))
  168. if LOG:
  169. LOG('using value codec %s chosen by '
  170. '%s' % (concreteEncoder.__class__.__name__, tagSet))
  171. pyObject = concreteEncoder.encode(value, self, **options)
  172. if LOG:
  173. LOG('encoder %s produced: '
  174. '%s' % (type(concreteEncoder).__name__, repr(pyObject)))
  175. debug.scope.pop()
  176. return pyObject
  177. class Encoder(object):
  178. SINGLE_ITEM_ENCODER = SingleItemEncoder
  179. def __init__(self, **options):
  180. self._singleItemEncoder = self.SINGLE_ITEM_ENCODER(**options)
  181. def __call__(self, pyObject, asn1Spec=None, **options):
  182. return self._singleItemEncoder(
  183. pyObject, asn1Spec=asn1Spec, **options)
  184. #: Turns ASN.1 object into a Python built-in type object(s).
  185. #:
  186. #: Takes any ASN.1 object (e.g. :py:class:`~pyasn1.type.base.PyAsn1Item` derivative)
  187. #: walks all its components recursively and produces a Python built-in type or a tree
  188. #: of those.
  189. #:
  190. #: One exception is that instead of :py:class:`dict`, the :py:class:`OrderedDict`
  191. #: is used to preserve ordering of the components in ASN.1 SEQUENCE.
  192. #:
  193. #: Parameters
  194. #: ----------
  195. # asn1Value: any pyasn1 object (e.g. :py:class:`~pyasn1.type.base.PyAsn1Item` derivative)
  196. #: pyasn1 object to encode (or a tree of them)
  197. #:
  198. #: Returns
  199. #: -------
  200. #: : :py:class:`object`
  201. #: Python built-in type instance (or a tree of them)
  202. #:
  203. #: Raises
  204. #: ------
  205. #: ~pyasn1.error.PyAsn1Error
  206. #: On encoding errors
  207. #:
  208. #: Examples
  209. #: --------
  210. #: Encode ASN.1 value object into native Python types
  211. #:
  212. #: .. code-block:: pycon
  213. #:
  214. #: >>> seq = SequenceOf(componentType=Integer())
  215. #: >>> seq.extend([1, 2, 3])
  216. #: >>> encode(seq)
  217. #: [1, 2, 3]
  218. #:
  219. encode = SingleItemEncoder()
  220. def __getattr__(attr: str):
  221. if newAttr := {"tagMap": "TAG_MAP", "typeMap": "TYPE_MAP"}.get(attr):
  222. warnings.warn(f"{attr} is deprecated. Please use {newAttr} instead.", DeprecationWarning)
  223. return globals()[newAttr]
  224. raise AttributeError(attr)