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_embedded_signature_signature_subpacket(self, subpacket):
296 return subpacket['embedded']['signature-type']
298 def _str_user_id_packet(self):
301 def from_bytes(self, data):
302 offset = self._parse_header(data=data)
303 packet = data[offset:offset + self['length']]
304 if len(packet) < self['length']:
305 raise ValueError('packet too short ({} < {})'.format(
306 len(packet), self['length']))
307 offset += self['length']
308 method_name = '_parse_{}'.format(self._clean_type())
309 method = getattr(self, method_name, None)
311 raise NotImplementedError(
312 'cannot parse packet type {!r}'.format(self['type']))
316 def _parse_header(self, data):
319 always_one = packet_tag & 1 << 7
321 raise ValueError('most significant packet tag bit not set')
322 self['new-format'] = packet_tag & 1 << 6
323 if self['new-format']:
324 type_code = packet_tag & 0b111111
325 raise NotImplementedError('new-format packet length')
327 type_code = packet_tag >> 2 & 0b1111
328 self['length-type'] = packet_tag & 0b11
329 length_bytes, length_type = self._old_format_packet_length_type[
332 raise NotImplementedError(
333 'old-format packet of indeterminate length')
334 length_format = '>{}'.format(length_type)
335 length_data = data[offset: offset + length_bytes]
336 offset += length_bytes
337 self['length'] = _struct.unpack(length_format, length_data)[0]
338 self['type'] = self._packet_types[type_code]
342 def _parse_multiprecision_integer(data):
343 r"""Parse RFC 4880's multiprecision integers
345 >>> PGPPacket._parse_multiprecision_integer(b'\x00\x01\x01')
347 >>> PGPPacket._parse_multiprecision_integer(b'\x00\x09\x01\xff')
350 bits = _struct.unpack('>H', data[:2])[0]
352 length = (bits + 7) // 8
354 for i in range(length):
355 value += data[offset + i] * 1 << (8 * (length - i - 1))
357 return (offset, value)
359 def _parse_string_to_key_specifier(self, data):
360 self['string-to-key-type'] = self._string_to_key_types[data[0]]
362 if self['string-to-key-type'] == 'simple':
363 self['string-to-key-hash-algorithm'] = self._hash_algorithms[
366 elif self['string-to-key-type'] == 'salted':
367 self['string-to-key-hash-algorithm'] = self._hash_algorithms[
370 self['string-to-key-salt'] = data[offset: offset + 8]
372 elif self['string-to-key-type'] == 'iterated and salted':
373 self['string-to-key-hash-algorithm'] = self._hash_algorithms[
376 self['string-to-key-salt'] = data[offset: offset + 8]
378 self['string-to-key-coded-count'] = data[offset]
381 raise NotImplementedError(
382 'string-to-key type {}'.format(self['string-to-key-type']))
385 def _parse_public_key_packet(self, data):
386 self._parse_generic_public_key_packet(data=data)
388 def _parse_public_subkey_packet(self, data):
389 self._parse_generic_public_key_packet(data=data)
391 def _parse_generic_public_key_packet(self, data):
392 self['key-version'] = data[0]
394 if self['key-version'] != 4:
395 raise NotImplementedError(
396 'public (sub)key packet version {}'.format(
397 self['key-version']))
399 self['creation-time'], algorithm = _struct.unpack(
400 '>IB', data[offset: offset + length])
402 self['public-key-algorithm'] = self._public_key_algorithms[algorithm]
403 if self['public-key-algorithm'].startswith('rsa '):
404 o, self['public-modulus'] = self._parse_multiprecision_integer(
407 o, self['public-exponent'] = self._parse_multiprecision_integer(
410 elif self['public-key-algorithm'].startswith('dsa '):
411 o, self['prime'] = self._parse_multiprecision_integer(
414 o, self['group-order'] = self._parse_multiprecision_integer(
417 o, self['group-generator'] = self._parse_multiprecision_integer(
420 o, self['public-key'] = self._parse_multiprecision_integer(
423 elif self['public-key-algorithm'].startswith('elgamal '):
424 o, self['prime'] = self._parse_multiprecision_integer(
427 o, self['group-generator'] = self._parse_multiprecision_integer(
430 o, self['public-key'] = self._parse_multiprecision_integer(
434 raise NotImplementedError(
435 'algorithm-specific key fields for {}'.format(
436 self['public-key-algorithm']))
437 fingerprint = _hashlib.sha1()
438 fingerprint.update(b'\x99')
439 fingerprint.update(_struct.pack('>H', len(data)))
440 fingerprint.update(data)
441 self['fingerprint'] = fingerprint.hexdigest()
444 def _parse_secret_key_packet(self, data):
445 self._parse_generic_secret_key_packet(data=data)
447 def _parse_secret_subkey_packet(self, data):
448 self._parse_generic_secret_key_packet(data=data)
450 def _parse_generic_secret_key_packet(self, data):
451 offset = self._parse_generic_public_key_packet(data=data)
452 string_to_key_usage = data[offset]
454 if string_to_key_usage in [255, 254]:
455 self['symmetric-encryption-algorithm'] = (
456 self._symmetric_key_algorithms[data[offset]])
458 offset += self._parse_string_to_key_specifier(data=data[offset:])
460 self['symmetric-encryption-algorithm'] = (
461 self._symmetric_key_algorithms[string_to_key_usage])
462 if string_to_key_usage:
463 block_size_bits = self._cipher_block_size.get(
464 self['symmetric-encryption-algorithm'], None)
465 if block_size_bits % 8:
466 raise NotImplementedError(
467 ('{}-bit block size for {} is not an integer number of bytes'
469 block_size_bits, self['symmetric-encryption-algorithm']))
470 block_size = block_size_bits // 8
472 raise NotImplementedError(
473 'unknown block size for {}'.format(
474 self['symmetric-encryption-algorithm']))
475 self['initial-vector'] = data[offset: offset + block_size]
477 if string_to_key_usage in [0, 255]:
481 self['secret-key'] = data[offset:key_end]
483 self['secret-key-checksum'] = data[key_end:]
485 def _parse_signature_subpackets(self, data):
487 while offset < len(data):
488 o, subpacket = self._parse_signature_subpacket(data=data[offset:])
492 def _parse_signature_subpacket(self, data):
498 elif first >= 192 and first < 255:
499 second = data[offset]
501 length = ((first - 192) << 8) + second + 192
503 length = _struct.unpack(
504 '>I', data[offset: offset + 4])[0]
506 subpacket['type'] = self._signature_subpacket_types[data[offset]]
508 subpacket_data = data[offset: offset + length - 1]
509 offset += len(subpacket_data)
510 method_name = '_parse_{}_signature_subpacket'.format(
511 self._clean_type(type=subpacket['type']))
512 method = getattr(self, method_name, None)
514 raise NotImplementedError(
515 'cannot parse signature subpacket type {!r}'.format(
517 method(data=subpacket_data, subpacket=subpacket)
518 return (offset, subpacket)
520 def _parse_signature_packet(self, data):
521 self['signature-version'] = data[0]
523 if self['signature-version'] != 4:
524 raise NotImplementedError(
525 'signature packet version {}'.format(
526 self['signature-version']))
527 self['signature-type'] = self._signature_types[data[offset]]
529 self['public-key-algorithm'] = self._public_key_algorithms[
532 self['hash-algorithm'] = self._hash_algorithms[data[offset]]
534 hashed_count = _struct.unpack('>H', data[offset: offset + 2])[0]
536 self['hashed-subpackets'] = list(self._parse_signature_subpackets(
537 data[offset: offset + hashed_count]))
538 offset += hashed_count
539 unhashed_count = _struct.unpack('>H', data[offset: offset + 2])[0]
541 self['unhashed-subpackets'] = list(self._parse_signature_subpackets(
542 data=data[offset: offset + unhashed_count]))
543 offset += unhashed_count
544 self['signed-hash-word'] = data[offset: offset + 2]
546 self['signature'] = data[offset:]
548 def _parse_issuer_signature_subpacket(self, data, subpacket):
549 subpacket['issuer'] = ''.join('{:02x}'.format(byte) for byte in data)
551 def _parse_embedded_signature_signature_subpacket(self, data, subpacket):
552 subpacket['embedded'] = PGPPacket()
553 subpacket['embedded']._parse_signature_packet(data=data)
555 def _parse_user_id_packet(self, data):
556 self['user'] = str(data, 'utf-8')
562 def packets_from_bytes(data):
564 while offset < len(data):
566 offset += packet.from_bytes(data=data[offset:])
570 class PGPKey (object):
571 def __init__(self, fingerprint):
572 self.fingerprint = fingerprint
573 self.public_packets = None
574 self.secret_packets = None
577 lines = ['key: {}'.format(self.fingerprint)]
578 if self.public_packets:
579 lines.append(' public:')
580 for packet in self.public_packets:
581 lines.extend(self._str_packet(packet=packet, prefix=' '))
582 if self.secret_packets:
583 lines.append(' secret:')
584 for packet in self.secret_packets:
585 lines.extend(self._str_packet(packet=packet, prefix=' '))
586 return '\n'.join(lines)
588 def _str_packet(self, packet, prefix):
589 lines = str(packet).split('\n')
590 return [prefix + line for line in lines]
592 def import_from_gpg(self):
593 key_export = _get_stdout(
594 ['gpg', '--export', self.fingerprint])
595 self.public_packets = list(
596 packets_from_bytes(data=key_export))
597 if self.public_packets[0]['type'] != 'public-key packet':
599 '{} does not start with a public-key packet'.format(
601 key_secret_export = _get_stdout(
602 ['gpg', '--export-secret-keys', self.fingerprint])
603 self.secret_packets = list(
604 packets_from_bytes(data=key_secret_export))
606 def export_to_gpg(self):
607 raise NotImplemetedError('export to gpg')
609 def import_from_key(self, key):
610 """Migrate the (sub)keys into this key"""
614 def migrate(old_key, new_key):
615 """Add the old key and sub-keys to the new key
617 For example, to upgrade your master key, while preserving old
618 signatures you'd made. You will lose signature *on* your old key
619 though, since sub-keys can't be signed (I don't think).
621 old_key = PGPKey(fingerprint=old_key)
622 old_key.import_from_gpg()
623 new_key = PGPKey(fingerprint=new_key)
624 new_key.import_from_gpg()
625 new_key.import_from_key(key=old_key)
631 if __name__ == '__main__':
634 old_key, new_key = _sys.argv[1:3]
635 migrate(old_key=old_key, new_key=new_key)