From: W. Trevor King Date: Sat, 21 Dec 2013 02:01:27 +0000 (-0800) Subject: Add PGPPacket._serialize_multiprecision_integer X-Git-Url: http://git.tremily.us/?a=commitdiff_plain;h=b14de04cc3590925a2c7fb31b02f2712e9b6af79;p=gpg-migrate.git Add PGPPacket._serialize_multiprecision_integer This is the inverse of _parse_multiprecision_integer. See the _parse_multiprecision_integer commit for references to RFC 4880. --- diff --git a/gpg-migrate.py b/gpg-migrate.py index 5a3c8f0..70c5250 100755 --- a/gpg-migrate.py +++ b/gpg-migrate.py @@ -1,6 +1,7 @@ #!/usr/bin/python import hashlib as _hashlib +import math as _math import re as _re import subprocess as _subprocess import struct as _struct @@ -684,6 +685,24 @@ class PGPPacket (dict): length_data, ]) + @staticmethod + def _serialize_multiprecision_integer(integer): + r"""Serialize RFC 4880's multipricision integers + + >>> PGPPacket._serialize_multiprecision_integer(1) + b'\x00\x01\x01' + >>> PGPPacket._serialize_multiprecision_integer(511) + b'\x00\t\x01\xff' + """ + bit_length = int(_math.log(integer, 2)) + 1 + chunks = [ + _struct.pack('>H', bit_length), + ] + while integer > 0: + chunks.insert(1, bytes([integer & 0xff])) + integer = integer >> 8 + return b''.join(chunks) + def packets_from_bytes(data): offset = 0