encoder.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #
  2. # This file is part of pyasn1 software.
  3. #
  4. # Copyright (c) 2005-2017, Ilya Etingof <etingof@gmail.com>
  5. # License: http://pyasn1.sf.net/license.html
  6. #
  7. from pyasn1.type import univ
  8. from pyasn1.codec.cer import encoder
  9. from pyasn1 import error
  10. __all__ = ['encode']
  11. class SetOfEncoder(encoder.SetOfEncoder):
  12. @staticmethod
  13. def _cmpSetComponents(c1, c2):
  14. tagSet1 = isinstance(c1, univ.Choice) and c1.getEffectiveTagSet() or c1.getTagSet()
  15. tagSet2 = isinstance(c2, univ.Choice) and c2.getEffectiveTagSet() or c2.getTagSet()
  16. return cmp(tagSet1, tagSet2)
  17. tagMap = encoder.tagMap.copy()
  18. tagMap.update({
  19. # Overload CER encoders with BER ones (a bit hackerish XXX)
  20. univ.BitString.tagSet: encoder.encoder.BitStringEncoder(),
  21. univ.OctetString.tagSet: encoder.encoder.OctetStringEncoder(),
  22. # Set & SetOf have same tags
  23. univ.SetOf().tagSet: SetOfEncoder()
  24. })
  25. typeMap = encoder.typeMap
  26. class Encoder(encoder.Encoder):
  27. supportIndefLength = False
  28. def __call__(self, client, defMode=True, maxChunkSize=0):
  29. if not defMode or maxChunkSize:
  30. raise error.PyAsn1Error('DER forbids indefinite length mode')
  31. return encoder.Encoder.__call__(self, client, defMode, maxChunkSize)
  32. #: Turns ASN.1 object into DER octet stream.
  33. #:
  34. #: Takes any ASN.1 object (e.g. :py:class:`~pyasn1.type.base.PyAsn1Item` derivative)
  35. #: walks all its components recursively and produces a DER octet stream.
  36. #:
  37. #: Parameters
  38. #: ----------
  39. # value: any pyasn1 object (e.g. :py:class:`~pyasn1.type.base.PyAsn1Item` derivative)
  40. #: A pyasn1 object to encode
  41. #:
  42. #: defMode: :py:class:`bool`
  43. #: If `False`, produces indefinite length encoding
  44. #:
  45. #: maxChunkSize: :py:class:`int`
  46. #: Maximum chunk size in chunked encoding mode (0 denotes unlimited chunk size)
  47. #:
  48. #: Returns
  49. #: -------
  50. #: : :py:class:`bytes` (Python 3) or :py:class:`str` (Python 2)
  51. #: Given ASN.1 object encoded into BER octetstream
  52. #:
  53. #: Raises
  54. #: ------
  55. #: : :py:class:`pyasn1.error.PyAsn1Error`
  56. #: On encoding errors
  57. encode = Encoder(tagMap, typeMap)