MCPcopy Create free account
hub / github.com/SecurityInnovation/PGPy / unlock

Method unlock

pgpy/pgp.py:1766–1818  ·  view source on GitHub ↗

Context manager method for unlocking passphrase-protected private keys. Has no effect if the key is not both private and passphrase-protected. When the context managed block is exited, the unprotected private key material is removed. Example:: privkey

(self, passphrase)

Source from the content-addressed store, hash-verified

1764
1765 @contextlib.contextmanager
1766 def unlock(self, passphrase):
1767 """
1768 Context manager method for unlocking passphrase-protected private keys. Has no effect if the key is not both
1769 private and passphrase-protected.
1770
1771 When the context managed block is exited, the unprotected private key material is removed.
1772
1773 Example::
1774
1775 privkey = PGPKey()
1776 privkey.parse(keytext)
1777
1778 assert privkey.is_protected
1779 assert privkey.is_unlocked is False
1780 # privkey.sign("some text") <- this would raise an exception
1781
1782 with privkey.unlock("TheCorrectPassphrase"):
1783 # privkey is now unlocked
1784 assert privkey.is_unlocked
1785 # so you can do things with it
1786 sig = privkey.sign("some text")
1787
1788 # privkey is no longer unlocked
1789 assert privkey.is_unlocked is False
1790
1791 Emits a :py:obj:`~warnings.UserWarning` if the key is public or not passphrase protected.
1792
1793 :param passphrase: The passphrase to be used to unlock this key.
1794 :type passphrase: ``str``
1795 :raises: :py:exc:`~pgpy.errors.PGPDecryptionError` if the passphrase is incorrect
1796 """
1797 if self.is_public:
1798 # we can't unprotect public keys because only private key material is ever protected
1799 warnings.warn("Public keys cannot be passphrase-protected", stacklevel=3)
1800 yield self
1801 return
1802
1803 if not self.is_protected:
1804 # we can't unprotect private keys that are not protected, because there is no ciphertext to decrypt
1805 warnings.warn("This key is not protected with a passphrase", stacklevel=3)
1806 yield self
1807 return
1808
1809 try:
1810 for sk in itertools.chain([self], self.subkeys.values()):
1811 sk._key.unprotect(passphrase)
1812 del passphrase
1813 yield self
1814
1815 finally:
1816 # clean up here by deleting the previously decrypted secret key material
1817 for sk in itertools.chain([self], self.subkeys.values()):
1818 sk._key.keymaterial.clear()
1819
1820 def add_uid(self, uid, selfsign=True, **prefs):
1821 """

Callers 8

test_unlock_pubkeyMethod · 0.80
test_unlockMethod · 0.80
test_unlock2Method · 0.80
test_revoke_subkeyMethod · 0.80
test_revoke_keyMethod · 0.80

Calls 2

unprotectMethod · 0.80
clearMethod · 0.80

Tested by 8

test_unlock_pubkeyMethod · 0.64
test_unlockMethod · 0.64
test_unlock2Method · 0.64
test_revoke_subkeyMethod · 0.64
test_revoke_keyMethod · 0.64