Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_add_pubsubkey_to_key(self, rsa_sec, temp_subkey):
pubtemp = temp_subkey.pubkey
with pytest.raises(PGPError):
rsa_sec.add_subkey(pubtemp)
def add_subkey(self, key, **prefs):
"""
Add a key as a subkey to this key.
:param key: A private :py:obj:`~pgpy.PGPKey` that does not have any subkeys of its own
:keyword usage: A ``set`` of key usage flags, as :py:obj:`~constants.KeyFlags` for the subkey to be added.
:type usage: ``set``
Other valid optional keyword arguments are identical to those of self-signatures for :py:meth:`PGPKey.certify`
"""
if self.is_public:
raise PGPError("Cannot add a subkey to a public key. Add the subkey to the private component first!")
if key.is_public:
raise PGPError("Cannot add a public key as a subkey to this key")
if key.is_primary:
if len(key._children) > 0:
raise PGPError("Cannot add a key that already has subkeys as a subkey!")
# convert key into a subkey
npk = PrivSubKeyV4()
npk.pkalg = key._key.pkalg
npk.created = key._key.created
npk.keymaterial = key._key.keymaterial
key._key = npk
key._key.update_hlen()
self._children[key.fingerprint.keyid] = key
key._parent = self
sig._signature.subpackets.addnew('KeyFlags', hashed=True, flags=usage)
crosssig = None
# if possible, have the subkey create a primary key binding signature
if key.key_algorithm.can_sign and prefs.pop('crosssign', True):
subkeyid = key.fingerprint.keyid
if not key.is_public:
crosssig = key.bind(self)
elif subkeyid in self.subkeys: # pragma: no cover
crosssig = self.subkeys[subkeyid].bind(self)
if crosssig is None:
if usage is None:
raise PGPError('subkey with no key usage flags (may be used for any purpose, including signing) requires a cross-signature')
if KeyFlags.Sign in usage:
raise PGPError('subkey marked for signing usage requires a cross-signature')
else:
sig._signature.subpackets.addnew('EmbeddedSignature', hashed=False, _sig=crosssig._signature)
return self._sign(key, sig, **prefs)
def check_attributes(self, key):
for attr, expected in self.conditions.items():
if getattr(key, attr) != expected:
raise PGPError("Expected: {attr:s} == {eval:s}. Got: {got:s}"
"".format(attr=attr, eval=str(expected), got=str(getattr(key, attr))))
1 octet - GNU S2K Extension Number.
If such a GNU extension is used neither an IV nor any kind of
checksum is used. The defined GNU S2K Extension Numbers are:
- 1 :: Do not store the secret part at all. No specific data
follows.
- 2 :: A stub to access smartcards. This data follows:
- One octet with the length of the following serial number.
- The serial number. Regardless of what the length octet
indicates no more than 16 octets are stored.
"""
if self.specifier == String2KeyType.GNUExtension:
if packet[:4] != b'\x00GNU':
raise PGPError("Invalid S2K GNU extension magic value")
del packet[:4]
self.gnuext = packet[0]
del packet[0]
if self.gnuext == S2KGNUExtension.Smartcard:
slen = min(packet[0], 16)
del packet[0]
self.scserial = packet[:slen]
del packet[:slen]
crosssig = None
# if possible, have the subkey create a primary key binding signature
if key.key_algorithm.can_sign and prefs.pop('crosssign', True):
subkeyid = key.fingerprint.keyid
if not key.is_public:
crosssig = key.bind(self)
elif subkeyid in self.subkeys: # pragma: no cover
crosssig = self.subkeys[subkeyid].bind(self)
if crosssig is None:
if usage is None:
raise PGPError('subkey with no key usage flags (may be used for any purpose, including signing) requires a cross-signature')
if KeyFlags.Sign in usage:
raise PGPError('subkey marked for signing usage requires a cross-signature')
else:
sig._signature.subpackets.addnew('EmbeddedSignature', hashed=False, _sig=crosssig._signature)
return self._sign(key, sig, **prefs)
ncls = MetaDispatchable._registry[(rcls, header.typeid, header.version)]
else: # pragma: no cover
ncls = None
if ncls is None:
ncls = MetaDispatchable._registry[(rcls, None)]
obj = _makeobj(ncls)
obj.header = header
try:
obj.parse(packet)
except Exception as ex:
six.raise_from(PGPError(str(ex)), ex)
else:
obj = _makeobj(cls)
return obj
def _preiter(first, iterable):
yield first
for item in iterable:
yield item
em = {}
em['keyid'] = key.fingerprint.keyid
em['flags'] = ', '.join(flag.name for flag in self.flags)
if len(self.flags):
for _key in _preiter(key, key.subkeys.values()):
if self.flags & set(_key._get_key_flags(user)):
break
else: # pragma: no cover
raise PGPError("Key {keyid:s} does not have the required usage flag {flags:s}".format(**em))
else:
_key = key
if _key is not key:
em['subkeyid'] = _key.fingerprint.keyid
logging.debug("Key {keyid:s} does not have the required usage flag {flags:s}; using subkey {subkeyid:s}"
"".format(**em), stacklevel=4)
yield _key
:raises: :py:exc:`~errors.PGPError` if the key is not private, or protected but not unlocked.
:raises: :py:exc:`~errors.PGPDecryptionError` if decryption fails for any other reason.
:returns: A new :py:obj:`PGPMessage` with the decrypted contents of ``message``.
"""
if not message.is_encrypted:
warnings.warn("This message is not encrypted", stacklevel=3)
return message
if self.fingerprint.keyid not in message.encrypters:
sks = set(self.subkeys)
mis = set(message.encrypters)
if sks & mis:
skid = list(sks & mis)[0]
return self.subkeys[skid].decrypt(message)
raise PGPError("Cannot decrypt the provided message with this key")
pkesk = next(pk for pk in message._sessionkeys if pk.pkalg == self.key_algorithm and pk.encrypter == self.fingerprint.keyid)
alg, key = pkesk.decrypt_sk(self._key)
# now that we have the symmetric cipher used and the key, we can decrypt the actual message
decmsg = PGPMessage()
decmsg.parse(message.message.decrypt(key, alg))
return decmsg