Python cryptography.hazmat.primitives.asymmetric.dsa.generate_private_key() Examples

The following are 29 code examples of cryptography.hazmat.primitives.asymmetric.dsa.generate_private_key(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module cryptography.hazmat.primitives.asymmetric.dsa , or try the search function .
Example #1
Source File: test_key_pair_authentication.py    From snowflake-connector-python with Apache License 2.0 6 votes vote down vote up
def generate_key_pair(key_length):
    private_key = rsa.generate_private_key(backend=default_backend(),
                                           public_exponent=65537,
                                           key_size=key_length)

    private_key_der = private_key.private_bytes(
        encoding=serialization.Encoding.DER,
        format=serialization.PrivateFormat.PKCS8,
        encryption_algorithm=serialization.NoEncryption())

    public_key_pem = private_key.public_key().public_bytes(
        serialization.Encoding.PEM,
        serialization.PublicFormat.SubjectPublicKeyInfo) \
        .decode("utf-8")

    # strip off header
    public_key_der_encoded = ''.join(public_key_pem.split('\n')[1:-2])

    return private_key_der, public_key_der_encoded 
Example #2
Source File: test_key_pair_authentication.py    From snowflake-connector-python with Apache License 2.0 6 votes vote down vote up
def generate_key_pair(key_length):
    private_key = rsa.generate_private_key(backend=default_backend(),
                                           public_exponent=65537,
                                           key_size=key_length)

    private_key_der = private_key.private_bytes(
        encoding=serialization.Encoding.DER,
        format=serialization.PrivateFormat.PKCS8,
        encryption_algorithm=serialization.NoEncryption())

    public_key_pem = private_key.public_key().public_bytes(
        serialization.Encoding.PEM,
        serialization.PublicFormat.SubjectPublicKeyInfo) \
        .decode("utf-8")

    # strip off header
    public_key_der_encoded = ''.join(public_key_pem.split('\n')[1:-2])

    return private_key_der, public_key_der_encoded 
Example #3
Source File: tls.py    From dcos-e2e with Apache License 2.0 6 votes vote down vote up
def generate_rsa_private_key(key_size=2048, public_exponent=65537):
    """
    Generate RSA private key.

    Args:
        key_size (int): RSA key size
        public_exponent (int): Key public exponent

    Return:
        rsa.RSAPrivateKey
    """
    return rsa.generate_private_key(
        public_exponent=public_exponent,
        key_size=key_size,
        backend=cryptography_default_backend
        ) 
Example #4
Source File: tls.py    From dcos-e2e with Apache License 2.0 6 votes vote down vote up
def generate_rsa_private_key(key_size=2048, public_exponent=65537):
    """
    Generate RSA private key.

    Args:
        key_size (int): RSA key size
        public_exponent (int): Key public exponent

    Return:
        rsa.RSAPrivateKey
    """
    return rsa.generate_private_key(
        public_exponent=public_exponent,
        key_size=key_size,
        backend=cryptography_default_backend
        ) 
Example #5
Source File: dsskey.py    From imoocc with GNU General Public License v2.0 6 votes vote down vote up
def generate(bits=1024, progress_func=None):
        """
        Generate a new private DSS key.  This factory function can be used to
        generate a new host key or authentication key.

        :param int bits: number of bits the generated key should be.
        :param function progress_func: Unused
        :return: new `.DSSKey` private key
        """
        numbers = dsa.generate_private_key(
            bits, backend=default_backend()
        ).private_numbers()
        key = DSSKey(vals=(
            numbers.public_numbers.parameter_numbers.p,
            numbers.public_numbers.parameter_numbers.q,
            numbers.public_numbers.parameter_numbers.g,
            numbers.public_numbers.y
        ))
        key.x = numbers.x
        return key

    ###  internals... 
Example #6
Source File: fields.py    From PGPy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _generate(self, key_size):
        if any(c != 0 for c in self):  # pragma: no cover
            raise PGPError("key is already populated")

        # generate some big numbers!
        pk = dsa.generate_private_key(key_size, default_backend())
        pkn = pk.private_numbers()

        self.p = MPI(pkn.public_numbers.parameter_numbers.p)
        self.q = MPI(pkn.public_numbers.parameter_numbers.q)
        self.g = MPI(pkn.public_numbers.parameter_numbers.g)
        self.y = MPI(pkn.public_numbers.y)
        self.x = MPI(pkn.x)

        del pkn
        del pk

        self._compute_chksum() 
Example #7
Source File: fields.py    From PGPy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _generate(self, key_size):
        if any(c != 0 for c in self):  # pragma: no cover
            raise PGPError("key is already populated")

        # generate some big numbers!
        pk = rsa.generate_private_key(65537, key_size, default_backend())
        pkn = pk.private_numbers()

        self.n = MPI(pkn.public_numbers.n)
        self.e = MPI(pkn.public_numbers.e)
        self.d = MPI(pkn.d)
        self.p = MPI(pkn.p)
        self.q = MPI(pkn.q)
        # from the RFC:
        # "- MPI of u, the multiplicative inverse of p, mod q."
        # or, simply, p^-1 mod p
        # rsa.rsa_crt_iqmp(p, q) normally computes q^-1 mod p,
        # so if we swap the values around we get the answer we want
        self.u = MPI(rsa.rsa_crt_iqmp(pkn.q, pkn.p))

        del pkn
        del pk

        self._compute_chksum() 
Example #8
Source File: template_filters.py    From kpm with Apache License 2.0 5 votes vote down vote up
def gen_private_dsa():
    from cryptography.hazmat.primitives import serialization
    from cryptography.hazmat.backends import default_backend
    from cryptography.hazmat.primitives.asymmetric import dsa

    private_key = dsa.generate_private_key(key_size=1024, backend=default_backend())
    pem = private_key.private_bytes(encoding=serialization.Encoding.PEM,
                                    format=serialization.PrivateFormat.TraditionalOpenSSL,
                                    encryption_algorithm=serialization.NoEncryption())
    return pem 
Example #9
Source File: test_key_pair_authentication.py    From snowflake-connector-python with Apache License 2.0 5 votes vote down vote up
def test_bad_private_key(db_parameters):
    db_config = {
        'protocol': db_parameters['protocol'],
        'account': db_parameters['account'],
        'user': db_parameters['user'],
        'host': db_parameters['host'],
        'port': db_parameters['port'],
        'database': db_parameters['database'],
        'schema': db_parameters['schema'],
        'timezone': 'UTC',
    }

    dsa_private_key = dsa.generate_private_key(key_size=2048,
                                               backend=default_backend())
    dsa_private_key_der = dsa_private_key.private_bytes(
        encoding=serialization.Encoding.DER,
        format=serialization.PrivateFormat.PKCS8,
        encryption_algorithm=serialization.NoEncryption())

    encrypted_rsa_private_key_der = rsa.generate_private_key(key_size=2048,
                                                             public_exponent=65537,
                                                             backend=default_backend()) \
        .private_bytes(encoding=serialization.Encoding.DER,
                       format=serialization.PrivateFormat.PKCS8,
                       encryption_algorithm=serialization.BestAvailableEncryption(
                           b'abcd'))

    bad_private_key_test_cases = ["abcd", 1234, b'abcd', dsa_private_key_der,
                                  encrypted_rsa_private_key_der]

    for private_key in bad_private_key_test_cases:
        db_config['private_key'] = private_key
        with pytest.raises(
                snowflake.connector.errors.ProgrammingError) as exec_info:
            snowflake.connector.connect(**db_config)
        assert (exec_info.value.errno == 251008) 
Example #10
Source File: template_filters.py    From kpm with Apache License 2.0 5 votes vote down vote up
def gen_private_rsa():
    from cryptography.hazmat.primitives import serialization
    from cryptography.hazmat.backends import default_backend
    from cryptography.hazmat.primitives.asymmetric import rsa

    private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048,
                                           backend=default_backend())
    pem = private_key.private_bytes(encoding=serialization.Encoding.PEM,
                                    format=serialization.PrivateFormat.TraditionalOpenSSL,
                                    encryption_algorithm=serialization.NoEncryption())
    return pem 
