3 import getpass as _getpass
4 import hashlib as _hashlib
7 import subprocess as _subprocess
8 import struct as _struct
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
16 def _get_stdout(args, stdin=None):
19 stdin_pipe = _subprocess.PIPE
20 p = _subprocess.Popen(args, stdin=stdin_pipe, stdout=_subprocess.PIPE)
21 stdout, stderr = p.communicate(stdin)
24 raise RuntimeError(status)
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
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',
49 11: 'literal data 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',
62 _public_key_algorithms = {
63 1: 'rsa (encrypt or sign)',
64 2: 'rsa encrypt-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',
85 _symmetric_key_algorithms = {
86 0: 'plaintext or unencrypted data',
93 7: 'aes with 128-bit key',
94 8: 'aes with 192-bit key',
95 9: 'aes with 256-bit key',
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,
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,
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,
134 _compression_algorithms = {
177 _hashlib_name = { # map OpenPGP-based names to hashlib names
180 'ripe-md/160': 'ripemd160',
187 _string_to_key_types = {
191 3: 'iterated and salted',
205 _string_to_key_expbias = 6
208 0x00: 'binary document',
209 0x01: 'canonical text document',
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',
218 0x20: 'key revocation',
219 0x28: 'subkey revocation',
220 0x30: 'certification revocation',
222 0x50: 'third-party confirmation',
225 _signature_subpacket_types = {
228 2: 'signature creation time',
229 3: 'signature expiration time',
230 4: 'exportable certification',
231 5: 'trust signature',
232 6: 'regular expression',
235 9: 'key expiration time',
236 10: 'placeholder for backward compatibility',
237 11: 'preferred symmetric algorithms',
238 12: 'revocation key',
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',
254 28: 'signer user id',
255 29: 'reason for revocation',
257 31: 'signature target',
258 32: 'embedded signature',
272 _clean_type_regex = _re.compile('\W+')
274 def _clean_type(self, type=None):
277 return self._clean_type_regex.sub('_', type)
280 def _reverse(dict, value):
281 """Reverse lookups in dictionaries
283 >>> PGPPacket._reverse(PGPPacket._packet_types, 'public-key packet')
286 return [k for k,v in dict.items() if v == value][0]
289 method_name = '_str_{}'.format(self._clean_type())
290 method = getattr(self, method_name, None)
294 return '{}: {}'.format(self['type'], details)
296 def _str_public_key_packet(self):
297 return self._str_generic_key_packet()
299 def _str_public_subkey_packet(self):
300 return self._str_generic_key_packet()
302 def _str_generic_key_packet(self):
303 return self['fingerprint'][-8:].upper()
305 def _str_secret_key_packet(self):
306 return self._str_generic_secret_key_packet()
308 def _str_secret_subkey_packet(self):
309 return self._str_generic_secret_key_packet()
311 def _str_generic_secret_key_packet(self):
312 lines = [self._str_generic_key_packet()]
314 ('symmetric encryption',
315 'symmetric-encryption-algorithm'),
316 ('s2k hash', 'string-to-key-hash-algorithm'),
317 ('s2k count', 'string-to-key-count'),
318 ('s2k salt', 'string-to-key-salt'),
319 ('IV', 'initial-vector'),
323 if isinstance(value, bytes):
324 value = ' '.join('{:02x}'.format(byte) for byte in value)
325 lines.append(' {}: {}'.format(label, value))
326 return '\n'.join(lines)
328 def _str_signature_packet(self):
329 lines = [self['signature-type']]
330 if self['hashed-subpackets']:
331 lines.append(' hashed subpackets:')
332 lines.extend(self._str_signature_subpackets(
333 self['hashed-subpackets'], prefix=' '))
334 if self['unhashed-subpackets']:
335 lines.append(' unhashed subpackets:')
336 lines.extend(self._str_signature_subpackets(
337 self['unhashed-subpackets'], prefix=' '))
338 return '\n'.join(lines)
340 def _str_signature_subpackets(self, subpackets, prefix):
342 for subpacket in subpackets:
343 method_name = '_str_{}_signature_subpacket'.format(
344 self._clean_type(type=subpacket['type']))
345 method = getattr(self, method_name, None)
347 lines.append(' {}: {}'.format(
349 method(subpacket=subpacket)))
351 lines.append(' {}'.format(subpacket['type']))
354 def _str_signature_creation_time_signature_subpacket(self, subpacket):
355 return str(subpacket['signature-creation-time'])
357 def _str_issuer_signature_subpacket(self, subpacket):
358 return subpacket['issuer'][-8:].upper()
360 def _str_key_expiration_time_signature_subpacket(self, subpacket):
361 return str(subpacket['key-expiration-time'])
363 def _str_preferred_symmetric_algorithms_signature_subpacket(
366 algo for algo in subpacket['preferred-symmetric-algorithms'])
368 def _str_preferred_hash_algorithms_signature_subpacket(
371 algo for algo in subpacket['preferred-hash-algorithms'])
373 def _str_preferred_compression_algorithms_signature_subpacket(
376 algo for algo in subpacket['preferred-compression-algorithms'])
378 def _str_key_server_preferences_signature_subpacket(self, subpacket):
380 x for x in sorted(subpacket['key-server-preferences']))
382 def _str_primary_user_id_signature_subpacket(self, subpacket):
383 return str(subpacket['primary-user-id'])
385 def _str_key_flags_signature_subpacket(self, subpacket):
386 return ', '.join(x for x in sorted(subpacket['key-flags']))
388 def _str_features_signature_subpacket(self, subpacket):
389 return ', '.join(x for x in sorted(subpacket['features']))
391 def _str_embedded_signature_signature_subpacket(self, subpacket):
392 return subpacket['embedded']['signature-type']
394 def _str_user_id_packet(self):
397 def from_bytes(self, data):
398 offset = self._parse_header(data=data)
399 packet = data[offset:offset + self['length']]
400 if len(packet) < self['length']:
401 raise ValueError('packet too short ({} < {})'.format(
402 len(packet), self['length']))
403 offset += self['length']
404 method_name = '_parse_{}'.format(self._clean_type())
405 method = getattr(self, method_name, None)
407 raise NotImplementedError(
408 'cannot parse packet type {!r}'.format(self['type']))
412 def _parse_header(self, data):
415 always_one = packet_tag & 1 << 7
417 raise ValueError('most significant packet tag bit not set')
418 self['new-format'] = packet_tag & 1 << 6
419 if self['new-format']:
420 type_code = packet_tag & 0b111111
421 raise NotImplementedError('new-format packet length')
423 type_code = packet_tag >> 2 & 0b1111
424 self['length-type'] = packet_tag & 0b11
425 length_bytes, length_type = self._old_format_packet_length_type[
428 raise NotImplementedError(
429 'old-format packet of indeterminate length')
430 length_format = '>{}'.format(length_type)
431 length_data = data[offset: offset + length_bytes]
432 offset += length_bytes
433 self['length'] = _struct.unpack(length_format, length_data)[0]
434 self['type'] = self._packet_types[type_code]
438 def _parse_multiprecision_integer(data):
439 r"""Parse RFC 4880's multiprecision integers
441 >>> PGPPacket._parse_multiprecision_integer(b'\x00\x01\x01')
443 >>> PGPPacket._parse_multiprecision_integer(b'\x00\x09\x01\xff')
446 bits = _struct.unpack('>H', data[:2])[0]
448 length = (bits + 7) // 8
450 for i in range(length):
451 value += data[offset + i] * 1 << (8 * (length - i - 1))
453 return (offset, value)
456 def _decode_string_to_key_count(cls, data):
457 r"""Decode RFC 4880's string-to-key count
459 >>> PGPPacket._decode_string_to_key_count(b'\x97'[0])
462 return (16 + (data & 15)) << ((data >> 4) + cls._string_to_key_expbias)
464 def _parse_string_to_key_specifier(self, data):
465 self['string-to-key-type'] = self._string_to_key_types[data[0]]
467 if self['string-to-key-type'] == 'simple':
468 self['string-to-key-hash-algorithm'] = self._hash_algorithms[
471 elif self['string-to-key-type'] == 'salted':
472 self['string-to-key-hash-algorithm'] = self._hash_algorithms[
475 self['string-to-key-salt'] = data[offset: offset + 8]
477 elif self['string-to-key-type'] == 'iterated and salted':
478 self['string-to-key-hash-algorithm'] = self._hash_algorithms[
481 self['string-to-key-salt'] = data[offset: offset + 8]
483 self['string-to-key-count'] = self._decode_string_to_key_count(
487 raise NotImplementedError(
488 'string-to-key type {}'.format(self['string-to-key-type']))
491 def _parse_public_key_packet(self, data):
492 self._parse_generic_public_key_packet(data=data)
494 def _parse_public_subkey_packet(self, data):
495 self._parse_generic_public_key_packet(data=data)
497 def _parse_generic_public_key_packet(self, data):
498 self['key-version'] = data[0]
500 if self['key-version'] != 4:
501 raise NotImplementedError(
502 'public (sub)key packet version {}'.format(
503 self['key-version']))
505 self['creation-time'], algorithm = _struct.unpack(
506 '>IB', data[offset: offset + length])
508 self['public-key-algorithm'] = self._public_key_algorithms[algorithm]
509 if self['public-key-algorithm'].startswith('rsa '):
510 o, self['public-modulus'] = self._parse_multiprecision_integer(
513 o, self['public-exponent'] = self._parse_multiprecision_integer(
516 elif self['public-key-algorithm'].startswith('dsa '):
517 o, self['prime'] = self._parse_multiprecision_integer(
520 o, self['group-order'] = self._parse_multiprecision_integer(
523 o, self['group-generator'] = self._parse_multiprecision_integer(
526 o, self['public-key'] = self._parse_multiprecision_integer(
529 elif self['public-key-algorithm'].startswith('elgamal '):
530 o, self['prime'] = self._parse_multiprecision_integer(
533 o, self['group-generator'] = self._parse_multiprecision_integer(
536 o, self['public-key'] = self._parse_multiprecision_integer(
540 raise NotImplementedError(
541 'algorithm-specific key fields for {}'.format(
542 self['public-key-algorithm']))
543 fingerprint = _hashlib.sha1()
544 fingerprint.update(b'\x99')
545 fingerprint.update(_struct.pack('>H', len(data)))
546 fingerprint.update(data)
547 self['fingerprint'] = fingerprint.hexdigest()
550 def _parse_secret_key_packet(self, data):
551 self._parse_generic_secret_key_packet(data=data)
553 def _parse_secret_subkey_packet(self, data):
554 self._parse_generic_secret_key_packet(data=data)
556 def _parse_generic_secret_key_packet(self, data):
557 offset = self._parse_generic_public_key_packet(data=data)
558 string_to_key_usage = data[offset]
560 if string_to_key_usage in [255, 254]:
561 self['symmetric-encryption-algorithm'] = (
562 self._symmetric_key_algorithms[data[offset]])
564 offset += self._parse_string_to_key_specifier(data=data[offset:])
566 self['symmetric-encryption-algorithm'] = (
567 self._symmetric_key_algorithms[string_to_key_usage])
568 if string_to_key_usage:
569 block_size_bits = self._cipher_block_size.get(
570 self['symmetric-encryption-algorithm'], None)
571 if block_size_bits % 8:
572 raise NotImplementedError(
573 ('{}-bit block size for {} is not an integer number of bytes'
575 block_size_bits, self['symmetric-encryption-algorithm']))
576 block_size = block_size_bits // 8
578 raise NotImplementedError(
579 'unknown block size for {}'.format(
580 self['symmetric-encryption-algorithm']))
581 self['initial-vector'] = data[offset: offset + block_size]
583 ciphertext = data[offset:]
584 offset += len(ciphertext)
585 decrypted_data = self.decrypt_symmetric_encryption(data=ciphertext)
587 decrypted_data = data[offset:key_end]
588 if string_to_key_usage in [0, 255]:
590 elif string_to_key_usage == 254:
594 secret_key = decrypted_data[:key_end]
596 secret_key_checksum = decrypted_data[key_end:]
598 calculated_checksum = sum(secret_key) % 65536
600 checksum_hash = _hashlib.sha1()
601 checksum_hash.update(secret_key)
602 calculated_checksum = checksum_hash.digest()
603 if secret_key_checksum != calculated_checksum:
605 'corrupt secret key (checksum {} != expected {})'.format(
606 secret_key_checksum, calculated_checksum))
607 self['secret-key'] = secret_key
609 def _parse_signature_subpackets(self, data):
611 while offset < len(data):
612 o, subpacket = self._parse_signature_subpacket(data=data[offset:])
616 def _parse_signature_subpacket(self, data):
622 elif first >= 192 and first < 255:
623 second = data[offset]
625 length = ((first - 192) << 8) + second + 192
627 length = _struct.unpack(
628 '>I', data[offset: offset + 4])[0]
630 subpacket['type'] = self._signature_subpacket_types[data[offset]]
632 subpacket_data = data[offset: offset + length - 1]
633 offset += len(subpacket_data)
634 method_name = '_parse_{}_signature_subpacket'.format(
635 self._clean_type(type=subpacket['type']))
636 method = getattr(self, method_name, None)
638 raise NotImplementedError(
639 'cannot parse signature subpacket type {!r}'.format(
641 method(data=subpacket_data, subpacket=subpacket)
642 return (offset, subpacket)
644 def _parse_signature_packet(self, data):
645 self['signature-version'] = data[0]
647 if self['signature-version'] != 4:
648 raise NotImplementedError(
649 'signature packet version {}'.format(
650 self['signature-version']))
651 self['signature-type'] = self._signature_types[data[offset]]
653 self['public-key-algorithm'] = self._public_key_algorithms[
656 self['hash-algorithm'] = self._hash_algorithms[data[offset]]
658 hashed_count = _struct.unpack('>H', data[offset: offset + 2])[0]
660 self['hashed-subpackets'] = list(self._parse_signature_subpackets(
661 data[offset: offset + hashed_count]))
662 offset += hashed_count
663 unhashed_count = _struct.unpack('>H', data[offset: offset + 2])[0]
665 self['unhashed-subpackets'] = list(self._parse_signature_subpackets(
666 data=data[offset: offset + unhashed_count]))
667 offset += unhashed_count
668 self['signed-hash-word'] = data[offset: offset + 2]
670 self['signature'] = data[offset:]
672 def _parse_signature_creation_time_signature_subpacket(
673 self, data, subpacket):
674 subpacket['signature-creation-time'] = _struct.unpack('>I', data)[0]
676 def _parse_issuer_signature_subpacket(self, data, subpacket):
677 subpacket['issuer'] = ''.join('{:02x}'.format(byte) for byte in data)
679 def _parse_key_expiration_time_signature_subpacket(
680 self, data, subpacket):
681 subpacket['key-expiration-time'] = _struct.unpack('>I', data)[0]
683 def _parse_preferred_symmetric_algorithms_signature_subpacket(
684 self, data, subpacket):
685 subpacket['preferred-symmetric-algorithms'] = [
686 self._symmetric_key_algorithms[d] for d in data]
688 def _parse_preferred_hash_algorithms_signature_subpacket(
689 self, data, subpacket):
690 subpacket['preferred-hash-algorithms'] = [
691 self._hash_algorithms[d] for d in data]
693 def _parse_preferred_compression_algorithms_signature_subpacket(
694 self, data, subpacket):
695 subpacket['preferred-compression-algorithms'] = [
696 self._compression_algorithms[d] for d in data]
698 def _parse_key_server_preferences_signature_subpacket(
699 self, data, subpacket):
700 subpacket['key-server-preferences'] = set()
702 subpacket['key-server-preferences'].add('no-modify')
704 def _parse_primary_user_id_signature_subpacket(self, data, subpacket):
705 subpacket['primary-user-id'] = bool(data[0])
707 def _parse_key_flags_signature_subpacket(self, data, subpacket):
708 subpacket['key-flags'] = set()
710 subpacket['key-flags'].add('can certify')
712 subpacket['key-flags'].add('can sign')
714 subpacket['key-flags'].add('can encrypt communications')
716 subpacket['key-flags'].add('can encrypt storage')
718 subpacket['key-flags'].add('private split')
720 subpacket['key-flags'].add('can authenticate')
722 subpacket['key-flags'].add('private shared')
724 def _parse_features_signature_subpacket(self, data, subpacket):
725 subpacket['features'] = set()
727 subpacket['features'].add('modification detection')
729 def _parse_embedded_signature_signature_subpacket(self, data, subpacket):
730 subpacket['embedded'] = PGPPacket()
731 subpacket['embedded']._parse_signature_packet(data=data)
733 def _parse_user_id_packet(self, data):
734 self['user'] = str(data, 'utf-8')
737 method_name = '_serialize_{}'.format(self._clean_type())
738 method = getattr(self, method_name, None)
740 raise NotImplementedError(
741 'cannot serialize packet type {!r}'.format(self['type']))
743 self['length'] = len(body)
745 self._serialize_header(),
749 def _serialize_header(self):
752 type_code = self._reverse(self._packet_types, self['type'])
754 always_one * (1 << 7) |
755 new_format * (1 << 6) |
756 type_code * (1 << 2) |
759 length_bytes, length_type = self._old_format_packet_length_type[
761 length_format = '>{}'.format(length_type)
762 length_data = _struct.pack(length_format, self['length'])
769 def _serialize_multiprecision_integer(integer):
770 r"""Serialize RFC 4880's multipricision integers
772 >>> PGPPacket._serialize_multiprecision_integer(1)
774 >>> PGPPacket._serialize_multiprecision_integer(511)
777 bit_length = int(_math.log(integer, 2)) + 1
779 _struct.pack('>H', bit_length),
782 chunks.insert(1, bytes([integer & 0xff]))
783 integer = integer >> 8
784 return b''.join(chunks)
787 def _encode_string_to_key_count(cls, count):
788 r"""Encode RFC 4880's string-to-key count
790 >>> PGPPacket._encode_string_to_key_count(753664)
794 count = count >> cls._string_to_key_expbias
797 coded_count += 1 << 4
798 coded_count += count & 15
799 return bytes([coded_count])
801 def _serialize_string_to_key_specifier(self):
802 string_to_key_type = bytes([
804 self._string_to_key_types, self['string-to-key-type']),
806 chunks = [string_to_key_type]
807 if self['string-to-key-type'] == 'simple':
808 chunks.append(bytes([self._reverse(
809 self._hash_algorithms, self['string-to-key-hash-algorithm'])]))
810 elif self['string-to-key-type'] == 'salted':
811 chunks.append(bytes([self._reverse(
812 self._hash_algorithms, self['string-to-key-hash-algorithm'])]))
813 chunks.append(self['string-to-key-salt'])
814 elif self['string-to-key-type'] == 'iterated and 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 chunks.append(self._encode_string_to_key_count(
819 count=self['string-to-key-count']))
821 raise NotImplementedError(
822 'string-to-key type {}'.format(self['string-to-key-type']))
824 return b''.join(chunks)
826 def _serialize_public_key_packet(self):
827 return self._serialize_generic_public_key_packet()
829 def _serialize_public_subkey_packet(self):
830 return self._serialize_generic_public_key_packet()
832 def _serialize_generic_public_key_packet(self):
833 key_version = bytes([self['key-version']])
834 chunks = [key_version]
835 if self['key-version'] != 4:
836 raise NotImplementedError(
837 'public (sub)key packet version {}'.format(
838 self['key-version']))
839 chunks.append(_struct.pack('>I', self['creation-time']))
840 chunks.append(bytes([self._reverse(
841 self._public_key_algorithms, self['public-key-algorithm'])]))
842 if self['public-key-algorithm'].startswith('rsa '):
843 chunks.append(self._serialize_multiprecision_integer(
844 self['public-modulus']))
845 chunks.append(self._serialize_multiprecision_integer(
846 self['public-exponent']))
847 elif self['public-key-algorithm'].startswith('dsa '):
848 chunks.append(self._serialize_multiprecision_integer(
850 chunks.append(self._serialize_multiprecision_integer(
851 self['group-order']))
852 chunks.append(self._serialize_multiprecision_integer(
853 self['group-generator']))
854 chunks.append(self._serialize_multiprecision_integer(
856 elif self['public-key-algorithm'].startswith('elgamal '):
857 chunks.append(self._serialize_multiprecision_integer(
859 chunks.append(self._serialize_multiprecision_integer(
860 self['group-generator']))
861 chunks.append(self._serialize_multiprecision_integer(
864 raise NotImplementedError(
865 'algorithm-specific key fields for {}'.format(
866 self['public-key-algorithm']))
867 return b''.join(chunks)
869 def _string_to_key(self, string, key_size):
872 '{}-bit key is not an integer number of bytes'.format(
874 key_size_bytes = key_size // 8
875 hash_name = self._hashlib_name[
876 self['string-to-key-hash-algorithm']]
877 string_hash = _hashlib.new(hash_name)
878 hashes = _math.ceil(key_size_bytes / string_hash.digest_size)
880 if self['string-to-key-type'] == 'simple':
881 update_bytes = string
882 elif self['string-to-key-type'] in [
884 'iterated and salted',
886 update_bytes = self['string-to-key-salt'] + string
887 if self['string-to-key-type'] == 'iterated and salted':
888 count = self['string-to-key-count']
889 if count < len(update_bytes):
890 count = len(update_bytes)
892 raise NotImplementedError(
893 'key calculation for string-to-key type {}'.format(
894 self['string-to-key-type']))
895 for padding in range(hashes):
896 string_hash = _hashlib.new(hash_name)
897 string_hash.update(padding * b'\x00')
898 if self['string-to-key-type'] in [
902 string_hash.update(update_bytes)
903 elif self['string-to-key-type'] == 'iterated and salted':
906 string_hash.update(update_bytes[:remaining])
907 remaining -= len(update_bytes)
908 key += string_hash.digest()
909 key = key[:key_size_bytes]
912 def decrypt_symmetric_encryption(self, data):
913 """Decrypt OpenPGP's Cipher Feedback mode"""
914 algorithm = self['symmetric-encryption-algorithm']
915 module = self._crypto_module[algorithm]
916 key_size = self._key_size[algorithm]
917 segment_size_bits = self._cipher_block_size[algorithm]
918 if segment_size_bits % 8:
919 raise NotImplementedError(
920 ('{}-bit segment size for {} is not an integer number of bytes'
921 ).format(segment_size_bits, algorithm))
922 segment_size_bytes = segment_size_bits // 8
923 padding = segment_size_bytes - len(data) % segment_size_bytes
925 data += b'\x00' * padding
926 passphrase = _getpass.getpass(
927 'passphrase for {}: '.format(self['fingerprint'][-8:]))
928 passphrase = passphrase.encode('ascii')
929 key = self._string_to_key(string=passphrase, key_size=key_size)
932 mode=module.MODE_CFB,
933 IV=self['initial-vector'],
934 segment_size=segment_size_bits)
935 plaintext = cipher.decrypt(data)
937 plaintext = plaintext[:-padding]
941 def packets_from_bytes(data):
943 while offset < len(data):
945 offset += packet.from_bytes(data=data[offset:])
949 class PGPKey (object):
950 """An OpenPGP key with public and private parts.
954 OpenPGP users may transfer public keys. The essential elements
955 of a transferable public key are as follows:
957 - One Public-Key packet
958 - Zero or more revocation signatures
959 - One or more User ID packets
960 - After each User ID packet, zero or more Signature packets
962 - Zero or more User Attribute packets
963 - After each User Attribute packet, zero or more Signature
964 packets (certifications)
965 - Zero or more Subkey packets
966 - After each Subkey packet, one Signature packet, plus
967 optionally a revocation
969 Secret keys have a similar packet stream [2]:
971 OpenPGP users may transfer secret keys. The format of a
972 transferable secret key is the same as a transferable public key
973 except that secret-key and secret-subkey packets are used
974 instead of the public key and public-subkey packets.
975 Implementations SHOULD include self-signatures on any user IDs
976 and subkeys, as this allows for a complete public key to be
977 automatically extracted from the transferable secret key.
978 Implementations MAY choose to omit the self-signatures,
979 especially if a transferable public key accompanies the
980 transferable secret key.
982 [1]: http://tools.ietf.org/search/rfc4880#section-11.1
983 [2]: http://tools.ietf.org/search/rfc4880#section-11.2
985 def __init__(self, fingerprint):
986 self.fingerprint = fingerprint
987 self.public_packets = None
988 self.secret_packets = None
991 lines = ['key: {}'.format(self.fingerprint)]
992 if self.public_packets:
993 lines.append(' public:')
994 for packet in self.public_packets:
995 lines.extend(self._str_packet(packet=packet, prefix=' '))
996 if self.secret_packets:
997 lines.append(' secret:')
998 for packet in self.secret_packets:
999 lines.extend(self._str_packet(packet=packet, prefix=' '))
1000 return '\n'.join(lines)
1002 def _str_packet(self, packet, prefix):
1003 lines = str(packet).split('\n')
1004 return [prefix + line for line in lines]
1006 def import_from_gpg(self):
1007 key_export = _get_stdout(
1008 ['gpg', '--export', self.fingerprint])
1009 self.public_packets = list(
1010 packets_from_bytes(data=key_export))
1011 if self.public_packets[0]['type'] != 'public-key packet':
1013 '{} does not start with a public-key packet'.format(
1015 key_secret_export = _get_stdout(
1016 ['gpg', '--export-secret-keys', self.fingerprint])
1017 self.secret_packets = list(
1018 packets_from_bytes(data=key_secret_export))
1019 if self.secret_packets[0]['type'] != 'secret-key packet':
1021 '{} does not start with a secret-key packet'.format(
1024 def export_to_gpg(self):
1025 raise NotImplemetedError('export to gpg')
1027 def import_from_key(self, key):
1028 """Migrate the (sub)keys into this key"""
1032 def migrate(old_key, new_key):
1033 """Add the old key and sub-keys to the new key
1035 For example, to upgrade your master key, while preserving old
1036 signatures you'd made. You will lose signature *on* your old key
1037 though, since sub-keys can't be signed (I don't think).
1039 old_key = PGPKey(fingerprint=old_key)
1040 old_key.import_from_gpg()
1041 new_key = PGPKey(fingerprint=new_key)
1042 new_key.import_from_gpg()
1043 new_key.import_from_key(key=old_key)
1049 if __name__ == '__main__':
1052 old_key, new_key = _sys.argv[1:3]
1053 migrate(old_key=old_key, new_key=new_key)