_oid.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. # This file is dual licensed under the terms of the Apache License, Version
  2. # 2.0, and the BSD License. See the LICENSE file in the root of this repository
  3. # for complete details.
  4. from __future__ import absolute_import, division, print_function
  5. from cryptography import utils
  6. class ObjectIdentifier(object):
  7. def __init__(self, dotted_string):
  8. self._dotted_string = dotted_string
  9. nodes = self._dotted_string.split(".")
  10. intnodes = []
  11. # There must be at least 2 nodes, the first node must be 0..2, and
  12. # if less than 2, the second node cannot have a value outside the
  13. # range 0..39. All nodes must be integers.
  14. for node in nodes:
  15. try:
  16. node_value = int(node, 10)
  17. except ValueError:
  18. raise ValueError(
  19. "Malformed OID: %s (non-integer nodes)"
  20. % (self._dotted_string)
  21. )
  22. if node_value < 0:
  23. raise ValueError(
  24. "Malformed OID: %s (negative-integer nodes)"
  25. % (self._dotted_string)
  26. )
  27. intnodes.append(node_value)
  28. if len(nodes) < 2:
  29. raise ValueError(
  30. "Malformed OID: %s (insufficient number of nodes)"
  31. % (self._dotted_string)
  32. )
  33. if intnodes[0] > 2:
  34. raise ValueError(
  35. "Malformed OID: %s (first node outside valid range)"
  36. % (self._dotted_string)
  37. )
  38. if intnodes[0] < 2 and intnodes[1] >= 40:
  39. raise ValueError(
  40. "Malformed OID: %s (second node outside valid range)"
  41. % (self._dotted_string)
  42. )
  43. def __eq__(self, other):
  44. if not isinstance(other, ObjectIdentifier):
  45. return NotImplemented
  46. return self.dotted_string == other.dotted_string
  47. def __ne__(self, other):
  48. return not self == other
  49. def __repr__(self):
  50. return "<ObjectIdentifier(oid={}, name={})>".format(
  51. self.dotted_string, self._name
  52. )
  53. def __hash__(self):
  54. return hash(self.dotted_string)
  55. @property
  56. def _name(self):
  57. # Lazy import to avoid an import cycle
  58. from cryptography.x509.oid import _OID_NAMES
  59. return _OID_NAMES.get(self, "Unknown OID")
  60. dotted_string = utils.read_only_property("_dotted_string")