Example #11
Source File: tls.py    From dcos-e2e with Apache License 2.0 5 votes vote down vote up
def generate_ec_private_key(curve=None):
    """
    Generate EC private key.

    Args:
        curve (ec.EllipticCurve): EC if not provided SECP384R1 used.

    Return:
        ec.EllipticCurvePrivateKey
    """
    curve = ec.SECP384R1() if curve is None else curve
    return ec.generate_private_key(
        curve=curve,
        backend=cryptography_default_backend
        ) 
Example #12
Source File: tls.py    From dcos-e2e with Apache License 2.0 5 votes vote down vote up
def generate_dsa_private_key(key_size=1024):
    """
    Generate DSA private key.

    Args:
        key_size (int): Key size of DSA key.

    Return:
        ec.DSAPrivateKey
    """
    return dsa.generate_private_key(
        key_size=key_size,
        backend=cryptography_default_backend
        ) 
Example #13
Source File: tls.py    From dcos-e2e with Apache License 2.0 5 votes vote down vote up
def generate_ec_private_key(curve=None):
    """
    Generate EC private key.

    Args:
        curve (ec.EllipticCurve): EC if not provided SECP384R1 used.

    Return:
        ec.EllipticCurvePrivateKey
    """
    curve = ec.SECP384R1() if curve is None else curve
    return ec.generate_private_key(
        curve=curve,
        backend=cryptography_default_backend
        ) 
