From: W. Trevor King Date: Sat, 21 Dec 2013 01:44:00 +0000 (-0800) Subject: Stub out PGPPacket.to_bytes with header serialization X-Git-Url: http://git.tremily.us/?a=commitdiff_plain;h=7298637a81ab87b82579afe34865a92a1cacee09;p=gpg-migrate.git Stub out PGPPacket.to_bytes with header serialization Also setup a body serialization framework along the lines of the existing packet-parsing framework in PGPPacket.from_bytes. The header serialization in _serialize_header is just the inverse of the parsing in _parse_header. See the _parse_header commit for references to RFC 4880. --- diff --git a/gpg-migrate.py b/gpg-migrate.py index 9453494..5a3c8f0 100755 --- a/gpg-migrate.py +++ b/gpg-migrate.py @@ -653,7 +653,36 @@ class PGPPacket (dict): self['user'] = str(data, 'utf-8') def to_bytes(self): - pass + method_name = '_serialize_{}'.format(self._clean_type()) + method = getattr(self, method_name, None) + if not method: + raise NotImplementedError( + 'cannot serialize packet type {!r}'.format(self['type'])) + body = method() + self['length'] = len(body) + return b''.join([ + self._serialize_header(), + body, + ]) + + def _serialize_header(self): + always_one = 1 + new_format = 0 + type_code = self._reverse(self._packet_types, self['type']) + packet_tag = ( + always_one * (1 << 7) | + new_format * (1 << 6) | + type_code * (1 << 2) | + self['length-type'] + ) + length_bytes, length_type = self._old_format_packet_length_type[ + self['length-type']] + length_format = '>{}'.format(length_type) + length_data = _struct.pack(length_format, self['length']) + return b''.join([ + bytes([packet_tag]), + length_data, + ]) def packets_from_bytes(data):