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_key_flags_signature_subpacket(self, subpacket):
296 return ', '.join(x for x in sorted(subpacket['key-flags']))
298 def _str_embedded_signature_signature_subpacket(self, subpacket):
299 return subpacket['embedded']['signature-type']
301 def _str_user_id_packet(self):
304 def from_bytes(self, data):
305 offset = self._parse_header(data=data)
306 packet = data[offset:offset + self['length']]
307 if len(packet) < self['length']:
308 raise ValueError('packet too short ({} < {})'.format(
309 len(packet), self['length']))
310 offset += self['length']
311 method_name = '_parse_{}'.format(self._clean_type())
312 method = getattr(self, method_name, None)
314 raise NotImplementedError(
315 'cannot parse packet type {!r}'.format(self['type']))
319 def _parse_header(self, data):
322 always_one = packet_tag & 1 << 7
324 raise ValueError('most significant packet tag bit not set')
325 self['new-format'] = packet_tag & 1 << 6
326 if self['new-format']:
327 type_code = packet_tag & 0b111111
328 raise NotImplementedError('new-format packet length')
330 type_code = packet_tag >> 2 & 0b1111
331 self['length-type'] = packet_tag & 0b11
332 length_bytes, length_type = self._old_format_packet_length_type[
335 raise NotImplementedError(
336 'old-format packet of indeterminate length')
337 length_format = '>{}'.format(length_type)
338 length_data = data[offset: offset + length_bytes]
339 offset += length_bytes
340 self['length'] = _struct.unpack(length_format, length_data)[0]
341 self['type'] = self._packet_types[type_code]
345 def _parse_multiprecision_integer(data):
346 r"""Parse RFC 4880's multiprecision integers
348 >>> PGPPacket._parse_multiprecision_integer(b'\x00\x01\x01')
350 >>> PGPPacket._parse_multiprecision_integer(b'\x00\x09\x01\xff')
353 bits = _struct.unpack('>H', data[:2])[0]
355 length = (bits + 7) // 8
357 for i in range(length):
358 value += data[offset + i] * 1 << (8 * (length - i - 1))
360 return (offset, value)
362 def _parse_string_to_key_specifier(self, data):
363 self['string-to-key-type'] = self._string_to_key_types[data[0]]
365 if self['string-to-key-type'] == 'simple':
366 self['string-to-key-hash-algorithm'] = self._hash_algorithms[
369 elif self['string-to-key-type'] == 'salted':
370 self['string-to-key-hash-algorithm'] = self._hash_algorithms[
373 self['string-to-key-salt'] = data[offset: offset + 8]
375 elif self['string-to-key-type'] == 'iterated and salted':
376 self['string-to-key-hash-algorithm'] = self._hash_algorithms[
379 self['string-to-key-salt'] = data[offset: offset + 8]
381 self['string-to-key-coded-count'] = data[offset]
384 raise NotImplementedError(
385 'string-to-key type {}'.format(self['string-to-key-type']))
388 def _parse_public_key_packet(self, data):
389 self._parse_generic_public_key_packet(data=data)
391 def _parse_public_subkey_packet(self, data):
392 self._parse_generic_public_key_packet(data=data)
394 def _parse_generic_public_key_packet(self, data):
395 self['key-version'] = data[0]
397 if self['key-version'] != 4:
398 raise NotImplementedError(
399 'public (sub)key packet version {}'.format(
400 self['key-version']))
402 self['creation-time'], algorithm = _struct.unpack(
403 '>IB', data[offset: offset + length])
405 self['public-key-algorithm'] = self._public_key_algorithms[algorithm]
406 if self['public-key-algorithm'].startswith('rsa '):
407 o, self['public-modulus'] = self._parse_multiprecision_integer(
410 o, self['public-exponent'] = self._parse_multiprecision_integer(
413 elif self['public-key-algorithm'].startswith('dsa '):
414 o, self['prime'] = self._parse_multiprecision_integer(
417 o, self['group-order'] = self._parse_multiprecision_integer(
420 o, self['group-generator'] = self._parse_multiprecision_integer(
423 o, self['public-key'] = self._parse_multiprecision_integer(
426 elif self['public-key-algorithm'].startswith('elgamal '):
427 o, self['prime'] = self._parse_multiprecision_integer(
430 o, self['group-generator'] = self._parse_multiprecision_integer(
433 o, self['public-key'] = self._parse_multiprecision_integer(
437 raise NotImplementedError(
438 'algorithm-specific key fields for {}'.format(
439 self['public-key-algorithm']))
440 fingerprint = _hashlib.sha1()
441 fingerprint.update(b'\x99')
442 fingerprint.update(_struct.pack('>H', len(data)))
443 fingerprint.update(data)
444 self['fingerprint'] = fingerprint.hexdigest()
447 def _parse_secret_key_packet(self, data):
448 self._parse_generic_secret_key_packet(data=data)
450 def _parse_secret_subkey_packet(self, data):
451 self._parse_generic_secret_key_packet(data=data)
453 def _parse_generic_secret_key_packet(self, data):
454 offset = self._parse_generic_public_key_packet(data=data)
455 string_to_key_usage = data[offset]
457 if string_to_key_usage in [255, 254]:
458 self['symmetric-encryption-algorithm'] = (
459 self._symmetric_key_algorithms[data[offset]])
461 offset += self._parse_string_to_key_specifier(data=data[offset:])
463 self['symmetric-encryption-algorithm'] = (
464 self._symmetric_key_algorithms[string_to_key_usage])
465 if string_to_key_usage:
466 block_size_bits = self._cipher_block_size.get(
467 self['symmetric-encryption-algorithm'], None)
468 if block_size_bits % 8:
469 raise NotImplementedError(
470 ('{}-bit block size for {} is not an integer number of bytes'
472 block_size_bits, self['symmetric-encryption-algorithm']))
473 block_size = block_size_bits // 8
475 raise NotImplementedError(
476 'unknown block size for {}'.format(
477 self['symmetric-encryption-algorithm']))
478 self['initial-vector'] = data[offset: offset + block_size]
480 if string_to_key_usage in [0, 255]:
484 self['secret-key'] = data[offset:key_end]
486 self['secret-key-checksum'] = data[key_end:]
488 def _parse_signature_subpackets(self, data):
490 while offset < len(data):
491 o, subpacket = self._parse_signature_subpacket(data=data[offset:])
495 def _parse_signature_subpacket(self, data):
501 elif first >= 192 and first < 255:
502 second = data[offset]
504 length = ((first - 192) << 8) + second + 192
506 length = _struct.unpack(
507 '>I', data[offset: offset + 4])[0]
509 subpacket['type'] = self._signature_subpacket_types[data[offset]]
511 subpacket_data = data[offset: offset + length - 1]
512 offset += len(subpacket_data)
513 method_name = '_parse_{}_signature_subpacket'.format(
514 self._clean_type(type=subpacket['type']))
515 method = getattr(self, method_name, None)
517 raise NotImplementedError(
518 'cannot parse signature subpacket type {!r}'.format(
520 method(data=subpacket_data, subpacket=subpacket)
521 return (offset, subpacket)
523 def _parse_signature_packet(self, data):
524 self['signature-version'] = data[0]
526 if self['signature-version'] != 4:
527 raise NotImplementedError(
528 'signature packet version {}'.format(
529 self['signature-version']))
530 self['signature-type'] = self._signature_types[data[offset]]
532 self['public-key-algorithm'] = self._public_key_algorithms[
535 self['hash-algorithm'] = self._hash_algorithms[data[offset]]
537 hashed_count = _struct.unpack('>H', data[offset: offset + 2])[0]
539 self['hashed-subpackets'] = list(self._parse_signature_subpackets(
540 data[offset: offset + hashed_count]))
541 offset += hashed_count
542 unhashed_count = _struct.unpack('>H', data[offset: offset + 2])[0]
544 self['unhashed-subpackets'] = list(self._parse_signature_subpackets(
545 data=data[offset: offset + unhashed_count]))
546 offset += unhashed_count
547 self['signed-hash-word'] = data[offset: offset + 2]
549 self['signature'] = data[offset:]
551 def _parse_issuer_signature_subpacket(self, data, subpacket):
552 subpacket['issuer'] = ''.join('{:02x}'.format(byte) for byte in data)
554 def _parse_key_flags_signature_subpacket(self, data, subpacket):
555 subpacket['key-flags'] = set()
557 subpacket['key-flags'].add('can certify')
559 subpacket['key-flags'].add('can sign')
561 subpacket['key-flags'].add('can encrypt communications')
563 subpacket['key-flags'].add('can encrypt storage')
565 subpacket['key-flags'].add('private split')
567 subpacket['key-flags'].add('can authenticate')
569 subpacket['key-flags'].add('private shared')
571 def _parse_embedded_signature_signature_subpacket(self, data, subpacket):
572 subpacket['embedded'] = PGPPacket()
573 subpacket['embedded']._parse_signature_packet(data=data)
575 def _parse_user_id_packet(self, data):
576 self['user'] = str(data, 'utf-8')
582 def packets_from_bytes(data):
584 while offset < len(data):
586 offset += packet.from_bytes(data=data[offset:])
590 class PGPKey (object):
591 def __init__(self, fingerprint):
592 self.fingerprint = fingerprint
593 self.public_packets = None
594 self.secret_packets = None
597 lines = ['key: {}'.format(self.fingerprint)]
598 if self.public_packets:
599 lines.append(' public:')
600 for packet in self.public_packets:
601 lines.extend(self._str_packet(packet=packet, prefix=' '))
602 if self.secret_packets:
603 lines.append(' secret:')
604 for packet in self.secret_packets:
605 lines.extend(self._str_packet(packet=packet, prefix=' '))
606 return '\n'.join(lines)
608 def _str_packet(self, packet, prefix):
609 lines = str(packet).split('\n')
610 return [prefix + line for line in lines]
612 def import_from_gpg(self):
613 key_export = _get_stdout(
614 ['gpg', '--export', self.fingerprint])
615 self.public_packets = list(
616 packets_from_bytes(data=key_export))
617 if self.public_packets[0]['type'] != 'public-key packet':
619 '{} does not start with a public-key packet'.format(
621 key_secret_export = _get_stdout(
622 ['gpg', '--export-secret-keys', self.fingerprint])
623 self.secret_packets = list(
624 packets_from_bytes(data=key_secret_export))
626 def export_to_gpg(self):
627 raise NotImplemetedError('export to gpg')
629 def import_from_key(self, key):
630 """Migrate the (sub)keys into this key"""
634 def migrate(old_key, new_key):
635 """Add the old key and sub-keys to the new key
637 For example, to upgrade your master key, while preserving old
638 signatures you'd made. You will lose signature *on* your old key
639 though, since sub-keys can't be signed (I don't think).
641 old_key = PGPKey(fingerprint=old_key)
642 old_key.import_from_gpg()
643 new_key = PGPKey(fingerprint=new_key)
644 new_key.import_from_gpg()
645 new_key.import_from_key(key=old_key)
651 if __name__ == '__main__':
654 old_key, new_key = _sys.argv[1:3]
655 migrate(old_key=old_key, new_key=new_key)