Example #14
Source File: fields.py    From PGPy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _generate(self, oid):
        if any(c != 0 for c in self):  # pragma: no cover
            raise PGPError("Key is already populated!")

        self.oid = EllipticCurveOID(oid)

        if not self.oid.can_gen:
            raise ValueError("Curve not currently supported: {}".format(oid.name))

        pk = ec.generate_private_key(self.oid.curve(), default_backend())
        pubn = pk.public_key().public_numbers()
        self.p = ECPoint.from_values(self.oid.key_size, ECPointFormat.Standard, MPI(pubn.x), MPI(pubn.y))
        self.s = MPI(pk.private_numbers().private_value)
        self._compute_chksum() 
Example #15
Source File: utils.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def generate_private_key(key_size, key_type, ecc_curve):
    """Generate a private key.

    This function assumes that you called :py:func:`~django_ca.utils.validate_key_parameters` on the input
    values and does not do any sanity checks on its own.

    Parameters
    ----------

    key_size : int
        The size of the private key (not used for ECC keys).
    key_type : {'RSA', 'DSA', 'ECC'}
        The type of the private key.
    ecc_curve : :py:class:`~cg:cryptography.hazmat.primitives.asymmetric.ec.EllipticCurve`
        The ECC curve to use for an ECC key.

    Returns
    -------

    key
        A private key of the appropriate type.
    """
    if key_type == 'DSA':
        private_key = dsa.generate_private_key(key_size=key_size, backend=default_backend())
    elif key_type == 'ECC':
        private_key = ec.generate_private_key(ecc_curve, default_backend())
    else:
        private_key = rsa.generate_private_key(public_exponent=65537, key_size=key_size,
                                               backend=default_backend())

    return private_key 
