_oid.py 2.3 KB

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