42905513c9236db2330977908e899e4846259300
[gpg-migrate.git] / gpg-migrate.py
1 #!/usr/bin/python
2
3 import getpass as _getpass
4 import hashlib as _hashlib
5 import math as _math
6 import re as _re
7 import subprocess as _subprocess
8 import struct as _struct
9
10 import Crypto.Cipher.AES as _crypto_cipher_aes
11 import Crypto.Cipher.Blowfish as _crypto_cipher_blowfish
12 import Crypto.Cipher.CAST as _crypto_cipher_cast
13 import Crypto.Cipher.DES3 as _crypto_cipher_des3
14
15
16 def _get_stdout(args, stdin=None):
17     stdin_pipe = None
18     if stdin is not None:
19         stdin_pipe = _subprocess.PIPE
20     p = _subprocess.Popen(args, stdin=stdin_pipe, stdout=_subprocess.PIPE)
21     stdout, stderr = p.communicate(stdin)
22     status = p.wait()
23     if status != 0:
24         raise RuntimeError(status)
25     return stdout
26
27
28 class PGPPacket (dict):
29     # http://tools.ietf.org/search/rfc4880
30     _old_format_packet_length_type = {  # type: (bytes, struct type)
31         0: (1, 'B'),  # 1-byte unsigned integer
32         1: (2, 'H'),  # 2-byte unsigned integer
33         2: (4, 'I'),  # 4-byte unsigned integer
34         3: (None, None),
35         }
36
37     _packet_types = {
38         0: 'reserved',
39         1: 'public-key encrypted session key packet',
40         2: 'signature packet',
41         3: 'symmetric-key encrypted session key packet',
42         4: 'one-pass signature packet',
43         5: 'secret-key packet',
44         6: 'public-key packet',
45         7: 'secret-subkey packet',
46         8: 'compressed data packet',
47         9: 'symmetrically encrypted data packet',
48         10: 'marker packet',
49         11: 'literal data packet',
50         12: 'trust packet',
51         13: 'user id packet',
52         14: 'public-subkey packet',
53         17: 'user attribute packet',
54         18: 'sym. encrypted and integrity protected data packet',
55         19: 'modification detection code packet',
56         60: 'private',
57         61: 'private',
58         62: 'private',
59         63: 'private',
60         }
61
62     _public_key_algorithms = {
63         1: 'rsa (encrypt or sign)',
64         2: 'rsa encrypt-only',
65         3: 'rsa sign-only',
66         16: 'elgamal (encrypt-only)',
67         17: 'dsa (digital signature algorithm)',
68         18: 'reserved for elliptic curve',
69         19: 'reserved for ecdsa',
70         20: 'reserved (formerly elgamal encrypt or sign)',
71         21: 'reserved for diffie-hellman',
72         100: 'private',
73         101: 'private',
74         102: 'private',
75         103: 'private',
76         104: 'private',
77         105: 'private',
78         106: 'private',
79         107: 'private',
80         108: 'private',
81         109: 'private',
82         110: 'private',
83         }
84
85     _symmetric_key_algorithms = {
86         0: 'plaintext or unencrypted data',
87         1: 'idea',
88         2: 'tripledes',
89         3: 'cast5',
90         4: 'blowfish',
91         5: 'reserved',
92         6: 'reserved',
93         7: 'aes with 128-bit key',
94         8: 'aes with 192-bit key',
95         9: 'aes with 256-bit key',
96         10: 'twofish',
97         100: 'private',
98         101: 'private',
99         102: 'private',
100         103: 'private',
101         104: 'private',
102         105: 'private',
103         106: 'private',
104         107: 'private',
105         108: 'private',
106         109: 'private',
107         110: 'private',
108         }
109
110     _cipher_block_size = {  # in bits
111         'aes with 128-bit key': 128,
112         'aes with 192-bit key': 128,
113         'aes with 256-bit key': 128,
114         'cast5': 64,
115         'twofish': 128,
116         }
117
118     _crypto_module = {
119         'aes with 128-bit key': _crypto_cipher_aes,
120         'aes with 192-bit key': _crypto_cipher_aes,
121         'aes with 256-bit key': _crypto_cipher_aes,
122         'blowfish': _crypto_cipher_blowfish,
123         'cast5': _crypto_cipher_cast,
124         'tripledes': _crypto_cipher_des3,
125         }
126
127     _key_size = {  # in bits
128         'aes with 128-bit key': 128,
129         'aes with 192-bit key': 192,
130         'aes with 256-bit key': 256,
131         'cast5': 128,
132         }
133
134     _compression_algorithms = {
135         0: 'uncompressed',
136         1: 'zip',
137         2: 'zlib',
138         3: 'bzip2',
139         100: 'private',
140         101: 'private',
141         102: 'private',
142         103: 'private',
143         104: 'private',
144         105: 'private',
145         106: 'private',
146         107: 'private',
147         108: 'private',
148         109: 'private',
149         110: 'private',
150         }
151
152     _hash_algorithms = {
153         1: 'md5',
154         2: 'sha-1',
155         3: 'ripe-md/160',
156         4: 'reserved',
157         5: 'reserved',
158         6: 'reserved',
159         7: 'reserved',
160         8: 'sha256',
161         9: 'sha384',
162         10: 'sha512',
163         11: 'sha224',
164         100: 'private',
165         101: 'private',
166         102: 'private',
167         103: 'private',
168         104: 'private',
169         105: 'private',
170         106: 'private',
171         107: 'private',
172         108: 'private',
173         109: 'private',
174         110: 'private',
175         }
176
177     _hashlib_name = {  # map OpenPGP-based names to hashlib names
178         'md5': 'md5',
179         'sha-1': 'sha1',
180         'ripe-md/160': 'ripemd160',
181         'sha256': 'sha256',
182         'sha384': 'sha384',
183         'sha512': 'sha512',
184         'sha224': 'sha224',
185         }
186
187     _string_to_key_types = {
188         0: 'simple',
189         1: 'salted',
190         2: 'reserved',
191         3: 'iterated and salted',
192         100: 'private',
193         101: 'private',
194         102: 'private',
195         103: 'private',
196         104: 'private',
197         105: 'private',
198         106: 'private',
199         107: 'private',
200         108: 'private',
201         109: 'private',
202         110: 'private',
203         }
204
205     _string_to_key_expbias = 6
206
207     _signature_types = {
208         0x00: 'binary document',
209         0x01: 'canonical text document',
210         0x02: 'standalone',
211         0x10: 'generic user id and public-key packet',
212         0x11: 'persona user id and public-key packet',
213         0x12: 'casual user id and public-key packet',
214         0x13: 'postitive user id and public-key packet',
215         0x18: 'subkey binding',
216         0x19: 'primary key binding',
217         0x1F: 'direct key',
218         0x20: 'key revocation',
219         0x28: 'subkey revocation',
220         0x30: 'certification revocation',
221         0x40: 'timestamp',
222         0x50: 'third-party confirmation',
223         }
224
225     _signature_subpacket_types = {
226         0: 'reserved',
227         1: 'reserved',
228         2: 'signature creation time',
229         3: 'signature expiration time',
230         4: 'exportable certification',
231         5: 'trust signature',
232         6: 'regular expression',
233         7: 'revocable',
234         8: 'reserved',
235         9: 'key expiration time',
236         10: 'placeholder for backward compatibility',
237         11: 'preferred symmetric algorithms',
238         12: 'revocation key',
239         13: 'reserved',
240         14: 'reserved',
241         15: 'reserved',
242         16: 'issuer',
243         17: 'reserved',
244         18: 'reserved',
245         19: 'reserved',
246         20: 'notation data',
247         21: 'preferred hash algorithms',
248         22: 'preferred compression algorithms',
249         23: 'key server preferences',
250         24: 'preferred key server',
251         25: 'primary user id',
252         26: 'policy uri',
253         27: 'key flags',
254         28: 'signer user id',
255         29: 'reason for revocation',
256         30: 'features',
257         31: 'signature target',
258         32: 'embedded signature',
259         100: 'private',
260         101: 'private',
261         102: 'private',
262         103: 'private',
263         104: 'private',
264         105: 'private',
265         106: 'private',
266         107: 'private',
267         108: 'private',
268         109: 'private',
269         110: 'private',
270         }
271
272     _clean_type_regex = _re.compile('\W+')
273
274     def __init__(self, key=None):
275         super(PGPPacket, self).__init__()
276         self.key = key
277
278     def _clean_type(self, type=None):
279         if type is None:
280             type = self['type']
281         return self._clean_type_regex.sub('_', type)
282
283     @staticmethod
284     def _reverse(dict, value):
285         """Reverse lookups in dictionaries
286
287         >>> PGPPacket._reverse(PGPPacket._packet_types, 'public-key packet')
288         6
289         """
290         return [k for k,v in dict.items() if v == value][0]
291
292     def __str__(self):
293         method_name = '_str_{}'.format(self._clean_type())
294         method = getattr(self, method_name, None)
295         if not method:
296             return self['type']
297         details = method()
298         return '{}: {}'.format(self['type'], details)
299
300     def _str_public_key_packet(self):
301         return self._str_generic_key_packet()
302
303     def _str_public_subkey_packet(self):
304         return self._str_generic_key_packet()
305
306     def _str_generic_key_packet(self):
307         return self['fingerprint'][-8:].upper()
308
309     def _str_secret_key_packet(self):
310         return self._str_generic_secret_key_packet()
311
312     def _str_secret_subkey_packet(self):
313         return self._str_generic_secret_key_packet()
314
315     def _str_generic_secret_key_packet(self):
316         lines = [self._str_generic_key_packet()]
317         for label, key in [
318                 ('symmetric encryption',
319                  'symmetric-encryption-algorithm'),
320                 ('s2k hash', 'string-to-key-hash-algorithm'),
321                 ('s2k count', 'string-to-key-count'),
322                 ('s2k salt', 'string-to-key-salt'),
323                 ('IV', 'initial-vector'),
324                 ]:
325             if key in self:
326                 value = self[key]
327                 if isinstance(value, bytes):
328                     value = ' '.join('{:02x}'.format(byte) for byte in value)
329                 lines.append('  {}: {}'.format(label, value))
330         return '\n'.join(lines)
331
332     def _str_signature_packet(self):
333         lines = [self['signature-type']]
334         if self['hashed-subpackets']:
335             lines.append('  hashed subpackets:')
336             lines.extend(self._str_signature_subpackets(
337                 self['hashed-subpackets'], prefix='    '))
338         if self['unhashed-subpackets']:
339             lines.append('  unhashed subpackets:')
340             lines.extend(self._str_signature_subpackets(
341                 self['unhashed-subpackets'], prefix='    '))
342         return '\n'.join(lines)
343
344     def _str_signature_subpackets(self, subpackets, prefix):
345         lines = []
346         for subpacket in subpackets:
347             method_name = '_str_{}_signature_subpacket'.format(
348                 self._clean_type(type=subpacket['type']))
349             method = getattr(self, method_name, None)
350             if method:
351                 lines.append('    {}: {}'.format(
352                     subpacket['type'],
353                     method(subpacket=subpacket)))
354             else:
355                 lines.append('    {}'.format(subpacket['type']))
356         return lines
357
358     def _str_signature_creation_time_signature_subpacket(self, subpacket):
359         return str(subpacket['signature-creation-time'])
360
361     def _str_issuer_signature_subpacket(self, subpacket):
362         return subpacket['issuer'][-8:].upper()
363
364     def _str_key_expiration_time_signature_subpacket(self, subpacket):
365         return str(subpacket['key-expiration-time'])
366
367     def _str_preferred_symmetric_algorithms_signature_subpacket(
368             self, subpacket):
369         return ', '.join(
370             algo for algo in subpacket['preferred-symmetric-algorithms'])
371
372     def _str_preferred_hash_algorithms_signature_subpacket(
373             self, subpacket):
374         return ', '.join(
375             algo for algo in subpacket['preferred-hash-algorithms'])
376
377     def _str_preferred_compression_algorithms_signature_subpacket(
378             self, subpacket):
379         return ', '.join(
380             algo for algo in subpacket['preferred-compression-algorithms'])
381
382     def _str_key_server_preferences_signature_subpacket(self, subpacket):
383         return ', '.join(
384             x for x in sorted(subpacket['key-server-preferences']))
385
386     def _str_primary_user_id_signature_subpacket(self, subpacket):
387         return str(subpacket['primary-user-id'])
388
389     def _str_key_flags_signature_subpacket(self, subpacket):
390         return ', '.join(x for x in sorted(subpacket['key-flags']))
391
392     def _str_features_signature_subpacket(self, subpacket):
393         return ', '.join(x for x in sorted(subpacket['features']))
394
395     def _str_embedded_signature_signature_subpacket(self, subpacket):
396         return subpacket['embedded']['signature-type']
397
398     def _str_user_id_packet(self):
399         return self['user']
400
401     def from_bytes(self, data):
402         offset = self._parse_header(data=data)
403         packet = data[offset:offset + self['length']]
404         if len(packet) < self['length']:
405             raise ValueError('packet too short ({} < {})'.format(
406                 len(packet), self['length']))
407         offset += self['length']
408         method_name = '_parse_{}'.format(self._clean_type())
409         method = getattr(self, method_name, None)
410         if not method:
411             raise NotImplementedError(
412                 'cannot parse packet type {!r}'.format(self['type']))
413         method(data=packet)
414         return offset
415
416     def _parse_header(self, data):
417         packet_tag = data[0]
418         offset = 1
419         always_one = packet_tag & 1 << 7
420         if not always_one:
421             raise ValueError('most significant packet tag bit not set')
422         self['new-format'] = packet_tag & 1 << 6
423         if self['new-format']:
424             type_code = packet_tag & 0b111111
425             raise NotImplementedError('new-format packet length')
426         else:
427             type_code = packet_tag >> 2 & 0b1111
428             self['length-type'] = packet_tag & 0b11
429             length_bytes, length_type = self._old_format_packet_length_type[
430                 self['length-type']]
431             if not length_bytes:
432                 raise NotImplementedError(
433                     'old-format packet of indeterminate length')
434             length_format = '>{}'.format(length_type)
435             length_data = data[offset: offset + length_bytes]
436             offset += length_bytes
437             self['length'] = _struct.unpack(length_format, length_data)[0]
438         self['type'] = self._packet_types[type_code]
439         return offset
440
441     @staticmethod
442     def _parse_multiprecision_integer(data):
443         r"""Parse RFC 4880's multiprecision integers
444
445         >>> PGPPacket._parse_multiprecision_integer(b'\x00\x01\x01')
446         (3, 1)
447         >>> PGPPacket._parse_multiprecision_integer(b'\x00\x09\x01\xff')
448         (4, 511)
449         """
450         bits = _struct.unpack('>H', data[:2])[0]
451         offset = 2
452         length = (bits + 7) // 8
453         value = 0
454         for i in range(length):
455             value += data[offset + i] * 1 << (8 * (length - i - 1))
456         offset += length
457         return (offset, value)
458
459     @classmethod
460     def _decode_string_to_key_count(cls, data):
461         r"""Decode RFC 4880's string-to-key count
462
463         >>> PGPPacket._decode_string_to_key_count(b'\x97'[0])
464         753664
465         """
466         return (16 + (data & 15)) << ((data >> 4) + cls._string_to_key_expbias)
467
468     def _parse_string_to_key_specifier(self, data):
469         self['string-to-key-type'] = self._string_to_key_types[data[0]]
470         offset = 1
471         if self['string-to-key-type'] == 'simple':
472             self['string-to-key-hash-algorithm'] = self._hash_algorithms[
473                 data[offset]]
474             offset += 1
475         elif self['string-to-key-type'] == 'salted':
476             self['string-to-key-hash-algorithm'] = self._hash_algorithms[
477                 data[offset]]
478             offset += 1
479             self['string-to-key-salt'] = data[offset: offset + 8]
480             offset += 8
481         elif self['string-to-key-type'] == 'iterated and salted':
482             self['string-to-key-hash-algorithm'] = self._hash_algorithms[
483                 data[offset]]
484             offset += 1
485             self['string-to-key-salt'] = data[offset: offset + 8]
486             offset += 8
487             self['string-to-key-count'] = self._decode_string_to_key_count(
488                 data=data[offset])
489             offset += 1
490         else:
491             raise NotImplementedError(
492                 'string-to-key type {}'.format(self['string-to-key-type']))
493         return offset
494
495     def _parse_public_key_packet(self, data):
496         self._parse_generic_public_key_packet(data=data)
497
498     def _parse_public_subkey_packet(self, data):
499         self._parse_generic_public_key_packet(data=data)
500
501     def _parse_generic_public_key_packet(self, data):
502         self['key-version'] = data[0]
503         offset = 1
504         if self['key-version'] != 4:
505             raise NotImplementedError(
506                 'public (sub)key packet version {}'.format(
507                     self['key-version']))
508         length = 5
509         self['creation-time'], algorithm = _struct.unpack(
510             '>IB', data[offset: offset + length])
511         offset += length
512         self['public-key-algorithm'] = self._public_key_algorithms[algorithm]
513         if self['public-key-algorithm'].startswith('rsa '):
514             o, self['public-modulus'] = self._parse_multiprecision_integer(
515                 data[offset:])
516             offset += o
517             o, self['public-exponent'] = self._parse_multiprecision_integer(
518                 data[offset:])
519             offset += o
520         elif self['public-key-algorithm'].startswith('dsa '):
521             o, self['prime'] = self._parse_multiprecision_integer(
522                 data[offset:])
523             offset += o
524             o, self['group-order'] = self._parse_multiprecision_integer(
525                 data[offset:])
526             offset += o
527             o, self['group-generator'] = self._parse_multiprecision_integer(
528                 data[offset:])
529             offset += o
530             o, self['public-key'] = self._parse_multiprecision_integer(
531                 data[offset:])
532             offset += o
533         elif self['public-key-algorithm'].startswith('elgamal '):
534             o, self['prime'] = self._parse_multiprecision_integer(
535                 data[offset:])
536             offset += o
537             o, self['group-generator'] = self._parse_multiprecision_integer(
538                 data[offset:])
539             offset += o
540             o, self['public-key'] = self._parse_multiprecision_integer(
541                 data[offset:])
542             offset += o
543         else:
544             raise NotImplementedError(
545                 'algorithm-specific key fields for {}'.format(
546                     self['public-key-algorithm']))
547         fingerprint = _hashlib.sha1()
548         fingerprint.update(b'\x99')
549         fingerprint.update(_struct.pack('>H', len(data)))
550         fingerprint.update(data)
551         self['fingerprint'] = fingerprint.hexdigest()
552         return offset
553
554     def _parse_secret_key_packet(self, data):
555         self._parse_generic_secret_key_packet(data=data)
556
557     def _parse_secret_subkey_packet(self, data):
558         self._parse_generic_secret_key_packet(data=data)
559
560     def _parse_generic_secret_key_packet(self, data):
561         offset = self._parse_generic_public_key_packet(data=data)
562         string_to_key_usage = data[offset]
563         offset += 1
564         if string_to_key_usage in [255, 254]:
565             self['symmetric-encryption-algorithm'] = (
566                 self._symmetric_key_algorithms[data[offset]])
567             offset += 1
568             offset += self._parse_string_to_key_specifier(data=data[offset:])
569         else:
570             self['symmetric-encryption-algorithm'] = (
571                 self._symmetric_key_algorithms[string_to_key_usage])
572         if string_to_key_usage:
573             block_size_bits = self._cipher_block_size.get(
574                 self['symmetric-encryption-algorithm'], None)
575             if block_size_bits % 8:
576                 raise NotImplementedError(
577                     ('{}-bit block size for {} is not an integer number of bytes'
578                      ).format(
579                          block_size_bits, self['symmetric-encryption-algorithm']))
580             block_size = block_size_bits // 8
581             if not block_size:
582                 raise NotImplementedError(
583                     'unknown block size for {}'.format(
584                         self['symmetric-encryption-algorithm']))
585             self['initial-vector'] = data[offset: offset + block_size]
586             offset += block_size
587             ciphertext = data[offset:]
588             offset += len(ciphertext)
589             decrypted_data = self.decrypt_symmetric_encryption(data=ciphertext)
590         else:
591             decrypted_data = data[offset:key_end]
592         if string_to_key_usage in [0, 255]:
593             key_end = -2
594         elif string_to_key_usage == 254:
595             key_end = -20
596         else:
597             key_end = 0
598         secret_key = decrypted_data[:key_end]
599         if key_end:
600             secret_key_checksum = decrypted_data[key_end:]
601             if key_end == -2:
602                 calculated_checksum = sum(secret_key) % 65536
603             else:
604                 checksum_hash = _hashlib.sha1()
605                 checksum_hash.update(secret_key)
606                 calculated_checksum = checksum_hash.digest()
607             if secret_key_checksum != calculated_checksum:
608                 raise ValueError(
609                     'corrupt secret key (checksum {} != expected {})'.format(
610                         secret_key_checksum, calculated_checksum))
611         self['secret-key'] = secret_key
612
613     def _parse_signature_subpackets(self, data):
614         offset = 0
615         while offset < len(data):
616             o, subpacket = self._parse_signature_subpacket(data=data[offset:])
617             offset += o
618             yield subpacket
619
620     def _parse_signature_subpacket(self, data):
621         subpacket = {}
622         first = data[0]
623         offset = 1
624         if first < 192:
625             length = first
626         elif first >= 192 and first < 255:
627             second = data[offset]
628             offset += 1
629             length = ((first - 192) << 8) + second + 192
630         else:
631             length = _struct.unpack(
632                 '>I', data[offset: offset + 4])[0]
633             offset += 4
634         subpacket['type'] = self._signature_subpacket_types[data[offset]]
635         offset += 1
636         subpacket_data = data[offset: offset + length - 1]
637         offset += len(subpacket_data)
638         method_name = '_parse_{}_signature_subpacket'.format(
639             self._clean_type(type=subpacket['type']))
640         method = getattr(self, method_name, None)
641         if not method:
642             raise NotImplementedError(
643                 'cannot parse signature subpacket type {!r}'.format(
644                     subpacket['type']))
645         method(data=subpacket_data, subpacket=subpacket)
646         return (offset, subpacket)
647
648     def _parse_signature_packet(self, data):
649         self['signature-version'] = data[0]
650         offset = 1
651         if self['signature-version'] != 4:
652             raise NotImplementedError(
653                 'signature packet version {}'.format(
654                     self['signature-version']))
655         self['signature-type'] = self._signature_types[data[offset]]
656         offset += 1
657         self['public-key-algorithm'] = self._public_key_algorithms[
658             data[offset]]
659         offset += 1
660         self['hash-algorithm'] = self._hash_algorithms[data[offset]]
661         offset += 1
662         hashed_count = _struct.unpack('>H', data[offset: offset + 2])[0]
663         offset += 2
664         self['hashed-subpackets'] = list(self._parse_signature_subpackets(
665             data[offset: offset + hashed_count]))
666         offset += hashed_count
667         unhashed_count = _struct.unpack('>H', data[offset: offset + 2])[0]
668         offset += 2
669         self['unhashed-subpackets'] = list(self._parse_signature_subpackets(
670             data=data[offset: offset + unhashed_count]))
671         offset += unhashed_count
672         self['signed-hash-word'] = data[offset: offset + 2]
673         offset += 2
674         self['signature'] = data[offset:]
675
676     def _parse_signature_creation_time_signature_subpacket(
677             self, data, subpacket):
678         subpacket['signature-creation-time'] = _struct.unpack('>I', data)[0]
679
680     def _parse_issuer_signature_subpacket(self, data, subpacket):
681         subpacket['issuer'] = ''.join('{:02x}'.format(byte) for byte in data)
682
683     def _parse_key_expiration_time_signature_subpacket(
684             self, data, subpacket):
685         subpacket['key-expiration-time'] = _struct.unpack('>I', data)[0]
686
687     def _parse_preferred_symmetric_algorithms_signature_subpacket(
688             self, data, subpacket):
689         subpacket['preferred-symmetric-algorithms'] = [
690             self._symmetric_key_algorithms[d] for d in data]
691
692     def _parse_preferred_hash_algorithms_signature_subpacket(
693             self, data, subpacket):
694         subpacket['preferred-hash-algorithms'] = [
695             self._hash_algorithms[d] for d in data]
696
697     def _parse_preferred_compression_algorithms_signature_subpacket(
698             self, data, subpacket):
699         subpacket['preferred-compression-algorithms'] = [
700             self._compression_algorithms[d] for d in data]
701
702     def _parse_key_server_preferences_signature_subpacket(
703             self, data, subpacket):
704         subpacket['key-server-preferences'] = set()
705         if data[0] & 0x80:
706             subpacket['key-server-preferences'].add('no-modify')
707
708     def _parse_primary_user_id_signature_subpacket(self, data, subpacket):
709         subpacket['primary-user-id'] = bool(data[0])
710
711     def _parse_key_flags_signature_subpacket(self, data, subpacket):
712         subpacket['key-flags'] = set()
713         if data[0] & 0x1:
714             subpacket['key-flags'].add('can certify')
715         if data[0] & 0x2:
716             subpacket['key-flags'].add('can sign')
717         if data[0] & 0x4:
718             subpacket['key-flags'].add('can encrypt communications')
719         if data[0] & 0x8:
720             subpacket['key-flags'].add('can encrypt storage')
721         if data[0] & 0x10:
722             subpacket['key-flags'].add('private split')
723         if data[0] & 0x20:
724             subpacket['key-flags'].add('can authenticate')
725         if data[0] & 0x80:
726             subpacket['key-flags'].add('private shared')
727
728     def _parse_features_signature_subpacket(self, data, subpacket):
729         subpacket['features'] = set()
730         if data[0] & 0x1:
731             subpacket['features'].add('modification detection')
732
733     def _parse_embedded_signature_signature_subpacket(self, data, subpacket):
734         subpacket['embedded'] = PGPPacket(key=self.key)
735         subpacket['embedded']._parse_signature_packet(data=data)
736
737     def _parse_user_id_packet(self, data):
738         self['user'] = str(data, 'utf-8')
739
740     def to_bytes(self):
741         method_name = '_serialize_{}'.format(self._clean_type())
742         method = getattr(self, method_name, None)
743         if not method:
744             raise NotImplementedError(
745                 'cannot serialize packet type {!r}'.format(self['type']))
746         body = method()
747         self['length'] = len(body)
748         return b''.join([
749             self._serialize_header(),
750             body,
751             ])
752
753     def _serialize_header(self):
754         always_one = 1
755         new_format = 0
756         type_code = self._reverse(self._packet_types, self['type'])
757         packet_tag = (
758             always_one * (1 << 7) |
759             new_format * (1 << 6) |
760             type_code * (1 << 2) |
761             self['length-type']
762             )
763         length_bytes, length_type = self._old_format_packet_length_type[
764             self['length-type']]
765         length_format = '>{}'.format(length_type)
766         length_data = _struct.pack(length_format, self['length'])
767         return b''.join([
768             bytes([packet_tag]),
769             length_data,
770             ])
771
772     @staticmethod
773     def _serialize_multiprecision_integer(integer):
774         r"""Serialize RFC 4880's multipricision integers
775
776         >>> PGPPacket._serialize_multiprecision_integer(1)
777         b'\x00\x01\x01'
778         >>> PGPPacket._serialize_multiprecision_integer(511)
779         b'\x00\t\x01\xff'
780         """
781         bit_length = int(_math.log(integer, 2)) + 1
782         chunks = [
783             _struct.pack('>H', bit_length),
784             ]
785         while integer > 0:
786             chunks.insert(1, bytes([integer & 0xff]))
787             integer = integer >> 8
788         return b''.join(chunks)
789
790     @classmethod
791     def _encode_string_to_key_count(cls, count):
792         r"""Encode RFC 4880's string-to-key count
793
794         >>> PGPPacket._encode_string_to_key_count(753664)
795         b'\x97'
796         """
797         coded_count = 0
798         count = count >> cls._string_to_key_expbias
799         while not count & 1:
800             count = count >> 1
801             coded_count += 1 << 4
802         coded_count += count & 15
803         return bytes([coded_count])
804
805     def _serialize_string_to_key_specifier(self):
806         string_to_key_type = bytes([
807             self._reverse(
808                 self._string_to_key_types, self['string-to-key-type']),
809             ])
810         chunks = [string_to_key_type]
811         if self['string-to-key-type'] == 'simple':
812             chunks.append(bytes([self._reverse(
813                 self._hash_algorithms, self['string-to-key-hash-algorithm'])]))
814         elif self['string-to-key-type'] == 'salted':
815             chunks.append(bytes([self._reverse(
816                 self._hash_algorithms, self['string-to-key-hash-algorithm'])]))
817             chunks.append(self['string-to-key-salt'])
818         elif self['string-to-key-type'] == 'iterated and salted':
819             chunks.append(bytes([self._reverse(
820                 self._hash_algorithms, self['string-to-key-hash-algorithm'])]))
821             chunks.append(self['string-to-key-salt'])
822             chunks.append(self._encode_string_to_key_count(
823                 count=self['string-to-key-count']))
824         else:
825             raise NotImplementedError(
826                 'string-to-key type {}'.format(self['string-to-key-type']))
827         return offset
828         return b''.join(chunks)
829
830     def _serialize_public_key_packet(self):
831         return self._serialize_generic_public_key_packet()
832
833     def _serialize_public_subkey_packet(self):
834         return self._serialize_generic_public_key_packet()
835
836     def _serialize_generic_public_key_packet(self):
837         key_version = bytes([self['key-version']])
838         chunks = [key_version]
839         if self['key-version'] != 4:
840             raise NotImplementedError(
841                 'public (sub)key packet version {}'.format(
842                     self['key-version']))
843         chunks.append(_struct.pack('>I', self['creation-time']))
844         chunks.append(bytes([self._reverse(
845             self._public_key_algorithms, self['public-key-algorithm'])]))
846         if self['public-key-algorithm'].startswith('rsa '):
847             chunks.append(self._serialize_multiprecision_integer(
848                 self['public-modulus']))
849             chunks.append(self._serialize_multiprecision_integer(
850                 self['public-exponent']))
851         elif self['public-key-algorithm'].startswith('dsa '):
852             chunks.append(self._serialize_multiprecision_integer(
853                 self['prime']))
854             chunks.append(self._serialize_multiprecision_integer(
855                 self['group-order']))
856             chunks.append(self._serialize_multiprecision_integer(
857                 self['group-generator']))
858             chunks.append(self._serialize_multiprecision_integer(
859                 self['public-key']))
860         elif self['public-key-algorithm'].startswith('elgamal '):
861             chunks.append(self._serialize_multiprecision_integer(
862                 self['prime']))
863             chunks.append(self._serialize_multiprecision_integer(
864                 self['group-generator']))
865             chunks.append(self._serialize_multiprecision_integer(
866                 self['public-key']))
867         else:
868             raise NotImplementedError(
869                 'algorithm-specific key fields for {}'.format(
870                     self['public-key-algorithm']))
871         return b''.join(chunks)
872
873     def _string_to_key(self, string, key_size):
874         if key_size % 8:
875             raise ValueError(
876                 '{}-bit key is not an integer number of bytes'.format(
877                     key_size))
878         key_size_bytes = key_size // 8
879         hash_name = self._hashlib_name[
880             self['string-to-key-hash-algorithm']]
881         string_hash = _hashlib.new(hash_name)
882         hashes = _math.ceil(key_size_bytes / string_hash.digest_size)
883         key = b''
884         if self['string-to-key-type'] == 'simple':
885             update_bytes = string
886         elif self['string-to-key-type'] in [
887                 'salted',
888                 'iterated and salted',
889                 ]:
890             update_bytes = self['string-to-key-salt'] + string
891             if self['string-to-key-type'] == 'iterated and salted':
892                 count = self['string-to-key-count']
893                 if count < len(update_bytes):
894                     count = len(update_bytes)
895         else:
896             raise NotImplementedError(
897                 'key calculation for string-to-key type {}'.format(
898                     self['string-to-key-type']))
899         for padding in range(hashes):
900             string_hash = _hashlib.new(hash_name)
901             string_hash.update(padding * b'\x00')
902             if self['string-to-key-type'] in [
903                     'simple',
904                     'salted',
905                     ]:
906                 string_hash.update(update_bytes)
907             elif self['string-to-key-type'] == 'iterated and salted':
908                 remaining = count
909                 while remaining > 0:
910                     string_hash.update(update_bytes[:remaining])
911                     remaining -= len(update_bytes)
912             key += string_hash.digest()
913         key = key[:key_size_bytes]
914         return key
915
916     def decrypt_symmetric_encryption(self, data):
917         """Decrypt OpenPGP's Cipher Feedback mode"""
918         algorithm = self['symmetric-encryption-algorithm']
919         module = self._crypto_module[algorithm]
920         key_size = self._key_size[algorithm]
921         segment_size_bits = self._cipher_block_size[algorithm]
922         if segment_size_bits % 8:
923             raise NotImplementedError(
924                 ('{}-bit segment size for {} is not an integer number of bytes'
925                  ).format(segment_size_bits, algorithm))
926         segment_size_bytes = segment_size_bits // 8
927         padding = segment_size_bytes - len(data) % segment_size_bytes
928         if padding:
929             data += b'\x00' * padding
930         passphrase = _getpass.getpass(
931             'passphrase for {}: '.format(self['fingerprint'][-8:]))
932         passphrase = passphrase.encode('ascii')
933         key = self._string_to_key(string=passphrase, key_size=key_size)
934         cipher = module.new(
935             key=key,
936             mode=module.MODE_CFB,
937             IV=self['initial-vector'],
938             segment_size=segment_size_bits)
939         plaintext = cipher.decrypt(data)
940         if padding:
941             plaintext = plaintext[:-padding]
942         return plaintext
943
944
945 class PGPKey (object):
946     """An OpenPGP key with public and private parts.
947
948     From RFC 4880 [1]:
949
950       OpenPGP users may transfer public keys.  The essential elements
951       of a transferable public key are as follows:
952
953       - One Public-Key packet
954       - Zero or more revocation signatures
955       - One or more User ID packets
956       - After each User ID packet, zero or more Signature packets
957         (certifications)
958       - Zero or more User Attribute packets
959       - After each User Attribute packet, zero or more Signature
960         packets (certifications)
961       - Zero or more Subkey packets
962       - After each Subkey packet, one Signature packet, plus
963         optionally a revocation
964
965     Secret keys have a similar packet stream [2]:
966
967       OpenPGP users may transfer secret keys.  The format of a
968       transferable secret key is the same as a transferable public key
969       except that secret-key and secret-subkey packets are used
970       instead of the public key and public-subkey packets.
971       Implementations SHOULD include self-signatures on any user IDs
972       and subkeys, as this allows for a complete public key to be
973       automatically extracted from the transferable secret key.
974       Implementations MAY choose to omit the self-signatures,
975       especially if a transferable public key accompanies the
976       transferable secret key.
977
978     [1]: http://tools.ietf.org/search/rfc4880#section-11.1
979     [2]: http://tools.ietf.org/search/rfc4880#section-11.2
980     """
981     def __init__(self, fingerprint):
982         self.fingerprint = fingerprint
983         self.public_packets = None
984         self.secret_packets = None
985
986     def __str__(self):
987         lines = ['key: {}'.format(self.fingerprint)]
988         if self.public_packets:
989             lines.append('  public:')
990             for packet in self.public_packets:
991                 lines.extend(self._str_packet(packet=packet, prefix='    '))
992         if self.secret_packets:
993             lines.append('  secret:')
994             for packet in self.secret_packets:
995                 lines.extend(self._str_packet(packet=packet, prefix='    '))
996         return '\n'.join(lines)
997
998     def _str_packet(self, packet, prefix):
999         lines = str(packet).split('\n')
1000         return [prefix + line for line in lines]
1001
1002     def import_from_gpg(self):
1003         key_export = _get_stdout(
1004             ['gpg', '--export', self.fingerprint])
1005         self.public_packets = list(
1006             self._packets_from_bytes(data=key_export))
1007         if self.public_packets[0]['type'] != 'public-key packet':
1008             raise ValueError(
1009                 '{} does not start with a public-key packet'.format(
1010                     self.fingerprint))
1011         key_secret_export = _get_stdout(
1012             ['gpg', '--export-secret-keys', self.fingerprint])
1013         self.secret_packets = list(
1014             self._packets_from_bytes(data=key_secret_export))
1015         if self.secret_packets[0]['type'] != 'secret-key packet':
1016             raise ValueError(
1017                 '{} does not start with a secret-key packet'.format(
1018                     self.fingerprint))
1019
1020     def _packets_from_bytes(self, data):
1021         offset = 0
1022         while offset < len(data):
1023             packet = PGPPacket(key=self)
1024             offset += packet.from_bytes(data=data[offset:])
1025             yield packet
1026
1027     def export_to_gpg(self):
1028         raise NotImplemetedError('export to gpg')
1029
1030     def import_from_key(self, key):
1031         """Migrate the (sub)keys into this key"""
1032         pass
1033
1034
1035 def migrate(old_key, new_key):
1036     """Add the old key and sub-keys to the new key
1037
1038     For example, to upgrade your master key, while preserving old
1039     signatures you'd made.  You will lose signature *on* your old key
1040     though, since sub-keys can't be signed (I don't think).
1041     """
1042     old_key = PGPKey(fingerprint=old_key)
1043     old_key.import_from_gpg()
1044     new_key = PGPKey(fingerprint=new_key)
1045     new_key.import_from_gpg()
1046     new_key.import_from_key(key=old_key)
1047
1048     print(old_key)
1049     print(new_key)
1050
1051
1052 if __name__ == '__main__':
1053     import sys as _sys
1054
1055     old_key, new_key = _sys.argv[1:3]
1056     migrate(old_key=old_key, new_key=new_key)