How to use PGPy - 10 common examples

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 / pgpy / packet / packets.py View on Github external
m = bytearray(self.ct.decrypt(decrypter, *decargs))

        """
        The value "m" in the above formulas is derived from the session key
        as follows.  First, the session key is prefixed with a one-octet
        algorithm identifier that specifies the symmetric encryption
        algorithm used to encrypt the following Symmetrically Encrypted Data
        Packet.  Then a two-octet checksum is appended, which is equal to the
        sum of the preceding session key octets, not including the algorithm
        identifier, modulo 65536.  This value is then encoded as described in
        PKCS#1 block encoding EME-PKCS1-v1_5 in Section 7.2.1 of [RFC3447] to
        form the "m" value used in the formulas above.  See Section 13.1 of
        this document for notes on OpenPGP's use of PKCS#1.
        """

        symalg = SymmetricKeyAlgorithm(m[0])
        del m[0]

        symkey = m[:symalg.key_size // 8]
        del m[:symalg.key_size // 8]

        checksum = self.bytes_to_int(m[:2])
        del m[:2]

        if not sum(symkey) % 65536 == checksum:  # pragma: no cover
            raise PGPDecryptionError("{:s} decryption failed".format(self.pkalg.name))

        return (symalg, symkey)
github SecurityInnovation / PGPy / tests / test_04_copy.py View on Github external
from datetime import datetime
    from enum import Enum

    # do some type checking to determine if we should check the identity of an object member
    # these types are singletons
    if isinstance(obj, (Enum, bool, type(None))):
        return False

    # these types are immutable
    if isinstance(obj, (six.string_types, datetime)):
        return False

    # 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
github SecurityInnovation / PGPy / tests / test_10_exceptions.py View on Github external
k.add_uid(u, usage={KeyFlags.Certify, KeyFlags.Sign}, hashes=[HashAlgorithm.SHA1])

    sk = PGPKey.new(PubKeyAlgorithm.RSAEncryptOrSign, 512)
    k.add_subkey(sk, usage={KeyFlags.EncryptCommunications})

    return k


key_algs = [ pka for pka in PubKeyAlgorithm if pka.can_gen and not pka.deprecated ]
key_algs_unim = [ pka for pka in PubKeyAlgorithm if not pka.can_gen and not pka.deprecated ]
key_algs_rsa_depr = [ pka for pka in PubKeyAlgorithm if pka.deprecated and pka is not PubKeyAlgorithm.FormerlyElGamalEncryptOrSign ]

key_algs_badsizes = {
    PubKeyAlgorithm.RSAEncryptOrSign: [256],
    PubKeyAlgorithm.DSA: [512],
    PubKeyAlgorithm.ECDSA: [curve for curve in EllipticCurveOID if not curve.can_gen],
    PubKeyAlgorithm.ECDH: [curve for curve in EllipticCurveOID if not curve.can_gen],
}
badkeyspec = [ (alg, size) for alg in key_algs_badsizes.keys() for size in key_algs_badsizes[alg] ]


class TestArmorable(object):
    # some basic test cases specific to the Armorable mixin class
    def test_malformed_base64(self):
        # 'asdf' base64-encoded becomes 'YXNkZg=='
        # remove one of the pad characters and we should get a PGPError
        data = '-----BEGIN PGP SOMETHING-----\n' \
               '\n' \
               'YXNkZg=\n' \
               '=ZEO6\n' \
               '-----END PGP SOMETHING-----\n'
        with pytest.raises(PGPError):
github SecurityInnovation / PGPy / tests / test_10_exceptions.py View on Github external
return PGPKey.new(PubKeyAlgorithm.RSAEncryptOrSign, 512)


@pytest.fixture(scope='module')
def temp_key():
    u = PGPUID.new('User')
    k = PGPKey.new(PubKeyAlgorithm.RSAEncryptOrSign, 512)
    k.add_uid(u, usage={KeyFlags.Certify, KeyFlags.Sign}, hashes=[HashAlgorithm.SHA1])

    sk = PGPKey.new(PubKeyAlgorithm.RSAEncryptOrSign, 512)
    k.add_subkey(sk, usage={KeyFlags.EncryptCommunications})

    return k


key_algs = [ pka for pka in PubKeyAlgorithm if pka.can_gen and not pka.deprecated ]
key_algs_unim = [ pka for pka in PubKeyAlgorithm if not pka.can_gen and not pka.deprecated ]
key_algs_rsa_depr = [ pka for pka in PubKeyAlgorithm if pka.deprecated and pka is not PubKeyAlgorithm.FormerlyElGamalEncryptOrSign ]

key_algs_badsizes = {
    PubKeyAlgorithm.RSAEncryptOrSign: [256],
    PubKeyAlgorithm.DSA: [512],
    PubKeyAlgorithm.ECDSA: [curve for curve in EllipticCurveOID if not curve.can_gen],
    PubKeyAlgorithm.ECDH: [curve for curve in EllipticCurveOID if not curve.can_gen],
}
badkeyspec = [ (alg, size) for alg in key_algs_badsizes.keys() for size in key_algs_badsizes[alg] ]


class TestArmorable(object):
    # some basic test cases specific to the Armorable mixin class
    def test_malformed_base64(self):
        # 'asdf' base64-encoded becomes 'YXNkZg=='
github trustcrypto / python-onlykey / tests / PGP_message.py View on Github external
def makekey():
    n = ok.getpub()
    if len(n) == 128:
        priv_key = pgpy.PGPKey.new(PubKeyAlgorithm.RSAEncryptOrSign, 1024)
    if len(n) == 256:
        priv_key = pgpy.PGPKey.new(PubKeyAlgorithm.RSAEncryptOrSign, 2048)
    if len(n) == 384:
        priv_key = pgpy.PGPKey.new(PubKeyAlgorithm.RSAEncryptOrSign, 3072)
    if len(n) == 512:
        priv_key = pgpy.PGPKey.new(PubKeyAlgorithm.RSAEncryptOrSign, 4096)
    #uid = pgpy.PGPUID.new('Abraham Lincoln', comment='Honest Abe', email='abraham.lincoln@whitehouse.gov')
    #priv_key.add_uid(uid, usage={KeyFlags.Sign}, hashes=[HashAlgorithm.SHA512, HashAlgorithm.SHA256],
    #        compression=[CompressionAlgorithm.BZ2, CompressionAlgorithm.Uncompressed],
    #        key_expires=timedelta(days=365))
    #p = n[:(len(n)/2)]
    #q = n[(len(n)/2):]
    n = n.encode("HEX")
    N = long(n, 16)
    #p = p.encode("HEX")
    #p = long(p, 16)
    #q = q.encode("HEX")
    #q = long(q, 16)
    e = int('10001', 16)
    #pub = rsatogpg(e,N,p,q,'Nikola Tesla')
github trustcrypto / python-onlykey / tests / PGP_message.py View on Github external
def makekey():
    n = ok.getpub()
    if len(n) == 128:
        priv_key = pgpy.PGPKey.new(PubKeyAlgorithm.RSAEncryptOrSign, 1024)
    if len(n) == 256:
        priv_key = pgpy.PGPKey.new(PubKeyAlgorithm.RSAEncryptOrSign, 2048)
    if len(n) == 384:
        priv_key = pgpy.PGPKey.new(PubKeyAlgorithm.RSAEncryptOrSign, 3072)
    if len(n) == 512:
        priv_key = pgpy.PGPKey.new(PubKeyAlgorithm.RSAEncryptOrSign, 4096)
    #uid = pgpy.PGPUID.new('Abraham Lincoln', comment='Honest Abe', email='abraham.lincoln@whitehouse.gov')
    #priv_key.add_uid(uid, usage={KeyFlags.Sign}, hashes=[HashAlgorithm.SHA512, HashAlgorithm.SHA256],
    #        compression=[CompressionAlgorithm.BZ2, CompressionAlgorithm.Uncompressed],
    #        key_expires=timedelta(days=365))
    #p = n[:(len(n)/2)]
    #q = n[(len(n)/2):]
    n = n.encode("HEX")
    N = long(n, 16)
    #p = p.encode("HEX")
    #p = long(p, 16)
github SecurityInnovation / PGPy / tests / test_03_armor.py View on Github external
('is_unlocked',   True),
         ('key_algorithm', PubKeyAlgorithm.ECDSA),
         ('magic',         "PUBLIC KEY BLOCK"),
         ('parent',        None),
         ('signers',       set()),],

    'tests/testdata/blocks/eccseckey.asc':
        [('created',       datetime(2010, 9, 17, 20, 33, 49)),
         ('expires_at',    None),
         ('fingerprint',   "502D 1A53 65D1 C0CA A699 4539 0BA5 2DF0 BAA5 9D9C"),
         ('is_expired',    False),
         ('is_primary',    True),
         ('is_protected',  True),
         ('is_public',     False),
         ('is_unlocked',   False),
         ('key_algorithm', PubKeyAlgorithm.ECDSA),
         ('magic',         "PRIVATE KEY BLOCK"),
         ('parent',        None),
         ('signers',       set()),],

    'tests/testdata/blocks/dsaseckey.asc':
        [('created',       datetime(2017, 2, 21, 19, 21, 41)),
         ('expires_at',    None),
         ('fingerprint',   "2B5B BB14 3BA0 B290 DCEE 6668 B798 AE89 9087 7201"),
         ('is_expired',    False),
         ('is_primary',    True),
         ('is_protected',  True),
         ('is_public',     False),
         ('is_unlocked',   False),
         ('key_algorithm', PubKeyAlgorithm.DSA),],

    'tests/testdata/blocks/dsapubkey.asc':
github SecurityInnovation / PGPy / tests / test_10_exceptions.py View on Github external
sk = PGPKey.new(PubKeyAlgorithm.RSAEncryptOrSign, 512)
    k.add_subkey(sk, usage={KeyFlags.EncryptCommunications})

    return k


key_algs = [ pka for pka in PubKeyAlgorithm if pka.can_gen and not pka.deprecated ]
key_algs_unim = [ pka for pka in PubKeyAlgorithm if not pka.can_gen and not pka.deprecated ]
key_algs_rsa_depr = [ pka for pka in PubKeyAlgorithm if pka.deprecated and pka is not PubKeyAlgorithm.FormerlyElGamalEncryptOrSign ]

key_algs_badsizes = {
    PubKeyAlgorithm.RSAEncryptOrSign: [256],
    PubKeyAlgorithm.DSA: [512],
    PubKeyAlgorithm.ECDSA: [curve for curve in EllipticCurveOID if not curve.can_gen],
    PubKeyAlgorithm.ECDH: [curve for curve in EllipticCurveOID if not curve.can_gen],
}
badkeyspec = [ (alg, size) for alg in key_algs_badsizes.keys() for size in key_algs_badsizes[alg] ]


class TestArmorable(object):
    # some basic test cases specific to the Armorable mixin class
    def test_malformed_base64(self):
        # 'asdf' base64-encoded becomes 'YXNkZg=='
        # remove one of the pad characters and we should get a PGPError
        data = '-----BEGIN PGP SOMETHING-----\n' \
               '\n' \
               'YXNkZg=\n' \
               '=ZEO6\n' \
               '-----END PGP SOMETHING-----\n'
        with pytest.raises(PGPError):
            Armorable.ascii_unarmor(data)
github SecurityInnovation / PGPy / tests / test_10_exceptions.py View on Github external
def rsa_sec():
    return PGPKey.from_file('tests/testdata/keys/rsa.1.sec.asc')[0]
github SecurityInnovation / PGPy / tests / test_99_regressions.py View on Github external
"+b4enZ/Z6qehoAdY1t4QYmA2PebKuerBXjIF1RWsPQDpu3GIZw4oBbdu5oUGB4I9\n" \
          "yIepindM2b2I9dlY3ct4uhRbBmXPFcslmJ1K4pCurXvr4Po4DCcWqUmsGUQQbI1G\n" \
          "UyAzSad7u9y3CRqhHFwzyFRRfl+/mgB2a6XvbGlG5Dkp1g7T/HIVJu+zv58AQkFw\n" \
          "+ABuWNKCXa3TB51bkiBQlkRTSAu2tVZ8hVGZE+wUw0o9rLiy6mldFvbLABEBAAGJ\n" \
          "AR8EGAEKAAkFAlOaNYoCGwwACgkQwPIhDg8ZPc1uDwf/SGoiZHjUsTWm4gZgZCzA\n" \
          "jOpZs7dKjLL8Wm5G3HTFIGX0O8HCzQJARWq05N6EYmI4nPXxu08ba30SubybSeFU\n" \
          "+iAPymqm2YNXrE2RwLWko78M0r9enUep6SvbGKnukPG7lz/33PsxIVyATfMmcmzV\n" \
          "4chyC7pICTwgHv/zC3S/k7GoS82Z39LO4R4aDa4aubNq6mx4eHUd0MSnYud1IzRx\n" \
          "D8cPxh9fCdoW0OpddqKNczAvO4bl5wwDafrEa7HpIX/sMVMZXo2h6TkitdLCdEfk\n" \
          "tgEjS0hTsFtfwsXt9TKi1x3HJIbcm8t78ubpWXepB/iNKVzv4punFHhKiz54ZFyN\n" \
          "dQ==\n" \
          "=lqIH\n" \
          "-----END PGP PUBLIC KEY BLOCK-----\n"

    # load the keypair above
    sk = PGPKey()
    sk.parse(sec)
    pk = PGPKey()
    pk.parse(pub)

    sigsubject = bytearray(b"Hello!I'm a test document.I'm going to get signed a bunch of times.KBYE!")

    sig = PGPSignature.new(SignatureType.BinaryDocument, PubKeyAlgorithm.RSAEncryptOrSign, HashAlgorithm.SHA512,
                           sk.fingerprint.keyid)
    sig._signature.subpackets['h_CreationTime'][-1].created = datetime(2014, 8, 6, 23, 28, 51)
    sig._signature.subpackets.update_hlen()
    hdata = sig.hashdata(sigsubject)
    sig._signature.hash2 = hashlib.new('sha512', hdata).digest()[:2]

    # create the signature
    signature = sk.__key__.__privkey__().sign(hdata, padding.PKCS1v15(), hashes.SHA512())
    sig._signature.signature.from_signer(signature)