Example #16
Source File: ssh.py    From opencanary with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def getDSAKeys():
    """
    Checks for existing DSA Keys, if there are none, generates a 2048 bit
    DSA key pair, saves them to a temporary location and returns the keys
    formatted as OpenSSH keys.
    """
    public_key = os.path.join(SSH_PATH, 'id_dsa.pub')
    private_key = os.path.join(SSH_PATH, 'id_dsa')

    if not (os.path.exists(public_key) and os.path.exists(private_key)):
        ssh_key = dsa.generate_private_key(
            key_size=2048,
            backend=default_backend())
        public_key_string = ssh_key.public_key().public_bytes(
            serialization.Encoding.OpenSSH,
            serialization.PublicFormat.OpenSSH)
        private_key_string = ssh_key.private_bytes(
            serialization.Encoding.PEM,
            serialization.PrivateFormat.TraditionalOpenSSL,
            serialization.NoEncryption())
        with open(public_key, 'w+b') as key_file:
            key_file.write(public_key_string)
        with open(private_key, 'w+b') as key_file:
            key_file.write(private_key_string)
    else:
        with open(public_key) as key_file:
            public_key_string = key_file.read()
        with open(private_key) as key_file:
            private_key_string = key_file.read()

    return public_key_string, private_key_string 
Example #17
Source File: ssh.py    From opencanary with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def getRSAKeys():
    """
    Checks for existing RSA Keys, if there are none, generates a 2048 bit
    RSA key pair, saves them to a temporary location and returns the keys
    formatted as OpenSSH keys.
    """
    public_key = os.path.join(SSH_PATH, 'id_rsa.pub')
    private_key = os.path.join(SSH_PATH, 'id_rsa')

    if not (os.path.exists(public_key) and os.path.exists(private_key)):
        ssh_key = rsa.generate_private_key(
            public_exponent=65537,
            key_size=2048,
            backend=default_backend())
        public_key_string = ssh_key.public_key().public_bytes(
            serialization.Encoding.OpenSSH,
            serialization.PublicFormat.OpenSSH)
        private_key_string = ssh_key.private_bytes(
            serialization.Encoding.PEM,
            serialization.PrivateFormat.TraditionalOpenSSL,
            serialization.NoEncryption())
        with open(public_key, 'w+b') as key_file:
            key_file.write(public_key_string)

        with open(private_key, 'w+b') as key_file:
            key_file.write(private_key_string)
    else:
        with open(public_key) as key_file:
            public_key_string = key_file.read()
        with open(private_key) as key_file:
            private_key_string = key_file.read()

    return public_key_string, private_key_string 
Example #18
Source File: test.py    From signxml with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        self.example_xml_files = (os.path.join(os.path.dirname(__file__), "example.xml"),
                                  os.path.join(os.path.dirname(__file__), "example2.xml"))
        self.keys = dict(hmac=b"secret",
                         rsa=rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=default_backend()),
                         dsa=dsa.generate_private_key(key_size=1024, backend=default_backend()),
                         ecdsa=ec.generate_private_key(curve=ec.SECP384R1(), backend=default_backend())) 
Example #19
Source File: ckeygen.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def generateECDSAkey(options):
    from cryptography.hazmat.backends import default_backend
    from cryptography.hazmat.primitives.asymmetric import ec

    if not options['bits']:
        options['bits'] = 256
    # OpenSSH supports only mandatory sections of RFC5656.
    # See https://www.openssh.com/txt/release-5.7
    curve  = b'ecdsa-sha2-nistp' + str(options['bits']).encode('ascii')
    keyPrimitive = ec.generate_private_key(
        curve=keys._curveTable[curve],
        backend=default_backend()
        )
    key = keys.Key(keyPrimitive)
    _saveKey(key, options) 
Example #20
Source File: ckeygen.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def generateDSAkey(options):
    from cryptography.hazmat.backends import default_backend
    from cryptography.hazmat.primitives.asymmetric import dsa

    if not options['bits']:
        options['bits'] = 1024
    keyPrimitive = dsa.generate_private_key(
        key_size=int(options['bits']),
        backend=default_backend(),
        )
    key = keys.Key(keyPrimitive)
    _saveKey(key, options) 
