From b14de04cc3590925a2c7fb31b02f2712e9b6af79 Mon Sep 17 00:00:00 2001 From: "W. Trevor King" Date: Fri, 20 Dec 2013 18:01:27 -0800 Subject: [PATCH] Add PGPPacket._serialize_multiprecision_integer This is the inverse of _parse_multiprecision_integer. See the _parse_multiprecision_integer commit for references to RFC 4880. --- gpg-migrate.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) 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 -- 2.26.2