How to use the pgpy.constants.KeyFlags function in PGPy

To help you get started, we’ve selected a few PGPy examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github leapcode / soledad / tests / e2e / utils.py View on Github external
def gen_key(username):
    print("generating OpenPGP key pair")
    key = pgpy.PGPKey.new(PubKeyAlgorithm.RSAEncryptOrSign, 4096)
    uid = pgpy.PGPUID.new(username, email='%s@%s' % (username, _provider))
    key.add_uid(
        uid,
        usage={KeyFlags.EncryptCommunications},
        hashes=[HashAlgorithm.SHA512],
        ciphers=[SymmetricKeyAlgorithm.AES256],
        compression=[CompressionAlgorithm.Uncompressed]
    )
    return key
github SecurityInnovation / PGPy / tests / test_05_actions.py View on Github external
def test_verify_invalid_sig(self, pkspec, string):
        # test verifying an invalid signature
        u = PGPUID.new('asdf')
        k = PGPKey.new(*pkspec)
        k.add_uid(u, usage={KeyFlags.Certify, KeyFlags.Sign}, hashes=[HashAlgorithm.SHA1])

        # sign the string with extra characters, so that verifying just string fails
        sig = k.sign(string + 'asdf')
        sv = k.pubkey.verify(string, sig)
        assert not sv
        assert sig in sv
github SecurityInnovation / PGPy / tests / test_05_actions.py View on Github external
alg, size = skspec
        if not alg.can_gen:
            pytest.xfail('Key algorithm {} not yet supported'.format(alg.name))

        if isinstance(size, EllipticCurveOID) and ((not size.can_gen) or size.curve.name not in _openssl_get_supported_curves()):
            pytest.xfail('Curve {} not yet supported'.format(size.curve.name))

        key = self.keys[pkspec]
        subkey = PGPKey.new(*skspec)

        # before adding subkey to key, the key packet should be a PrivKeyV4, not a PrivSubKeyV4
        assert isinstance(subkey._key, PrivKeyV4)
        assert not isinstance(subkey._key, PrivSubKeyV4)

        key.add_subkey(subkey, usage={KeyFlags.EncryptCommunications})

        # now that we've added it, it should be a PrivSubKeyV4
        assert isinstance(subkey._key, PrivSubKeyV4)

        # self-verify
        with warnings.catch_warnings():
            warnings.simplefilter('ignore')
            assert key.verify(subkey)

            sv = key.verify(key)
        assert sv
        assert subkey in sv

        if gpg:
            # try to verify with GPG
            self.gpg_verify_key(key)
github SecurityInnovation / PGPy / tests / test_05_actions.py View on Github external
def test_add_altuid(self, pkspec):
        if pkspec not in self.keys:
            pytest.skip('Keyspec {} not in keys; must not have generated'.format(pkspec))

        key = self.keys[pkspec]
        uid = PGPUID.new('T. Keyerson', 'Secondary UID', 'testkey@localhost.local')

        expiration = datetime.utcnow() + timedelta(days=2)

        # add all of the sbpackets that only work on self-certifications
        with warnings.catch_warnings():
            warnings.simplefilter('ignore')
            key.add_uid(uid,
                        usage=[KeyFlags.Certify, KeyFlags.Sign],
                        ciphers=[SymmetricKeyAlgorithm.AES256, SymmetricKeyAlgorithm.Camellia256],
                        hashes=[HashAlgorithm.SHA384],
                        compression=[CompressionAlgorithm.ZLIB],
                        key_expiration=expiration,
                        keyserver_flags={KeyServerPreferences.NoModify},
                        keyserver='about:none',
                        primary=False)

        sig = uid.selfsig

        assert sig.type == SignatureType.Positive_Cert
        assert sig.cipherprefs == [SymmetricKeyAlgorithm.AES256, SymmetricKeyAlgorithm.Camellia256]
        assert sig.hashprefs == [HashAlgorithm.SHA384]
        assert sig.compprefs == [CompressionAlgorithm.ZLIB]
        assert sig.features == {Features.ModificationDetection}
        assert sig.key_expiration == expiration - key.created
github trustcrypto / python-onlykey / tests / PGP_message.py View on Github external
while slot== 0:
    ok.displaykeylabels()
    print
    print 'Enter slot number to use (1 - 4) or enter 0 to list key labels'
    print
    slot = int(raw_input())
    ok.slot(slot)