Example #21
Source File: ckeygen.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def generateRSAkey(options):
    from cryptography.hazmat.backends import default_backend
    from cryptography.hazmat.primitives.asymmetric import rsa

    if not options['bits']:
        options['bits'] = 1024
    keyPrimitive = rsa.generate_private_key(
        key_size=int(options['bits']),
        public_exponent=65537,
        backend=default_backend(),
        )
    key = keys.Key(keyPrimitive)
    _saveKey(key, options) 
Example #22
Source File: cfn_dsakey_provider.py    From cfn-secret-provider with Apache License 2.0 5 votes vote down vote up
def create_key(self):
        key = dsa.generate_private_key(
            backend=crypto_default_backend(), key_size=self.get("KeySize")
        )
        private_key = key.private_bytes(
            crypto_serialization.Encoding.PEM,
            crypto_serialization.PrivateFormat.PKCS8,
            crypto_serialization.NoEncryption(),
        )

        public_key = key.public_key().public_bytes(
            crypto_serialization.Encoding.OpenSSH,
            crypto_serialization.PublicFormat.OpenSSH,
        )
        return private_key.decode("ascii"), public_key.decode("ascii") 
Example #23
Source File: ckeygen.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def generateECDSAkey(options):
    from cryptography.hazmat.backends import default_backend
    from cryptography.hazmat.primitives.asymmetric import ec

    if not options['bits']:
        options['bits'] = 256
    # OpenSSH supports only mandatory sections of RFC5656.
    # See https://www.openssh.com/txt/release-5.7
    curve  = b'ecdsa-sha2-nistp' + str(options['bits']).encode('ascii')
    keyPrimitive = ec.generate_private_key(
        curve=keys._curveTable[curve],
        backend=default_backend()
        )
    key = keys.Key(keyPrimitive)
    _saveKey(key, options) 
Example #24
Source File: ckeygen.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def generateDSAkey(options):
    from cryptography.hazmat.backends import default_backend
    from cryptography.hazmat.primitives.asymmetric import dsa

    if not options['bits']:
        options['bits'] = 1024
    keyPrimitive = dsa.generate_private_key(
        key_size=int(options['bits']),
        backend=default_backend(),
        )
    key = keys.Key(keyPrimitive)
    _saveKey(key, options) 
Example #25
Source File: ckeygen.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def generateRSAkey(options):
    from cryptography.hazmat.backends import default_backend
    from cryptography.hazmat.primitives.asymmetric import rsa

    if not options['bits']:
        options['bits'] = 1024
    keyPrimitive = rsa.generate_private_key(
        key_size=int(options['bits']),
        public_exponent=65537,
        backend=default_backend(),
        )
    key = keys.Key(keyPrimitive)
    _saveKey(key, options) 
Example #26
Source File: template_filters.py    From appr with Apache License 2.0 5 votes vote down vote up
def gen_private_dsa():
    from cryptography.hazmat.primitives import serialization
    from cryptography.hazmat.backends import default_backend
    from cryptography.hazmat.primitives.asymmetric import dsa

    private_key = dsa.generate_private_key(key_size=1024, backend=default_backend())
    pem = private_key.private_bytes(encoding=serialization.Encoding.PEM,
                                    format=serialization.PrivateFormat.TraditionalOpenSSL,
                                    encryption_algorithm=serialization.NoEncryption())
    return pem 
Example #27
Source File: template_filters.py    From appr with Apache License 2.0 5 votes vote down vote up
def gen_private_rsa():
    from cryptography.hazmat.primitives import serialization
    from cryptography.hazmat.backends import default_backend
    from cryptography.hazmat.primitives.asymmetric import rsa

    private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048,
                                           backend=default_backend())
    pem = private_key.private_bytes(encoding=serialization.Encoding.PEM,
                                    format=serialization.PrivateFormat.TraditionalOpenSSL,
                                    encryption_algorithm=serialization.NoEncryption())
    return pem 
