def delete_transferrable_key(self, key): if self.read_only: raise TypeError if key.fingerprint[-8:] not in self._offset_table: raise KeyError offset = self._offset_table[key.fingerprint[-8:]] self.lock_db() try: data = b'' with open(self.filename, 'rb') as fh: data = fh.read(offset) packets = [] packet_iter = parse_binary_packet_stream(fh) header_format = None for packet in packet_iter: if header_format is None: header_format = packet.header_format if packets and packet.type in ( constants.PUBLIC_KEY_PACKET_TYPE, constants.SECRET_KEY_PACKET_TYPE, ): break last_offset = fh.tell() fh.seek(last_offset) data += fh.read() with open(self.filename, 'wb') as fh: fh.write(data) self._update_offset_table() finally: self.unlock_db()
def _get_key(self, offset): self.lock_db() try: with open(self.filename, 'rb') as fh: fh.seek(offset) packets = [] packet_iter = parse_binary_packet_stream(fh) for packet in packet_iter: if packet.type == constants.COMPRESSED_DATA_PACKET_TYPE: continue elif packets and packet.type in ( constants.PUBLIC_KEY_PACKET_TYPE, constants.SECRET_KEY_PACKET_TYPE, ): break else: packets.append(packet) finally: self.unlock_db() key = None if packets and packets[0].type == constants.PUBLIC_KEY_PACKET_TYPE: key = TransferablePublicKey.from_packets(packets) elif packets and packets[0].type == constants.SECRET_KEY_PACKET_TYPE: key = TransferableSecretKey.from_packets(packets) elif packets: raise ValueError(packets[0]) else: raise KeyError() return key
def _update_offset_table(self): offset_table = {} self.lock_db() try: with open(self.filename, 'rb') as fh: packet_iter = parse_binary_packet_stream(fh) last_offset = fh.tell() for packet in packet_iter: if self._preferred_header_format is None: self._preferred_header_format = packet.header_format if packet.type in ( constants.PUBLIC_KEY_PACKET_TYPE, constants.SECRET_KEY_PACKET_TYPE, ): offset_table[packet.key_id[-8:]] = last_offset last_offset = fh.tell() finally: self.unlock_db() self._offset_table = offset_table