3 import hashlib as _hashlib
5 import subprocess as _subprocess
6 import struct as _struct
9 def _get_stdout(args, stdin=None):
12 stdin_pipe = _subprocess.PIPE
13 p = _subprocess.Popen(args, stdin=stdin_pipe, stdout=_subprocess.PIPE)
14 stdout, stderr = p.communicate(stdin)
17 raise RuntimeError(status)
21 class PGPPacket (dict):
22 # http://tools.ietf.org/search/rfc4880
23 _old_format_packet_length_type = { # type: (bytes, struct type)
24 0: (1, 'B'), # 1-byte unsigned integer
25 1: (2, 'H'), # 2-byte unsigned integer
26 2: (4, 'I'), # 4-byte unsigned integer
32 1: 'public-key encrypted session key packet',
33 2: 'signature packet',
34 3: 'symmetric-key encrypted session key packet',
35 4: 'one-pass signature packet',
36 5: 'secret-key packet',
37 6: 'public-key packet',
38 7: 'secret-subkey packet',
39 8: 'compressed data packet',
40 9: 'symmetrically encrypted data packet',
42 11: 'literal data packet',
45 14: 'public-subkey packet',
46 17: 'user attribute packet',
47 18: 'sym. encrypted and integrity protected data packet',
48 19: 'modification detection code packet',
55 _public_key_algorithms = {
56 1: 'rsa (encrypt or sign)',
57 2: 'rsa encrypt-only',
59 16: 'elgamal (encrypt-only)',
60 17: 'dsa (digital signature algorithm)',
61 18: 'reserved for elliptic curve',
62 19: 'reserved for ecdsa',
63 20: 'reserved (formerly elgamal encrypt or sign)',
64 21: 'reserved for diffie-hellman',
78 _symmetric_key_algorithms = {
79 0: 'plaintext or unencrypted data',
86 7: 'aes with 128-bit key',
87 8: 'aes with 192-bit key',
88 9: 'aes with 256-bit key',
103 _cipher_block_size = { # in bits
104 'aes with 128-bit key': 128,
105 'aes with 192-bit key': 128,
106 'aes with 256-bit key': 128,
110 _compression_algorithms = {
153 _string_to_key_types = {
157 3: 'iterated and salted',
172 0x00: 'binary document',
173 0x01: 'canonical text document',
175 0x10: 'generic user id and public-key packet',
176 0x11: 'persona user id and public-key packet',
177 0x12: 'casual user id and public-key packet',
178 0x13: 'postitive user id and public-key packet',
179 0x18: 'subkey binding',
180 0x19: 'primary key binding',
182 0x20: 'key revocation',
183 0x28: 'subkey revocation',
184 0x30: 'certification revocation',
186 0x50: 'third-party confirmation',
189 _signature_subpacket_types = {
192 2: 'signature creation time',
193 3: 'signature expiration time',
194 4: 'exportable certification',
195 5: 'trust signature',
196 6: 'regular expression',
199 9: 'key expiration time',
200 10: 'placeholder for backward compatibility',
201 11: 'preferred symmetric algorithms',
202 12: 'revocation key',
211 21: 'preferred hash algorithms',
212 22: 'preferred compression algorithms',
213 23: 'key server preferences',
214 24: 'preferred key server',
215 25: 'primary user id',
218 28: 'signer user id',
219 29: 'reason for revocation',
221 31: 'signature target',
222 32: 'embedded signature',
236 _clean_type_regex = _re.compile('\W+')
238 def _clean_type(self, type=None):
241 return self._clean_type_regex.sub('_', type)
244 method_name = '_str_{}'.format(self._clean_type())
245 method = getattr(self, method_name, None)
249 return '{}: {}'.format(self['type'], details)
251 def _str_public_key_packet(self):
252 return self._str_generic_key_packet()
254 def _str_public_subkey_packet(self):
255 return self._str_generic_key_packet()
257 def _str_secret_key_packet(self):
258 return self._str_generic_key_packet()
260 def _str_secret_subkey_packet(self):
261 return self._str_generic_key_packet()
263 def _str_generic_key_packet(self):
264 return self['fingerprint'][-8:].upper()
266 def _str_signature_packet(self):
267 lines = [self['signature-type']]
268 if self['hashed-subpackets']:
269 lines.append(' hashed subpackets:')
270 lines.extend(self._str_signature_subpackets(
271 self['hashed-subpackets'], prefix=' '))
272 if self['unhashed-subpackets']:
273 lines.append(' unhashed subpackets:')
274 lines.extend(self._str_signature_subpackets(
275 self['unhashed-subpackets'], prefix=' '))
276 return '\n'.join(lines)
278 def _str_signature_subpackets(self, subpackets, prefix):
280 for subpacket in subpackets:
281 method_name = '_str_{}_signature_subpacket'.format(
282 self._clean_type(type=subpacket['type']))
283 method = getattr(self, method_name, None)
285 lines.append(' {}: {}'.format(
287 method(subpacket=subpacket)))
289 lines.append(' {}'.format(subpacket['type']))
292 def _str_issuer_signature_subpacket(self, subpacket):
293 return subpacket['issuer'][-8:].upper()
295 def _str_preferred_symmetric_algorithms_signature_subpacket(
298 algo for algo in subpacket['preferred-symmetric-algorithms'])
300 def _str_preferred_hash_algorithms_signature_subpacket(
303 algo for algo in subpacket['preferred-hash-algorithms'])
305 def _str_preferred_compression_algorithms_signature_subpacket(
308 algo for algo in subpacket['preferred-compression-algorithms'])
310 def _str_key_flags_signature_subpacket(self, subpacket):
311 return ', '.join(x for x in sorted(subpacket['key-flags']))
313 def _str_features_signature_subpacket(self, subpacket):
314 return ', '.join(x for x in sorted(subpacket['features']))
316 def _str_embedded_signature_signature_subpacket(self, subpacket):
317 return subpacket['embedded']['signature-type']
319 def _str_user_id_packet(self):
322 def from_bytes(self, data):
323 offset = self._parse_header(data=data)
324 packet = data[offset:offset + self['length']]
325 if len(packet) < self['length']:
326 raise ValueError('packet too short ({} < {})'.format(
327 len(packet), self['length']))
328 offset += self['length']
329 method_name = '_parse_{}'.format(self._clean_type())
330 method = getattr(self, method_name, None)
332 raise NotImplementedError(
333 'cannot parse packet type {!r}'.format(self['type']))
337 def _parse_header(self, data):
340 always_one = packet_tag & 1 << 7
342 raise ValueError('most significant packet tag bit not set')
343 self['new-format'] = packet_tag & 1 << 6
344 if self['new-format']:
345 type_code = packet_tag & 0b111111
346 raise NotImplementedError('new-format packet length')
348 type_code = packet_tag >> 2 & 0b1111
349 self['length-type'] = packet_tag & 0b11
350 length_bytes, length_type = self._old_format_packet_length_type[
353 raise NotImplementedError(
354 'old-format packet of indeterminate length')
355 length_format = '>{}'.format(length_type)
356 length_data = data[offset: offset + length_bytes]
357 offset += length_bytes
358 self['length'] = _struct.unpack(length_format, length_data)[0]
359 self['type'] = self._packet_types[type_code]
363 def _parse_multiprecision_integer(data):
364 r"""Parse RFC 4880's multiprecision integers
366 >>> PGPPacket._parse_multiprecision_integer(b'\x00\x01\x01')
368 >>> PGPPacket._parse_multiprecision_integer(b'\x00\x09\x01\xff')
371 bits = _struct.unpack('>H', data[:2])[0]
373 length = (bits + 7) // 8
375 for i in range(length):
376 value += data[offset + i] * 1 << (8 * (length - i - 1))
378 return (offset, value)
380 def _parse_string_to_key_specifier(self, data):
381 self['string-to-key-type'] = self._string_to_key_types[data[0]]
383 if self['string-to-key-type'] == 'simple':
384 self['string-to-key-hash-algorithm'] = self._hash_algorithms[
387 elif self['string-to-key-type'] == 'salted':
388 self['string-to-key-hash-algorithm'] = self._hash_algorithms[
391 self['string-to-key-salt'] = data[offset: offset + 8]
393 elif self['string-to-key-type'] == 'iterated and salted':
394 self['string-to-key-hash-algorithm'] = self._hash_algorithms[
397 self['string-to-key-salt'] = data[offset: offset + 8]
399 self['string-to-key-coded-count'] = data[offset]
402 raise NotImplementedError(
403 'string-to-key type {}'.format(self['string-to-key-type']))
406 def _parse_public_key_packet(self, data):
407 self._parse_generic_public_key_packet(data=data)
409 def _parse_public_subkey_packet(self, data):
410 self._parse_generic_public_key_packet(data=data)
412 def _parse_generic_public_key_packet(self, data):
413 self['key-version'] = data[0]
415 if self['key-version'] != 4:
416 raise NotImplementedError(
417 'public (sub)key packet version {}'.format(
418 self['key-version']))
420 self['creation-time'], algorithm = _struct.unpack(
421 '>IB', data[offset: offset + length])
423 self['public-key-algorithm'] = self._public_key_algorithms[algorithm]
424 if self['public-key-algorithm'].startswith('rsa '):
425 o, self['public-modulus'] = self._parse_multiprecision_integer(
428 o, self['public-exponent'] = self._parse_multiprecision_integer(
431 elif self['public-key-algorithm'].startswith('dsa '):
432 o, self['prime'] = self._parse_multiprecision_integer(
435 o, self['group-order'] = self._parse_multiprecision_integer(
438 o, self['group-generator'] = self._parse_multiprecision_integer(
441 o, self['public-key'] = self._parse_multiprecision_integer(
444 elif self['public-key-algorithm'].startswith('elgamal '):
445 o, self['prime'] = self._parse_multiprecision_integer(
448 o, self['group-generator'] = self._parse_multiprecision_integer(
451 o, self['public-key'] = self._parse_multiprecision_integer(
455 raise NotImplementedError(
456 'algorithm-specific key fields for {}'.format(
457 self['public-key-algorithm']))
458 fingerprint = _hashlib.sha1()
459 fingerprint.update(b'\x99')
460 fingerprint.update(_struct.pack('>H', len(data)))
461 fingerprint.update(data)
462 self['fingerprint'] = fingerprint.hexdigest()
465 def _parse_secret_key_packet(self, data):
466 self._parse_generic_secret_key_packet(data=data)
468 def _parse_secret_subkey_packet(self, data):
469 self._parse_generic_secret_key_packet(data=data)
471 def _parse_generic_secret_key_packet(self, data):
472 offset = self._parse_generic_public_key_packet(data=data)
473 string_to_key_usage = data[offset]
475 if string_to_key_usage in [255, 254]:
476 self['symmetric-encryption-algorithm'] = (
477 self._symmetric_key_algorithms[data[offset]])
479 offset += self._parse_string_to_key_specifier(data=data[offset:])
481 self['symmetric-encryption-algorithm'] = (
482 self._symmetric_key_algorithms[string_to_key_usage])
483 if string_to_key_usage:
484 block_size_bits = self._cipher_block_size.get(
485 self['symmetric-encryption-algorithm'], None)
486 if block_size_bits % 8:
487 raise NotImplementedError(
488 ('{}-bit block size for {} is not an integer number of bytes'
490 block_size_bits, self['symmetric-encryption-algorithm']))
491 block_size = block_size_bits // 8
493 raise NotImplementedError(
494 'unknown block size for {}'.format(
495 self['symmetric-encryption-algorithm']))
496 self['initial-vector'] = data[offset: offset + block_size]
498 if string_to_key_usage in [0, 255]:
502 self['secret-key'] = data[offset:key_end]
504 self['secret-key-checksum'] = data[key_end:]
506 def _parse_signature_subpackets(self, data):
508 while offset < len(data):
509 o, subpacket = self._parse_signature_subpacket(data=data[offset:])
513 def _parse_signature_subpacket(self, data):
519 elif first >= 192 and first < 255:
520 second = data[offset]
522 length = ((first - 192) << 8) + second + 192
524 length = _struct.unpack(
525 '>I', data[offset: offset + 4])[0]
527 subpacket['type'] = self._signature_subpacket_types[data[offset]]
529 subpacket_data = data[offset: offset + length - 1]
530 offset += len(subpacket_data)
531 method_name = '_parse_{}_signature_subpacket'.format(
532 self._clean_type(type=subpacket['type']))
533 method = getattr(self, method_name, None)
535 raise NotImplementedError(
536 'cannot parse signature subpacket type {!r}'.format(
538 method(data=subpacket_data, subpacket=subpacket)
539 return (offset, subpacket)
541 def _parse_signature_packet(self, data):
542 self['signature-version'] = data[0]
544 if self['signature-version'] != 4:
545 raise NotImplementedError(
546 'signature packet version {}'.format(
547 self['signature-version']))
548 self['signature-type'] = self._signature_types[data[offset]]
550 self['public-key-algorithm'] = self._public_key_algorithms[
553 self['hash-algorithm'] = self._hash_algorithms[data[offset]]
555 hashed_count = _struct.unpack('>H', data[offset: offset + 2])[0]
557 self['hashed-subpackets'] = list(self._parse_signature_subpackets(
558 data[offset: offset + hashed_count]))
559 offset += hashed_count
560 unhashed_count = _struct.unpack('>H', data[offset: offset + 2])[0]
562 self['unhashed-subpackets'] = list(self._parse_signature_subpackets(
563 data=data[offset: offset + unhashed_count]))
564 offset += unhashed_count
565 self['signed-hash-word'] = data[offset: offset + 2]
567 self['signature'] = data[offset:]
569 def _parse_issuer_signature_subpacket(self, data, subpacket):
570 subpacket['issuer'] = ''.join('{:02x}'.format(byte) for byte in data)
572 def _parse_preferred_symmetric_algorithms_signature_subpacket(
573 self, data, subpacket):
574 subpacket['preferred-symmetric-algorithms'] = [
575 self._symmetric_key_algorithms[d] for d in data]
577 def _parse_preferred_hash_algorithms_signature_subpacket(
578 self, data, subpacket):
579 subpacket['preferred-hash-algorithms'] = [
580 self._hash_algorithms[d] for d in data]
582 def _parse_preferred_compression_algorithms_signature_subpacket(
583 self, data, subpacket):
584 subpacket['preferred-compression-algorithms'] = [
585 self._compression_algorithms[d] for d in data]
587 def _parse_key_flags_signature_subpacket(self, data, subpacket):
588 subpacket['key-flags'] = set()
590 subpacket['key-flags'].add('can certify')
592 subpacket['key-flags'].add('can sign')
594 subpacket['key-flags'].add('can encrypt communications')
596 subpacket['key-flags'].add('can encrypt storage')
598 subpacket['key-flags'].add('private split')
600 subpacket['key-flags'].add('can authenticate')
602 subpacket['key-flags'].add('private shared')
604 def _parse_features_signature_subpacket(self, data, subpacket):
605 subpacket['features'] = set()
607 subpacket['features'].add('modification detection')
609 def _parse_embedded_signature_signature_subpacket(self, data, subpacket):
610 subpacket['embedded'] = PGPPacket()
611 subpacket['embedded']._parse_signature_packet(data=data)
613 def _parse_user_id_packet(self, data):
614 self['user'] = str(data, 'utf-8')
620 def packets_from_bytes(data):
622 while offset < len(data):
624 offset += packet.from_bytes(data=data[offset:])
628 class PGPKey (object):
629 def __init__(self, fingerprint):
630 self.fingerprint = fingerprint
631 self.public_packets = None
632 self.secret_packets = None
635 lines = ['key: {}'.format(self.fingerprint)]
636 if self.public_packets:
637 lines.append(' public:')
638 for packet in self.public_packets:
639 lines.extend(self._str_packet(packet=packet, prefix=' '))
640 if self.secret_packets:
641 lines.append(' secret:')
642 for packet in self.secret_packets:
643 lines.extend(self._str_packet(packet=packet, prefix=' '))
644 return '\n'.join(lines)
646 def _str_packet(self, packet, prefix):
647 lines = str(packet).split('\n')
648 return [prefix + line for line in lines]
650 def import_from_gpg(self):
651 key_export = _get_stdout(
652 ['gpg', '--export', self.fingerprint])
653 self.public_packets = list(
654 packets_from_bytes(data=key_export))
655 if self.public_packets[0]['type'] != 'public-key packet':
657 '{} does not start with a public-key packet'.format(
659 key_secret_export = _get_stdout(
660 ['gpg', '--export-secret-keys', self.fingerprint])
661 self.secret_packets = list(
662 packets_from_bytes(data=key_secret_export))
664 def export_to_gpg(self):
665 raise NotImplemetedError('export to gpg')
667 def import_from_key(self, key):
668 """Migrate the (sub)keys into this key"""
672 def migrate(old_key, new_key):
673 """Add the old key and sub-keys to the new key
675 For example, to upgrade your master key, while preserving old
676 signatures you'd made. You will lose signature *on* your old key
677 though, since sub-keys can't be signed (I don't think).
679 old_key = PGPKey(fingerprint=old_key)
680 old_key.import_from_gpg()
681 new_key = PGPKey(fingerprint=new_key)
682 new_key.import_from_gpg()
683 new_key.import_from_key(key=old_key)
689 if __name__ == '__main__':
692 old_key, new_key = _sys.argv[1:3]
693 migrate(old_key=old_key, new_key=new_key)