| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
import struct |
| 24 |
|
| 25 |
from Crypto.Util.py3compat import byte_string, bchr, bord |
| 26 |
|
| 27 |
from Crypto.Util.number import long_to_bytes, bytes_to_long |
| 28 |
|
| 29 |
__all__ = ['DerObject', 'DerInteger', 'DerBoolean', 'DerOctetString', |
| 30 |
'DerNull', 'DerSequence', 'DerObjectId', 'DerBitString', 'DerSetOf'] |
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
def _is_number(x, only_non_negative=False): |
| 41 |
test = 0 |
| 42 |
try: |
| 43 |
test = x + test |
| 44 |
except TypeError: |
| 45 |
return False |
| 46 |
return not only_non_negative or x >= 0 |
| 47 |
|
| 48 |
|
| 49 |
class BytesIO_EOF(object): |
| 50 |
"""This class differs from BytesIO in that a ValueError exception is |
| 51 |
raised whenever EOF is reached.""" |
| 52 |
|
| 53 |
def __init__(self, initial_bytes): |
| 54 |
self._buffer = initial_bytes |
| 55 |
self._index = 0 |
| 56 |
self._bookmark = None |
| 57 |
|
| 58 |
def set_bookmark(self): |
| 59 |
self._bookmark = self._index |
| 60 |
|
| 61 |
def data_since_bookmark(self): |
| 62 |
assert self._bookmark is not None |
| 63 |
return self._buffer[self._bookmark:self._index] |
| 64 |
|
| 65 |
def remaining_data(self): |
| 66 |
return len(self._buffer) - self._index |
| 67 |
|
| 68 |
def read(self, length): |
| 69 |
new_index = self._index + length |
| 70 |
if new_index > len(self._buffer): |
| 71 |
raise ValueError("Not enough data for DER decoding: expected %d bytes and found %d" % (new_index, len(self._buffer))) |
| 72 |
|
| 73 |
result = self._buffer[self._index:new_index] |
| 74 |
self._index = new_index |
| 75 |
return result |
| 76 |
|
| 77 |
def read_byte(self): |
| 78 |
return bord(self.read(1)[0]) |
| 79 |
|
| 80 |
|
| 81 |
class DerObject(object): |
| 82 |
"""Base class for defining a single DER object. |
| 83 |
|
| 84 |
This class should never be directly instantiated. |
| 85 |
""" |
| 86 |
|
| 87 |
def __init__(self, asn1Id=None, payload=b'', implicit=None, |
| 88 |
constructed=False, explicit=None): |
| 89 |
"""Initialize the DER object according to a specific ASN.1 type. |
| 90 |
|
| 91 |
:Parameters: |
| 92 |
asn1Id : integer or byte |
| 93 |
The universal DER tag number for this object |
| 94 |
(e.g. 0x10 for a SEQUENCE). |
| 95 |
If None, the tag is not known yet. |
| 96 |
|
| 97 |
payload : byte string |
| 98 |
The initial payload of the object (that it, |
| 99 |
the content octets). |
| 100 |
If not specified, the payload is empty. |
| 101 |
|
| 102 |
implicit : integer or byte |
| 103 |
The IMPLICIT tag number (< 0x1F) to use for the encoded object. |
| 104 |
It overrides the universal tag *asn1Id*. |
| 105 |
It cannot be combined with the ``explicit`` parameter. |
| 106 |
By default, there is no IMPLICIT tag. |
| 107 |
|
| 108 |
constructed : bool |
| 109 |
True when the ASN.1 type is *constructed*. |
| 110 |
False when it is *primitive* (default). |
| 111 |
|
| 112 |
explicit : integer or byte |
| 113 |
The EXPLICIT tag number (< 0x1F) to use for the encoded object. |
| 114 |
It cannot be combined with the ``implicit`` parameter. |
| 115 |
By default, there is no EXPLICIT tag. |
| 116 |
""" |
| 117 |
|
| 118 |
if asn1Id is None: |
| 119 |
|
| 120 |
self._tag_octet = None |
| 121 |
return |
| 122 |
asn1Id = self._convertTag(asn1Id) |
| 123 |
|
| 124 |
self.payload = payload |
| 125 |
|
| 126 |
|
| 127 |
|
| 128 |
|
| 129 |
|
| 130 |
|
| 131 |
|
| 132 |
|
| 133 |
|
| 134 |
|
| 135 |
|
| 136 |
|
| 137 |
|
| 138 |
|
| 139 |
|
| 140 |
constructed_bit = 0x20 if constructed else 0x00 |
| 141 |
|
| 142 |
if None not in (explicit, implicit): |
| 143 |
raise ValueError("Explicit and implicit tags are" |
| 144 |
" mutually exclusive") |
| 145 |
|
| 146 |
if implicit is not None: |
| 147 |
|
| 148 |
self._tag_octet = 0x80 | constructed_bit | self._convertTag(implicit) |
| 149 |
elif explicit is not None: |
| 150 |
|
| 151 |
self._tag_octet = 0x80 | 0x20 | self._convertTag(explicit) |
| 152 |
self._inner_tag_octet = constructed_bit | asn1Id |
| 153 |
else: |
| 154 |
|
| 155 |
self._tag_octet = constructed_bit | asn1Id |
| 156 |
|
| 157 |
def _convertTag(self, tag): |
| 158 |
"""Check if *tag* is a real DER tag (5 bits). |
| 159 |
Convert it from a character to number if necessary. |
| 160 |
""" |
| 161 |
if not _is_number(tag): |
| 162 |
if len(tag) == 1: |
| 163 |
tag = bord(tag[0]) |
| 164 |
|
| 165 |
if not (_is_number(tag) and 0 <= tag < 0x1F): |
| 166 |
raise ValueError("Wrong DER tag") |
| 167 |
return tag |
| 168 |
|
| 169 |
@staticmethod |
| 170 |
def _definite_form(length): |
| 171 |
"""Build length octets according to BER/DER |
| 172 |
definite form. |
| 173 |
""" |
| 174 |
if length > 127: |
| 175 |
encoding = long_to_bytes(length) |
| 176 |
return bchr(len(encoding) + 128) + encoding |
| 177 |
return bchr(length) |
| 178 |
|
| 179 |
def encode(self): |
| 180 |
"""Return this DER element, fully encoded as a binary byte string.""" |
| 181 |
|
| 182 |
|
| 183 |
|
| 184 |
|
| 185 |
output_payload = self.payload |
| 186 |
|
| 187 |
|
| 188 |
|
| 189 |
if hasattr(self, "_inner_tag_octet"): |
| 190 |
output_payload = (bchr(self._inner_tag_octet) + |
| 191 |
self._definite_form(len(self.payload)) + |
| 192 |
self.payload) |
| 193 |
|
| 194 |
return (bchr(self._tag_octet) + |
| 195 |
self._definite_form(len(output_payload)) + |
| 196 |
output_payload) |
| 197 |
|
| 198 |
def _decodeLen(self, s): |
| 199 |
"""Decode DER length octets from a file.""" |
| 200 |
|
| 201 |
length = s.read_byte() |
| 202 |
|
| 203 |
if length > 127: |
| 204 |
encoded_length = s.read(length & 0x7F) |
| 205 |
if bord(encoded_length[0]) == 0: |
| 206 |
raise ValueError("Invalid DER: length has leading zero") |
| 207 |
length = bytes_to_long(encoded_length) |
| 208 |
if length <= 127: |
| 209 |
raise ValueError("Invalid DER: length in long form but smaller than 128") |
| 210 |
|
| 211 |
return length |
| 212 |
|
| 213 |
def decode(self, der_encoded, strict=False): |
| 214 |
"""Decode a complete DER element, and re-initializes this |
| 215 |
object with it. |
| 216 |
|
| 217 |
Args: |
| 218 |
der_encoded (byte string): A complete DER element. |
| 219 |
|
| 220 |
Raises: |
| 221 |
ValueError: in case of parsing errors. |
| 222 |
""" |
| 223 |
|
| 224 |
if not byte_string(der_encoded): |
| 225 |
raise ValueError("Input is not a byte string") |
| 226 |
|
| 227 |
s = BytesIO_EOF(der_encoded) |
| 228 |
self._decodeFromStream(s, strict) |
| 229 |
|
| 230 |
|
| 231 |
if s.remaining_data() > 0: |
| 232 |
raise ValueError("Unexpected extra data after the DER structure") |
| 233 |
|
| 234 |
return self |
| 235 |
|
| 236 |
def _decodeFromStream(self, s, strict): |
| 237 |
"""Decode a complete DER element from a file.""" |
| 238 |
|
| 239 |
idOctet = s.read_byte() |
| 240 |
if self._tag_octet is not None: |
| 241 |
if idOctet != self._tag_octet: |
| 242 |
raise ValueError("Unexpected DER tag") |
| 243 |
else: |
| 244 |
self._tag_octet = idOctet |
| 245 |
length = self._decodeLen(s) |
| 246 |
self.payload = s.read(length) |
| 247 |
|
| 248 |
|
| 249 |
|
| 250 |
if hasattr(self, "_inner_tag_octet"): |
| 251 |
p = BytesIO_EOF(self.payload) |
| 252 |
inner_octet = p.read_byte() |
| 253 |
if inner_octet != self._inner_tag_octet: |
| 254 |
raise ValueError("Unexpected internal DER tag") |
| 255 |
length = self._decodeLen(p) |
| 256 |
self.payload = p.read(length) |
| 257 |
|
| 258 |
|
| 259 |
if p.remaining_data() > 0: |
| 260 |
raise ValueError("Unexpected extra data after the DER structure") |
| 261 |
|
| 262 |
|
| 263 |
class DerInteger(DerObject): |
| 264 |
"""Class to model a DER INTEGER. |
| 265 |
|
| 266 |
An example of encoding is:: |
| 267 |
|
| 268 |
>>> from Crypto.Util.asn1 import DerInteger |
| 269 |
>>> from binascii import hexlify, unhexlify |
| 270 |
>>> int_der = DerInteger(9) |
| 271 |
>>> print hexlify(int_der.encode()) |
| 272 |
|
| 273 |
which will show ``020109``, the DER encoding of 9. |
| 274 |
|
| 275 |
And for decoding:: |
| 276 |
|
| 277 |
>>> s = unhexlify(b'020109') |
| 278 |
>>> try: |
| 279 |
>>> int_der = DerInteger() |
| 280 |
>>> int_der.decode(s) |
| 281 |
>>> print int_der.value |
| 282 |
>>> except ValueError: |
| 283 |
>>> print "Not a valid DER INTEGER" |
| 284 |
|
| 285 |
the output will be ``9``. |
| 286 |
|
| 287 |
:ivar value: The integer value |
| 288 |
:vartype value: integer |
| 289 |
""" |
| 290 |
|
| 291 |
def __init__(self, value=0, implicit=None, explicit=None): |
| 292 |
"""Initialize the DER object as an INTEGER. |
| 293 |
|
| 294 |
:Parameters: |
| 295 |
value : integer |
| 296 |
The value of the integer. |
| 297 |
|
| 298 |
implicit : integer |
| 299 |
The IMPLICIT tag to use for the encoded object. |
| 300 |
It overrides the universal tag for INTEGER (2). |
| 301 |
""" |
| 302 |
|
| 303 |
DerObject.__init__(self, 0x02, b'', implicit, |
| 304 |
False, explicit) |
| 305 |
self.value = value |
| 306 |
|
| 307 |
def encode(self): |
| 308 |
"""Return the DER INTEGER, fully encoded as a |
| 309 |
binary string.""" |
| 310 |
|
| 311 |
number = self.value |
| 312 |
self.payload = b'' |
| 313 |
while True: |
| 314 |
self.payload = bchr(int(number & 255)) + self.payload |
| 315 |
if 128 <= number <= 255: |
| 316 |
self.payload = bchr(0x00) + self.payload |
| 317 |
if -128 <= number <= 255: |
| 318 |
break |
| 319 |
number >>= 8 |
| 320 |
return DerObject.encode(self) |
| 321 |
|
| 322 |
def decode(self, der_encoded, strict=False): |
| 323 |
"""Decode a DER-encoded INTEGER, and re-initializes this |
| 324 |
object with it. |
| 325 |
|
| 326 |
Args: |
| 327 |
der_encoded (byte string): A complete INTEGER DER element. |
| 328 |
|
| 329 |
Raises: |
| 330 |
ValueError: in case of parsing errors. |
| 331 |
""" |
| 332 |
|
| 333 |
return DerObject.decode(self, der_encoded, strict=strict) |
| 334 |
|
| 335 |
def _decodeFromStream(self, s, strict): |
| 336 |
"""Decode a complete DER INTEGER from a file.""" |
| 337 |
|
| 338 |
|
| 339 |
DerObject._decodeFromStream(self, s, strict) |
| 340 |
|
| 341 |
if strict: |
| 342 |
if len(self.payload) == 0: |
| 343 |
raise ValueError("Invalid encoding for DER INTEGER: empty payload") |
| 344 |
if len(self.payload) >= 2 and struct.unpack('>H', self.payload[:2])[0] < 0x80: |
| 345 |
raise ValueError("Invalid encoding for DER INTEGER: leading zero") |
| 346 |
|
| 347 |
|
| 348 |
self.value = 0 |
| 349 |
bits = 1 |
| 350 |
for i in self.payload: |
| 351 |
self.value *= 256 |
| 352 |
self.value += bord(i) |
| 353 |
bits <<= 8 |
| 354 |
if self.payload and bord(self.payload[0]) & 0x80: |
| 355 |
self.value -= bits |
| 356 |
|
| 357 |
|
| 358 |
class DerBoolean(DerObject): |
| 359 |
"""Class to model a DER-encoded BOOLEAN. |
| 360 |
|
| 361 |
An example of encoding is:: |
| 362 |
|
| 363 |
>>> from Crypto.Util.asn1 import DerBoolean |
| 364 |
>>> bool_der = DerBoolean(True) |
| 365 |
>>> print(bool_der.encode().hex()) |
| 366 |
|
| 367 |
which will show ``0101ff``, the DER encoding of True. |
| 368 |
|
| 369 |
And for decoding:: |
| 370 |
|
| 371 |
>>> s = bytes.fromhex('0101ff') |
| 372 |
>>> try: |
| 373 |
>>> bool_der = DerBoolean() |
| 374 |
>>> bool_der.decode(s) |
| 375 |
>>> print(bool_der.value) |
| 376 |
>>> except ValueError: |
| 377 |
>>> print "Not a valid DER BOOLEAN" |
| 378 |
|
| 379 |
the output will be ``True``. |
| 380 |
|
| 381 |
:ivar value: The boolean value |
| 382 |
:vartype value: boolean |
| 383 |
""" |
| 384 |
def __init__(self, value=False, implicit=None, explicit=None): |
| 385 |
"""Initialize the DER object as a BOOLEAN. |
| 386 |
|
| 387 |
Args: |
| 388 |
value (boolean): |
| 389 |
The value of the boolean. Default is False. |
| 390 |
|
| 391 |
implicit (integer or byte): |
| 392 |
The IMPLICIT tag number (< 0x1F) to use for the encoded object. |
| 393 |
It overrides the universal tag for BOOLEAN (1). |
| 394 |
It cannot be combined with the ``explicit`` parameter. |
| 395 |
By default, there is no IMPLICIT tag. |
| 396 |
|
| 397 |
explicit (integer or byte): |
| 398 |
The EXPLICIT tag number (< 0x1F) to use for the encoded object. |
| 399 |
It cannot be combined with the ``implicit`` parameter. |
| 400 |
By default, there is no EXPLICIT tag. |
| 401 |
""" |
| 402 |
|
| 403 |
DerObject.__init__(self, 0x01, b'', implicit, False, explicit) |
| 404 |
self.value = value |
| 405 |
|
| 406 |
def encode(self): |
| 407 |
"""Return the DER BOOLEAN, fully encoded as a binary string.""" |
| 408 |
|
| 409 |
self.payload = b'\xFF' if self.value else b'\x00' |
| 410 |
return DerObject.encode(self) |
| 411 |
|
| 412 |
def decode(self, der_encoded, strict=False): |
| 413 |
"""Decode a DER-encoded BOOLEAN, and re-initializes this object with it. |
| 414 |
|
| 415 |
Args: |
| 416 |
der_encoded (byte string): A DER-encoded BOOLEAN. |
| 417 |
|
| 418 |
Raises: |
| 419 |
ValueError: in case of parsing errors. |
| 420 |
""" |
| 421 |
|
| 422 |
return DerObject.decode(self, der_encoded, strict) |
| 423 |
|
| 424 |
def _decodeFromStream(self, s, strict): |
| 425 |
"""Decode a DER-encoded BOOLEAN from a file.""" |
| 426 |
|
| 427 |
|
| 428 |
DerObject._decodeFromStream(self, s, strict) |
| 429 |
|
| 430 |
if len(self.payload) != 1: |
| 431 |
raise ValueError("Invalid encoding for DER BOOLEAN: payload is not 1 byte") |
| 432 |
|
| 433 |
if bord(self.payload[0]) == 0: |
| 434 |
self.value = False |
| 435 |
elif bord(self.payload[0]) == 0xFF: |
| 436 |
self.value = True |
| 437 |
else: |
| 438 |
raise ValueError("Invalid payload for DER BOOLEAN") |
| 439 |
|
| 440 |
|
| 441 |
class DerSequence(DerObject): |
| 442 |
"""Class to model a DER SEQUENCE. |
| 443 |
|
| 444 |
This object behaves like a dynamic Python sequence. |
| 445 |
|
| 446 |
Sub-elements that are INTEGERs behave like Python integers. |
| 447 |
|
| 448 |
Any other sub-element is a binary string encoded as a complete DER |
| 449 |
sub-element (TLV). |
| 450 |
|
| 451 |
An example of encoding is: |
| 452 |
|
| 453 |
>>> from Crypto.Util.asn1 import DerSequence, DerInteger |
| 454 |
>>> from binascii import hexlify, unhexlify |
| 455 |
>>> obj_der = unhexlify('070102') |
| 456 |
>>> seq_der = DerSequence([4]) |
| 457 |
>>> seq_der.append(9) |
| 458 |
>>> seq_der.append(obj_der.encode()) |
| 459 |
>>> print hexlify(seq_der.encode()) |
| 460 |
|
| 461 |
which will show ``3009020104020109070102``, the DER encoding of the |
| 462 |
sequence containing ``4``, ``9``, and the object with payload ``02``. |
| 463 |
|
| 464 |
For decoding: |
| 465 |
|
| 466 |
>>> s = unhexlify(b'3009020104020109070102') |
| 467 |
>>> try: |
| 468 |
>>> seq_der = DerSequence() |
| 469 |
>>> seq_der.decode(s) |
| 470 |
>>> print len(seq_der) |
| 471 |
>>> print seq_der[0] |
| 472 |
>>> print seq_der[:] |
| 473 |
>>> except ValueError: |
| 474 |
>>> print "Not a valid DER SEQUENCE" |
| 475 |
|
| 476 |
the output will be:: |
| 477 |
|
| 478 |
3 |
| 479 |
4 |
| 480 |
[4, 9, b'\x07\x01\x02'] |
| 481 |
|
| 482 |
""" |
| 483 |
|
| 484 |
def __init__(self, startSeq=None, implicit=None, explicit=None): |
| 485 |
"""Initialize the DER object as a SEQUENCE. |
| 486 |
|
| 487 |
:Parameters: |
| 488 |
startSeq : Python sequence |
| 489 |
A sequence whose element are either integers or |
| 490 |
other DER objects. |
| 491 |
|
| 492 |
implicit : integer or byte |
| 493 |
The IMPLICIT tag number (< 0x1F) to use for the encoded object. |
| 494 |
It overrides the universal tag for SEQUENCE (16). |
| 495 |
It cannot be combined with the ``explicit`` parameter. |
| 496 |
By default, there is no IMPLICIT tag. |
| 497 |
|
| 498 |
explicit : integer or byte |
| 499 |
The EXPLICIT tag number (< 0x1F) to use for the encoded object. |
| 500 |
It cannot be combined with the ``implicit`` parameter. |
| 501 |
By default, there is no EXPLICIT tag. |
| 502 |
""" |
| 503 |
|
| 504 |
DerObject.__init__(self, 0x10, b'', implicit, True, explicit) |
| 505 |
if startSeq is None: |
| 506 |
self._seq = [] |
| 507 |
else: |
| 508 |
self._seq = startSeq |
| 509 |
|
| 510 |
|
| 511 |
|
| 512 |
def __delitem__(self, n): |
| 513 |
del self._seq[n] |
| 514 |
|
| 515 |
def __getitem__(self, n): |
| 516 |
return self._seq[n] |
| 517 |
|
| 518 |
def __setitem__(self, key, value): |
| 519 |
self._seq[key] = value |
| 520 |
|
| 521 |
def __setslice__(self, i, j, sequence): |
| 522 |
self._seq[i:j] = sequence |
| 523 |
|
| 524 |
def __delslice__(self, i, j): |
| 525 |
del self._seq[i:j] |
| 526 |
|
| 527 |
def __getslice__(self, i, j): |
| 528 |
return self._seq[max(0, i):max(0, j)] |
| 529 |
|
| 530 |
def __len__(self): |
| 531 |
return len(self._seq) |
| 532 |
|
| 533 |
def __iadd__(self, item): |
| 534 |
self._seq.append(item) |
| 535 |
return self |
| 536 |
|
| 537 |
def append(self, item): |
| 538 |
self._seq.append(item) |
| 539 |
return self |
| 540 |
|
| 541 |
def insert(self, index, item): |
| 542 |
self._seq.insert(index, item) |
| 543 |
return self |
| 544 |
|
| 545 |
def hasInts(self, only_non_negative=True): |
| 546 |
"""Return the number of items in this sequence that are |
| 547 |
integers. |
| 548 |
|
| 549 |
Args: |
| 550 |
only_non_negative (boolean): |
| 551 |
If ``True``, negative integers are not counted in. |
| 552 |
""" |
| 553 |
|
| 554 |
items = [x for x in self._seq if _is_number(x, only_non_negative)] |
| 555 |
return len(items) |
| 556 |
|
| 557 |
def hasOnlyInts(self, only_non_negative=True): |
| 558 |
"""Return ``True`` if all items in this sequence are integers |
| 559 |
or non-negative integers. |
| 560 |
|
| 561 |
This function returns False is the sequence is empty, |
| 562 |
or at least one member is not an integer. |
| 563 |
|
| 564 |
Args: |
| 565 |
only_non_negative (boolean): |
| 566 |
If ``True``, the presence of negative integers |
| 567 |
causes the method to return ``False``.""" |
| 568 |
return self._seq and self.hasInts(only_non_negative) == len(self._seq) |
| 569 |
|
| 570 |
def encode(self): |
| 571 |
"""Return this DER SEQUENCE, fully encoded as a |
| 572 |
binary string. |
| 573 |
|
| 574 |
Raises: |
| 575 |
ValueError: if some elements in the sequence are neither integers |
| 576 |
nor byte strings. |
| 577 |
""" |
| 578 |
self.payload = b'' |
| 579 |
for item in self._seq: |
| 580 |
if byte_string(item): |
| 581 |
self.payload += item |
| 582 |
elif _is_number(item): |
| 583 |
self.payload += DerInteger(item).encode() |
| 584 |
else: |
| 585 |
self.payload += item.encode() |
| 586 |
return DerObject.encode(self) |
| 587 |
|
| 588 |
def decode(self, der_encoded, strict=False, nr_elements=None, only_ints_expected=False): |
| 589 |
"""Decode a complete DER SEQUENCE, and re-initializes this |
| 590 |
object with it. |
| 591 |
|
| 592 |
Args: |
| 593 |
der_encoded (byte string): |
| 594 |
A complete SEQUENCE DER element. |
| 595 |
nr_elements (None or integer or list of integers): |
| 596 |
The number of members the SEQUENCE can have |
| 597 |
only_ints_expected (boolean): |
| 598 |
Whether the SEQUENCE is expected to contain only integers. |
| 599 |
strict (boolean): |
| 600 |
Whether decoding must check for strict DER compliancy. |
| 601 |
|
| 602 |
Raises: |
| 603 |
ValueError: in case of parsing errors. |
| 604 |
|
| 605 |
DER INTEGERs are decoded into Python integers. Any other DER |
| 606 |
element is not decoded. Its validity is not checked. |
| 607 |
""" |
| 608 |
|
| 609 |
self._nr_elements = nr_elements |
| 610 |
result = DerObject.decode(self, der_encoded, strict=strict) |
| 611 |
|
| 612 |
if only_ints_expected and not self.hasOnlyInts(): |
| 613 |
raise ValueError("Some members are not INTEGERs") |
| 614 |
|
| 615 |
return result |
| 616 |
|
| 617 |
def _decodeFromStream(self, s, strict): |
| 618 |
"""Decode a complete DER SEQUENCE from a file.""" |
| 619 |
|
| 620 |
self._seq = [] |
| 621 |
|
| 622 |
|
| 623 |
DerObject._decodeFromStream(self, s, strict) |
| 624 |
|
| 625 |
|
| 626 |
p = BytesIO_EOF(self.payload) |
| 627 |
while p.remaining_data() > 0: |
| 628 |
p.set_bookmark() |
| 629 |
|
| 630 |
der = DerObject() |
| 631 |
der._decodeFromStream(p, strict) |
| 632 |
|
| 633 |
|
| 634 |
if der._tag_octet != 0x02: |
| 635 |
self._seq.append(p.data_since_bookmark()) |
| 636 |
else: |
| 637 |
derInt = DerInteger() |
| 638 |
data = p.data_since_bookmark() |
| 639 |
derInt.decode(data, strict=strict) |
| 640 |
self._seq.append(derInt.value) |
| 641 |
|
| 642 |
ok = True |
| 643 |
if self._nr_elements is not None: |
| 644 |
try: |
| 645 |
ok = len(self._seq) in self._nr_elements |
| 646 |
except TypeError: |
| 647 |
ok = len(self._seq) == self._nr_elements |
| 648 |
|
| 649 |
if not ok: |
| 650 |
raise ValueError("Unexpected number of members (%d)" |
| 651 |
" in the sequence" % len(self._seq)) |
| 652 |
|
| 653 |
|
| 654 |
class DerOctetString(DerObject): |
| 655 |
"""Class to model a DER OCTET STRING. |
| 656 |
|
| 657 |
An example of encoding is: |
| 658 |
|
| 659 |
>>> from Crypto.Util.asn1 import DerOctetString |
| 660 |
>>> from binascii import hexlify, unhexlify |
| 661 |
>>> os_der = DerOctetString(b'\\xaa') |
| 662 |
>>> os_der.payload += b'\\xbb' |
| 663 |
>>> print hexlify(os_der.encode()) |
| 664 |
|
| 665 |
which will show ``0402aabb``, the DER encoding for the byte string |
| 666 |
``b'\\xAA\\xBB'``. |
| 667 |
|
| 668 |
For decoding: |
| 669 |
|
| 670 |
>>> s = unhexlify(b'0402aabb') |
| 671 |
>>> try: |
| 672 |
>>> os_der = DerOctetString() |
| 673 |
>>> os_der.decode(s) |
| 674 |
>>> print hexlify(os_der.payload) |
| 675 |
>>> except ValueError: |
| 676 |
>>> print "Not a valid DER OCTET STRING" |
| 677 |
|
| 678 |
the output will be ``aabb``. |
| 679 |
|
| 680 |
:ivar payload: The content of the string |
| 681 |
:vartype payload: byte string |
| 682 |
""" |
| 683 |
|
| 684 |
def __init__(self, value=b'', implicit=None): |
| 685 |
"""Initialize the DER object as an OCTET STRING. |
| 686 |
|
| 687 |
:Parameters: |
| 688 |
value : byte string |
| 689 |
The initial payload of the object. |
| 690 |
If not specified, the payload is empty. |
| 691 |
|
| 692 |
implicit : integer |
| 693 |
The IMPLICIT tag to use for the encoded object. |
| 694 |
It overrides the universal tag for OCTET STRING (4). |
| 695 |
""" |
| 696 |
DerObject.__init__(self, 0x04, value, implicit, False) |
| 697 |
|
| 698 |
|
| 699 |
class DerNull(DerObject): |
| 700 |
"""Class to model a DER NULL element.""" |
| 701 |
|
| 702 |
def __init__(self): |
| 703 |
"""Initialize the DER object as a NULL.""" |
| 704 |
|
| 705 |
DerObject.__init__(self, 0x05, b'', None, False) |
| 706 |
|
| 707 |
|
| 708 |
class DerObjectId(DerObject): |
| 709 |
"""Class to model a DER OBJECT ID. |
| 710 |
|
| 711 |
An example of encoding is: |
| 712 |
|
| 713 |
>>> from Crypto.Util.asn1 import DerObjectId |
| 714 |
>>> from binascii import hexlify, unhexlify |
| 715 |
>>> oid_der = DerObjectId("1.2") |
| 716 |
>>> oid_der.value += ".840.113549.1.1.1" |
| 717 |
>>> print hexlify(oid_der.encode()) |
| 718 |
|
| 719 |
which will show ``06092a864886f70d010101``, the DER encoding for the |
| 720 |
RSA Object Identifier ``1.2.840.113549.1.1.1``. |
| 721 |
|
| 722 |
For decoding: |
| 723 |
|
| 724 |
>>> s = unhexlify(b'06092a864886f70d010101') |
| 725 |
>>> try: |
| 726 |
>>> oid_der = DerObjectId() |
| 727 |
>>> oid_der.decode(s) |
| 728 |
>>> print oid_der.value |
| 729 |
>>> except ValueError: |
| 730 |
>>> print "Not a valid DER OBJECT ID" |
| 731 |
|
| 732 |
the output will be ``1.2.840.113549.1.1.1``. |
| 733 |
|
| 734 |
:ivar value: The Object ID (OID), a dot separated list of integers |
| 735 |
:vartype value: string |
| 736 |
""" |
| 737 |
|
| 738 |
def __init__(self, value='', implicit=None, explicit=None): |
| 739 |
"""Initialize the DER object as an OBJECT ID. |
| 740 |
|
| 741 |
:Parameters: |
| 742 |
value : string |
| 743 |
The initial Object Identifier (e.g. "1.2.0.0.6.2"). |
| 744 |
implicit : integer |
| 745 |
The IMPLICIT tag to use for the encoded object. |
| 746 |
It overrides the universal tag for OBJECT ID (6). |
| 747 |
explicit : integer |
| 748 |
The EXPLICIT tag to use for the encoded object. |
| 749 |
""" |
| 750 |
DerObject.__init__(self, 0x06, b'', implicit, False, explicit) |
| 751 |
self.value = value |
| 752 |
|
| 753 |
def encode(self): |
| 754 |
"""Return the DER OBJECT ID, fully encoded as a |
| 755 |
binary string.""" |
| 756 |
|
| 757 |
comps = [int(x) for x in self.value.split(".")] |
| 758 |
|
| 759 |
if len(comps) < 2: |
| 760 |
raise ValueError("Not a valid Object Identifier string") |
| 761 |
if comps[0] > 2: |
| 762 |
raise ValueError("First component must be 0, 1 or 2") |
| 763 |
if comps[0] < 2 and comps[1] > 39: |
| 764 |
raise ValueError("Second component must be 39 at most") |
| 765 |
|
| 766 |
subcomps = [40 * comps[0] + comps[1]] + comps[2:] |
| 767 |
|
| 768 |
encoding = [] |
| 769 |
for v in reversed(subcomps): |
| 770 |
encoding.append(v & 0x7F) |
| 771 |
v >>= 7 |
| 772 |
while v: |
| 773 |
encoding.append((v & 0x7F) | 0x80) |
| 774 |
v >>= 7 |
| 775 |
|
| 776 |
self.payload = b''.join([bchr(x) for x in reversed(encoding)]) |
| 777 |
return DerObject.encode(self) |
| 778 |
|
| 779 |
def decode(self, der_encoded, strict=False): |
| 780 |
"""Decode a complete DER OBJECT ID, and re-initializes this |
| 781 |
object with it. |
| 782 |
|
| 783 |
Args: |
| 784 |
der_encoded (byte string): |
| 785 |
A complete DER OBJECT ID. |
| 786 |
strict (boolean): |
| 787 |
Whether decoding must check for strict DER compliancy. |
| 788 |
|
| 789 |
Raises: |
| 790 |
ValueError: in case of parsing errors. |
| 791 |
""" |
| 792 |
|
| 793 |
return DerObject.decode(self, der_encoded, strict) |
| 794 |
|
| 795 |
def _decodeFromStream(self, s, strict): |
| 796 |
"""Decode a complete DER OBJECT ID from a file.""" |
| 797 |
|
| 798 |
|
| 799 |
DerObject._decodeFromStream(self, s, strict) |
| 800 |
|
| 801 |
|
| 802 |
p = BytesIO_EOF(self.payload) |
| 803 |
|
| 804 |
subcomps = [] |
| 805 |
v = 0 |
| 806 |
while p.remaining_data(): |
| 807 |
c = p.read_byte() |
| 808 |
v = (v << 7) + (c & 0x7F) |
| 809 |
if not (c & 0x80): |
| 810 |
subcomps.append(v) |
| 811 |
v = 0 |
| 812 |
|
| 813 |
if len(subcomps) == 0: |
| 814 |
raise ValueError("Empty payload") |
| 815 |
|
| 816 |
if subcomps[0] < 40: |
| 817 |
subcomps[:1] = [0, subcomps[0]] |
| 818 |
elif subcomps[0] < 80: |
| 819 |
subcomps[:1] = [1, subcomps[0] - 40] |
| 820 |
else: |
| 821 |
subcomps[:1] = [2, subcomps[0] - 80] |
| 822 |
|
| 823 |
self.value = ".".join([str(x) for x in subcomps]) |
| 824 |
|
| 825 |
|
| 826 |
class DerBitString(DerObject): |
| 827 |
"""Class to model a DER BIT STRING. |
| 828 |
|
| 829 |
An example of encoding is: |
| 830 |
|
| 831 |
>>> from Crypto.Util.asn1 import DerBitString |
| 832 |
>>> bs_der = DerBitString(b'\\xAA') |
| 833 |
>>> bs_der.value += b'\\xBB' |
| 834 |
>>> print(bs_der.encode().hex()) |
| 835 |
|
| 836 |
which will show ``030300aabb``, the DER encoding for the bit string |
| 837 |
``b'\\xAA\\xBB'``. |
| 838 |
|
| 839 |
For decoding: |
| 840 |
|
| 841 |
>>> s = bytes.fromhex('030300aabb') |
| 842 |
>>> try: |
| 843 |
>>> bs_der = DerBitString() |
| 844 |
>>> bs_der.decode(s) |
| 845 |
>>> print(bs_der.value.hex()) |
| 846 |
>>> except ValueError: |
| 847 |
>>> print "Not a valid DER BIT STRING" |
| 848 |
|
| 849 |
the output will be ``aabb``. |
| 850 |
|
| 851 |
:ivar value: The content of the string |
| 852 |
:vartype value: byte string |
| 853 |
""" |
| 854 |
|
| 855 |
def __init__(self, value=b'', implicit=None, explicit=None): |
| 856 |
"""Initialize the DER object as a BIT STRING. |
| 857 |
|
| 858 |
:Parameters: |
| 859 |
value : byte string or DER object |
| 860 |
The initial, packed bit string. |
| 861 |
If not specified, the bit string is empty. |
| 862 |
implicit : integer |
| 863 |
The IMPLICIT tag to use for the encoded object. |
| 864 |
It overrides the universal tag for BIT STRING (3). |
| 865 |
explicit : integer |
| 866 |
The EXPLICIT tag to use for the encoded object. |
| 867 |
""" |
| 868 |
DerObject.__init__(self, 0x03, b'', implicit, False, explicit) |
| 869 |
|
| 870 |
|
| 871 |
if isinstance(value, DerObject): |
| 872 |
self.value = value.encode() |
| 873 |
else: |
| 874 |
self.value = value |
| 875 |
|
| 876 |
def encode(self): |
| 877 |
"""Return the DER BIT STRING, fully encoded as a |
| 878 |
byte string.""" |
| 879 |
|
| 880 |
|
| 881 |
self.payload = b'\x00' + self.value |
| 882 |
return DerObject.encode(self) |
| 883 |
|
| 884 |
def decode(self, der_encoded, strict=False): |
| 885 |
"""Decode a complete DER BIT STRING, and re-initializes this |
| 886 |
object with it. |
| 887 |
|
| 888 |
Args: |
| 889 |
der_encoded (byte string): a complete DER BIT STRING. |
| 890 |
strict (boolean): |
| 891 |
Whether decoding must check for strict DER compliancy. |
| 892 |
|
| 893 |
Raises: |
| 894 |
ValueError: in case of parsing errors. |
| 895 |
""" |
| 896 |
|
| 897 |
return DerObject.decode(self, der_encoded, strict) |
| 898 |
|
| 899 |
def _decodeFromStream(self, s, strict): |
| 900 |
"""Decode a complete DER BIT STRING DER from a file.""" |
| 901 |
|
| 902 |
|
| 903 |
DerObject._decodeFromStream(self, s, strict) |
| 904 |
|
| 905 |
if self.payload and bord(self.payload[0]) != 0: |
| 906 |
raise ValueError("Not a valid BIT STRING") |
| 907 |
|
| 908 |
|
| 909 |
self.value = b'' |
| 910 |
|
| 911 |
if self.payload: |
| 912 |
self.value = self.payload[1:] |
| 913 |
|
| 914 |
|
| 915 |
class DerSetOf(DerObject): |
| 916 |
"""Class to model a DER SET OF. |
| 917 |
|
| 918 |
An example of encoding is: |
| 919 |
|
| 920 |
>>> from Crypto.Util.asn1 import DerBitString |
| 921 |
>>> from binascii import hexlify, unhexlify |
| 922 |
>>> so_der = DerSetOf([4,5]) |
| 923 |
>>> so_der.add(6) |
| 924 |
>>> print hexlify(so_der.encode()) |
| 925 |
|
| 926 |
which will show ``3109020104020105020106``, the DER encoding |
| 927 |
of a SET OF with items 4,5, and 6. |
| 928 |
|
| 929 |
For decoding: |
| 930 |
|
| 931 |
>>> s = unhexlify(b'3109020104020105020106') |
| 932 |
>>> try: |
| 933 |
>>> so_der = DerSetOf() |
| 934 |
>>> so_der.decode(s) |
| 935 |
>>> print [x for x in so_der] |
| 936 |
>>> except ValueError: |
| 937 |
>>> print "Not a valid DER SET OF" |
| 938 |
|
| 939 |
the output will be ``[4, 5, 6]``. |
| 940 |
""" |
| 941 |
|
| 942 |
def __init__(self, startSet=None, implicit=None): |
| 943 |
"""Initialize the DER object as a SET OF. |
| 944 |
|
| 945 |
:Parameters: |
| 946 |
startSet : container |
| 947 |
The initial set of integers or DER encoded objects. |
| 948 |
implicit : integer |
| 949 |
The IMPLICIT tag to use for the encoded object. |
| 950 |
It overrides the universal tag for SET OF (17). |
| 951 |
""" |
| 952 |
DerObject.__init__(self, 0x11, b'', implicit, True) |
| 953 |
self._seq = [] |
| 954 |
|
| 955 |
|
| 956 |
|
| 957 |
self._elemOctet = None |
| 958 |
|
| 959 |
if startSet: |
| 960 |
for e in startSet: |
| 961 |
self.add(e) |
| 962 |
|
| 963 |
def __getitem__(self, n): |
| 964 |
return self._seq[n] |
| 965 |
|
| 966 |
def __iter__(self): |
| 967 |
return iter(self._seq) |
| 968 |
|
| 969 |
def __len__(self): |
| 970 |
return len(self._seq) |
| 971 |
|
| 972 |
def add(self, elem): |
| 973 |
"""Add an element to the set. |
| 974 |
|
| 975 |
Args: |
| 976 |
elem (byte string or integer): |
| 977 |
An element of the same type of objects already in the set. |
| 978 |
It can be an integer or a DER encoded object. |
| 979 |
""" |
| 980 |
|
| 981 |
if _is_number(elem): |
| 982 |
eo = 0x02 |
| 983 |
elif isinstance(elem, DerObject): |
| 984 |
eo = self._tag_octet |
| 985 |
else: |
| 986 |
eo = bord(elem[0]) |
| 987 |
|
| 988 |
if self._elemOctet != eo: |
| 989 |
if self._elemOctet is not None: |
| 990 |
raise ValueError("New element does not belong to the set") |
| 991 |
self._elemOctet = eo |
| 992 |
|
| 993 |
if elem not in self._seq: |
| 994 |
self._seq.append(elem) |
| 995 |
|
| 996 |
def decode(self, der_encoded, strict=False): |
| 997 |
"""Decode a complete SET OF DER element, and re-initializes this |
| 998 |
object with it. |
| 999 |
|
| 1000 |
DER INTEGERs are decoded into Python integers. Any other DER |
| 1001 |
element is left undecoded; its validity is not checked. |
| 1002 |
|
| 1003 |
Args: |
| 1004 |
der_encoded (byte string): a complete DER BIT SET OF. |
| 1005 |
strict (boolean): |
| 1006 |
Whether decoding must check for strict DER compliancy. |
| 1007 |
|
| 1008 |
Raises: |
| 1009 |
ValueError: in case of parsing errors. |
| 1010 |
""" |
| 1011 |
|
| 1012 |
return DerObject.decode(self, der_encoded, strict) |
| 1013 |
|
| 1014 |
def _decodeFromStream(self, s, strict): |
| 1015 |
"""Decode a complete DER SET OF from a file.""" |
| 1016 |
|
| 1017 |
self._seq = [] |
| 1018 |
|
| 1019 |
|
| 1020 |
DerObject._decodeFromStream(self, s, strict) |
| 1021 |
|
| 1022 |
|
| 1023 |
p = BytesIO_EOF(self.payload) |
| 1024 |
setIdOctet = -1 |
| 1025 |
while p.remaining_data() > 0: |
| 1026 |
p.set_bookmark() |
| 1027 |
|
| 1028 |
der = DerObject() |
| 1029 |
der._decodeFromStream(p, strict) |
| 1030 |
|
| 1031 |
|
| 1032 |
if setIdOctet < 0: |
| 1033 |
setIdOctet = der._tag_octet |
| 1034 |
else: |
| 1035 |
if setIdOctet != der._tag_octet: |
| 1036 |
raise ValueError("Not all elements are of the same DER type") |
| 1037 |
|
| 1038 |
|
| 1039 |
if setIdOctet != 0x02: |
| 1040 |
self._seq.append(p.data_since_bookmark()) |
| 1041 |
else: |
| 1042 |
derInt = DerInteger() |
| 1043 |
derInt.decode(p.data_since_bookmark(), strict) |
| 1044 |
self._seq.append(derInt.value) |
| 1045 |
|
| 1046 |
|
| 1047 |
def encode(self): |
| 1048 |
"""Return this SET OF DER element, fully encoded as a |
| 1049 |
binary string. |
| 1050 |
""" |
| 1051 |
|
| 1052 |
|
| 1053 |
ordered = [] |
| 1054 |
for item in self._seq: |
| 1055 |
if _is_number(item): |
| 1056 |
bys = DerInteger(item).encode() |
| 1057 |
elif isinstance(item, DerObject): |
| 1058 |
bys = item.encode() |
| 1059 |
else: |
| 1060 |
bys = item |
| 1061 |
ordered.append(bys) |
| 1062 |
ordered.sort() |
| 1063 |
self.payload = b''.join(ordered) |
| 1064 |
return DerObject.encode(self) |