How to use the pgpy.PGPMessage.from_file 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 SecurityInnovation / PGPy / tests / test_04_PGP_objects.py View on Github external
def test_load_from_file(self, msgfile):
        # TODO: figure out a good way to verify that all went well here, because
        #       PGPy reorders signatures sometimes, and also unwraps compressed messages
        #       so comparing str(msg) to the contents of msgfile doesn't actually work
        msg = PGPMessage.from_file(msgfile)

        with open(msgfile, 'r') as mf:
            mt = mf.read()

            assert len(str(msg)) == len(mt)
github SecurityInnovation / PGPy / tests / test_10_exceptions.py View on Github external
def test_decrypt_wrongkey(self, targette_sec):
        msg = PGPMessage.from_file('tests/testdata/messages/message.rsa.cast5.asc')
        with pytest.raises(PGPError):
            targette_sec.decrypt(msg)
github SecurityInnovation / PGPy / tests / test_05_actions.py View on Github external
def test_gpg_cv25519_decrypt(self, abe):
        # test the decryption of X25519 generated by GnuPG
        seckey, _ = PGPKey.from_file('tests/testdata/keys/ecc.2.sec.asc')
        emsg = PGPMessage.from_file('tests/testdata/messages/message.ecdh.cv25519.asc')
        with warnings.catch_warnings():
            warnings.simplefilter('ignore')
            dmsg = seckey.decrypt(emsg)
        assert bytes(dmsg.message) == b"This message will have been encrypted"
github SecurityInnovation / PGPy / tests / test_04_copy.py View on Github external
# integers are kind of a special case.
    #   ints that do not exceed sys.maxsize are singletons, and in either case are immutable
    #   this shouldn't apply to MPIs, though, which are subclasses of int
    if isinstance(obj, int) and not isinstance(obj, pgpy.packet.types.MPI):
        return False

    return True


def ksort(key):
    # return a tuple of key, key.count('.') so we get a descending alphabetical, ascending depth ordering
    return key, key.count('.')


objs = [sig(), uid(),] + [PGPMessage.from_file(m) for m in _msgs] + [key(f) for f in _keys]
cids = ['sig', 'uid',] + [os.path.basename(m) for m in _msgs] + [os.path.basename(f) for f in _keys]


@pytest.mark.parametrize('obj', objs, ids=cids)
def test_copy_obj(request, obj):
    obj2 = copy.copy(obj)

    objflat = {name: val for name, val in walk_obj(obj, '{}.'.format(request.node.callspec.id))}
    obj2flat = {name: val for name, val in walk_obj(obj2, '{}.'.format(request.node.callspec.id))}

    for k in sorted(objflat, key=ksort):
        print("checking attribute: {} ".format(k), end="")
        if isinstance(objflat[k], pgpy.types.SorteDeque):
            print("[SorteDeque] ", end="")
            assert len(objflat[k]) == len(obj2flat[k])
github SecurityInnovation / PGPy / tests / test_05_actions.py View on Github external
from pgpy.constants import CompressionAlgorithm
from pgpy.constants import EllipticCurveOID
from pgpy.constants import Features
from pgpy.constants import HashAlgorithm
from pgpy.constants import KeyFlags
from pgpy.constants import KeyServerPreferences
from pgpy.constants import PubKeyAlgorithm
from pgpy.constants import RevocationReason
from pgpy.constants import SignatureType
from pgpy.constants import SymmetricKeyAlgorithm
from pgpy.packet import Packet
from pgpy.packet.packets import PrivKeyV4
from pgpy.packet.packets import PrivSubKeyV4


enc_msgs = [ PGPMessage.from_file(f) for f in sorted(glob.glob('tests/testdata/messages/message*.pass*.asc')) ]


class TestPGPMessage(object):
    @staticmethod
    def gpg_message(msg):
        ret = None
        with gpg.Context(offline=True) as c:
            c.set_engine_info(gpg.constants.PROTOCOL_OpenPGP, home_dir=gnupghome)
            msg, _ = c.verify(gpg.Data(string=str(msg)))
            ret = bytes(msg)
        return ret

    @staticmethod
    def gpg_decrypt(msg, passphrase):
        try:
            ret = None
github SecurityInnovation / PGPy / tests / test_10_exceptions.py View on Github external
def test_decrypt_wrongpass(self):
        msg = PGPMessage.from_file(next(f for f in glob.glob('tests/testdata/messages/message*.pass*.asc')))
        with pytest.raises(PGPDecryptionError):
            msg.decrypt("TheWrongPassword")
github TheClimateCorporation / python-dpkg / pydpkg / __init__.py View on Github external
def _process_dsc_file(self):
        """Extract the dsc message from a file: parse the dsc body
        and return an email.Message object.  Attempt to extract the
        RFC822 message from an OpenPGP message if necessary."""
        self._log.debug('process_dsc_file()')
        if not self.filename.endswith('.dsc'):
            self._log.debug(
                'File %s does not appear to be a dsc file; pressing '
                'on but we may experience some turbulence and possibly '
                'explode.', self.filename)
        try:
            self._pgp_message = pgpy.PGPMessage.from_file(self.filename)
            self._log.debug('Found pgp signed message')
            msg = message_from_string(self._pgp_message.message)
        except TypeError as ex:
            self._log.exception(ex)
            self._log.fatal(
                'dsc file %s has a corrupt signature: %s', self.filename, ex)
            raise DscBadSignatureError
        except IOError as ex:
            self._log.fatal('Could not read dsc file "%s": %s',
                            self.filename, ex)
            raise
        except (ValueError, pgpy.errors.PGPError) as ex:
            self._log.warning('dsc file %s is not signed: %s',
                              self.filename, ex)
            with open(self.filename) as fileobj:
                msg = message_from_file(fileobj)