You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

_der.py 5.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  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. import six
  6. from cryptography.utils import int_from_bytes, int_to_bytes
  7. # This module contains a lightweight DER encoder and decoder. See X.690 for the
  8. # specification. This module intentionally does not implement the more complex
  9. # BER encoding, only DER.
  10. #
  11. # Note this implementation treats an element's constructed bit as part of the
  12. # tag. This is fine for DER, where the bit is always computable from the type.
  13. CONSTRUCTED = 0x20
  14. CONTEXT_SPECIFIC = 0x80
  15. INTEGER = 0x02
  16. BIT_STRING = 0x03
  17. OCTET_STRING = 0x04
  18. NULL = 0x05
  19. OBJECT_IDENTIFIER = 0x06
  20. SEQUENCE = 0x10 | CONSTRUCTED
  21. SET = 0x11 | CONSTRUCTED
  22. PRINTABLE_STRING = 0x13
  23. UTC_TIME = 0x17
  24. GENERALIZED_TIME = 0x18
  25. class DERReader(object):
  26. def __init__(self, data):
  27. self.data = memoryview(data)
  28. def __enter__(self):
  29. return self
  30. def __exit__(self, exc_type, exc_value, tb):
  31. if exc_value is None:
  32. self.check_empty()
  33. def is_empty(self):
  34. return len(self.data) == 0
  35. def check_empty(self):
  36. if not self.is_empty():
  37. raise ValueError("Invalid DER input: trailing data")
  38. def read_byte(self):
  39. if len(self.data) < 1:
  40. raise ValueError("Invalid DER input: insufficient data")
  41. ret = six.indexbytes(self.data, 0)
  42. self.data = self.data[1:]
  43. return ret
  44. def read_bytes(self, n):
  45. if len(self.data) < n:
  46. raise ValueError("Invalid DER input: insufficient data")
  47. ret = self.data[:n]
  48. self.data = self.data[n:]
  49. return ret
  50. def read_any_element(self):
  51. tag = self.read_byte()
  52. # Tag numbers 31 or higher are stored in multiple bytes. No supported
  53. # ASN.1 types use such tags, so reject these.
  54. if tag & 0x1f == 0x1f:
  55. raise ValueError("Invalid DER input: unexpected high tag number")
  56. length_byte = self.read_byte()
  57. if length_byte & 0x80 == 0:
  58. # If the high bit is clear, the first length byte is the length.
  59. length = length_byte
  60. else:
  61. # If the high bit is set, the first length byte encodes the length
  62. # of the length.
  63. length_byte &= 0x7f
  64. if length_byte == 0:
  65. raise ValueError(
  66. "Invalid DER input: indefinite length form is not allowed "
  67. "in DER"
  68. )
  69. length = 0
  70. for i in range(length_byte):
  71. length <<= 8
  72. length |= self.read_byte()
  73. if length == 0:
  74. raise ValueError(
  75. "Invalid DER input: length was not minimally-encoded"
  76. )
  77. if length < 0x80:
  78. # If the length could have been encoded in short form, it must
  79. # not use long form.
  80. raise ValueError(
  81. "Invalid DER input: length was not minimally-encoded"
  82. )
  83. body = self.read_bytes(length)
  84. return tag, DERReader(body)
  85. def read_element(self, expected_tag):
  86. tag, body = self.read_any_element()
  87. if tag != expected_tag:
  88. raise ValueError("Invalid DER input: unexpected tag")
  89. return body
  90. def read_single_element(self, expected_tag):
  91. with self:
  92. return self.read_element(expected_tag)
  93. def read_optional_element(self, expected_tag):
  94. if len(self.data) > 0 and six.indexbytes(self.data, 0) == expected_tag:
  95. return self.read_element(expected_tag)
  96. return None
  97. def as_integer(self):
  98. if len(self.data) == 0:
  99. raise ValueError("Invalid DER input: empty integer contents")
  100. first = six.indexbytes(self.data, 0)
  101. if first & 0x80 == 0x80:
  102. raise ValueError("Negative DER integers are not supported")
  103. # The first 9 bits must not all be zero or all be ones. Otherwise, the
  104. # encoding should have been one byte shorter.
  105. if len(self.data) > 1:
  106. second = six.indexbytes(self.data, 1)
  107. if first == 0 and second & 0x80 == 0:
  108. raise ValueError(
  109. "Invalid DER input: integer not minimally-encoded"
  110. )
  111. return int_from_bytes(self.data, "big")
  112. def encode_der_integer(x):
  113. if not isinstance(x, six.integer_types):
  114. raise ValueError("Value must be an integer")
  115. if x < 0:
  116. raise ValueError("Negative integers are not supported")
  117. n = x.bit_length() // 8 + 1
  118. return int_to_bytes(x, n)
  119. def encode_der(tag, *children):
  120. length = 0
  121. for child in children:
  122. length += len(child)
  123. chunks = [six.int2byte(tag)]
  124. if length < 0x80:
  125. chunks.append(six.int2byte(length))
  126. else:
  127. length_bytes = int_to_bytes(length)
  128. chunks.append(six.int2byte(0x80 | len(length_bytes)))
  129. chunks.append(length_bytes)
  130. chunks.extend(children)
  131. return b"".join(chunks)