Example #28
Source File: test_key_pair_authentication.py    From snowflake-connector-python with Apache License 2.0 5 votes vote down vote up
def test_bad_private_key(db_parameters):
    db_config = {
        'protocol': db_parameters['protocol'],
        'account': db_parameters['account'],
        'user': db_parameters['user'],
        'host': db_parameters['host'],
        'port': db_parameters['port'],
        'database': db_parameters['database'],
        'schema': db_parameters['schema'],
        'timezone': 'UTC',
    }

    dsa_private_key = dsa.generate_private_key(key_size=2048,
                                               backend=default_backend())
    dsa_private_key_der = dsa_private_key.private_bytes(
        encoding=serialization.Encoding.DER,
        format=serialization.PrivateFormat.PKCS8,
        encryption_algorithm=serialization.NoEncryption())

    encrypted_rsa_private_key_der = rsa.generate_private_key(key_size=2048,
                                                             public_exponent=65537,
                                                             backend=default_backend()) \
        .private_bytes(encoding=serialization.Encoding.DER,
                       format=serialization.PrivateFormat.PKCS8,
                       encryption_algorithm=serialization.BestAvailableEncryption(
                           b'abcd'))

    bad_private_key_test_cases = ["abcd", 1234, b'abcd', dsa_private_key_der,
                                  encrypted_rsa_private_key_der]

    for private_key in bad_private_key_test_cases:
        db_config['private_key'] = private_key
        with pytest.raises(
                snowflake.connector.errors.ProgrammingError) as exec_info:
            snowflake.connector.connect(**db_config)
        assert (exec_info.value.errno == 251008) 
Example #29
Source File: fields.py    From PGPy with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def encrypt(cls, pk, *args):
        """
        For convenience, the synopsis of the encoding method is given below;
        however, this section, [NIST-SP800-56A], and [RFC3394] are the
        normative sources of the definition.

            Obtain the authenticated recipient public key R
            Generate an ephemeral key pair {v, V=vG}
            Compute the shared point S = vR;
            m = symm_alg_ID || session key || checksum || pkcs5_padding;
            curve_OID_len = (byte)len(curve_OID);
            Param = curve_OID_len || curve_OID || public_key_alg_ID || 03
            || 01 || KDF_hash_ID || KEK_alg_ID for AESKeyWrap || "Anonymous
            Sender    " || recipient_fingerprint;
            Z_len = the key size for the KEK_alg_ID used with AESKeyWrap
            Compute Z = KDF( S, Z_len, Param );
            Compute C = AESKeyWrap( Z, m ) as per [RFC3394]
            VB = convert point V to the octet string
            Output (MPI(VB) || len(C) || C).

        The decryption is the inverse of the method given.  Note that the
        recipient obtains the shared secret by calculating
        """
        # *args should be:
        # - m
        #
        _m, = args

        # m may need to be PKCS5-padded
        padder = PKCS7(64).padder()
        m = padder.update(_m) + padder.finalize()

        km = pk.keymaterial
        ct = cls()

        # generate ephemeral key pair and keep public key in ct
        # use private key to compute the shared point "s"
        if km.oid == EllipticCurveOID.Curve25519:
            v = x25519.X25519PrivateKey.generate()
            x = v.public_key().public_bytes(encoding=serialization.Encoding.Raw, format=serialization.PublicFormat.Raw)
            ct.p = ECPoint.from_values(km.oid.key_size, ECPointFormat.Native, x)
            s = v.exchange(km.__pubkey__())
        else:
            v = ec.generate_private_key(km.oid.curve(), default_backend())
            x = MPI(v.public_key().public_numbers().x)
            y = MPI(v.public_key().public_numbers().y)
            ct.p = ECPoint.from_values(km.oid.key_size, ECPointFormat.Standard, x, y)
            s = v.exchange(ec.ECDH(), km.__pubkey__())

        # derive the wrapping key
        z = km.kdf.derive_key(s, km.oid, PubKeyAlgorithm.ECDH, pk.fingerprint)

        # compute C
        ct.c = aes_key_wrap(z, m, default_backend())

        return ct