# PGPMessage will automatically determine if this is a cleartext message or not
# message_from_file = pgpy.PGPMessage.from_file("path/to/a/message")
if action == 's':
    priv_key = makekey()
    uid = pgpy.PGPUID.new('Nikola Tesla')
    #uid._parent = priv_key
    priv_key.add_uid(uid, usage={KeyFlags.Sign, KeyFlags.EncryptCommunications, KeyFlags.EncryptStorage},
                 hashes=[HashAlgorithm.SHA256, HashAlgorithm.SHA384, HashAlgorithm.SHA512, HashAlgorithm.SHA224],
                 ciphers=[SymmetricKeyAlgorithm.AES256, SymmetricKeyAlgorithm.AES192, SymmetricKeyAlgorithm.AES128],
                 compression=[CompressionAlgorithm.ZLIB, CompressionAlgorithm.BZ2, CompressionAlgorithm.ZIP, CompressionAlgorithm.Uncompressed],
                 key_expires=timedelta(days=365))

    print
    print 'Do you want to sign a text message or add signature to a PGP Message?'
    print 't = text message, p = PGP Message'
    print
    action2 = raw_input()
    if action2 == 't':
        print
        print 'Type or paste the text message, press return to go to new line, and then press Ctrl+D or Ctrl+Z (Windows only)'
        print
        msg_blob = sys.stdin.read()
        message_from_blob = priv_key.sign2(msg_blob)
github SecurityInnovation / PGPy / pgpy / pgp.py View on Github external
    @KeyAction(KeyFlags.EncryptCommunications, KeyFlags.EncryptStorage, is_public=True)
    def encrypt(self, message, sessionkey=None, **prefs):
        """
        Encrypt a PGPMessage using this key.

        :param message: The message to encrypt.
        :type message: :py:obj:`PGPMessage`
        :optional param sessionkey: Provide a session key to use when encrypting something. Default is ``None``.
                                    If ``None``, a session key of the appropriate length will be generated randomly.

                                    .. warning::

                                        Care should be taken when making use of this option! Session keys *absolutely need*
                                        to be unpredictable! Use the ``gen_key()`` method on the desired
                                        :py:obj:`~constants.SymmetricKeyAlgorithm` to generate the session key!
        :type sessionkey: ``bytes``, ``str``
github SecurityInnovation / PGPy / pgpy / pgp.py View on Github external
def _get_key_flags(self, user=None):
        if self.is_primary:
            if user is not None:
                user = self.get_uid(user)

            elif len(self._uids) == 0:
                return {KeyFlags.Certify}

            else:
                user = next(iter(self.userids))

            # RFC 4880 says that primary keys *must* be capable of certification
            return {KeyFlags.Certify} | user.selfsig.key_flags

        return next(self.self_signatures).key_flags
github SecurityInnovation / PGPy / pgpy / packet / subpackets / signature.py View on Github external
    @flags.register(_KeyFlags)
    @flags.register(_Features)
    def flags_int(self, val):
        if self.__flags__ is None:  # pragma: no cover
            raise AttributeError("Error: __flags__ not set!")

        self._flags |= (self.__flags__ & val)
github SecurityInnovation / PGPy / pgpy / pgp.py View on Github external
    @KeyAction(KeyFlags.Sign, is_unlocked=True, is_public=False)
    def sign(self, subject, **prefs):
        """
        Sign text, a message, or a timestamp using this key.

        :param subject: The text to be signed
        :type subject: ``str``, :py:obj:`~pgpy.PGPMessage`, ``None``
        :raises: :py:exc:`~pgpy.errors.PGPError` if the key is passphrase-protected and has not been unlocked
        :raises: :py:exc:`~pgpy.errors.PGPError` if the key is public
        :returns: :py:obj:`PGPSignature`

        The following optional keyword arguments can be used with :py:meth:`PGPKey.sign`, as well as
        :py:meth:`PGPKey.certify`,  :py:meth:`PGPKey.revoke`, and :py:meth:`PGPKey.bind`:

        :keyword expires: Set an expiration date for this signature
        :type expires: :py:obj:`~datetime.datetime`, :py:obj:`~datetime.timedelta`
        :keyword notation: Add arbitrary notation data to this signature.