| 13 | |
| 14 | |
| 15 | def encode_integer(r): |
| 16 | assert r >= 0 # can't support negative numbers yet |
| 17 | h = ("%x" % r).encode() |
| 18 | if len(h) % 2: |
| 19 | h = b'0' + h |
| 20 | s = binascii.unhexlify(h) |
| 21 | num = s[0] if isinstance(s[0], int) else ord(s[0]) |
| 22 | if num <= 0x7f: |
| 23 | return b'\x02' + int.to_bytes(len(s), 1, 'big') + s |
| 24 | else: |
| 25 | # DER integers are two's complement, so if the first byte is |
| 26 | # 0x80-0xff then we need an extra 0x00 byte to prevent it from |
| 27 | # looking negative. |
| 28 | return b'\x02' + int.to_bytes(len(s)+1, 1, 'big') + b'\x00' + s |
| 29 | |
| 30 | |
| 31 | def encode_bitstring(s): |