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

The following are 30 code examples of cryptography.hazmat.primitives.asymmetric.rsa.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.rsa , or try the search function .
Example #1
Source File: 0262e50e90e0_add_ssh_keypair_into_keypair.py    From backend.ai-manager with GNU Lesser General Public License v3.0 8 votes vote down vote up
def generate_ssh_keypair():
    key = rsa.generate_private_key(
        backend=crypto_default_backend(),
        public_exponent=65537,
        key_size=2048
    )
    private_key = key.private_bytes(
        crypto_serialization.Encoding.PEM,
        crypto_serialization.PrivateFormat.TraditionalOpenSSL,
        crypto_serialization.NoEncryption()
    ).decode("utf-8")
    public_key = key.public_key().public_bytes(
        crypto_serialization.Encoding.OpenSSH,
        crypto_serialization.PublicFormat.OpenSSH
    ).decode("utf-8")
    return (public_key, private_key) 
Example #2
Source File: keypair.py    From backend.ai-manager with GNU Lesser General Public License v3.0 7 votes vote down vote up
def generate_ssh_keypair() -> Tuple[str, str]:
    '''
    Generate RSA keypair for SSH/SFTP connection.
    '''
    key = rsa.generate_private_key(
        backend=crypto_default_backend(),
        public_exponent=65537,
        key_size=2048
    )
    private_key = key.private_bytes(
        crypto_serialization.Encoding.PEM,
        crypto_serialization.PrivateFormat.TraditionalOpenSSL,
        crypto_serialization.NoEncryption()
    ).decode("utf-8")
    public_key = key.public_key().public_bytes(
        crypto_serialization.Encoding.OpenSSH,
        crypto_serialization.PublicFormat.OpenSSH
    ).decode("utf-8")
    return (public_key, private_key) 
Example #3
Source File: basic_file_encryption_with_multiple_providers.py    From aws-encryption-sdk-python with Apache License 2.0 6 votes vote down vote up
def _get_raw_key(self, key_id):
        """Retrieves a static, randomly generated, RSA key for the specified key id.

        :param str key_id: User-defined ID for the static key
        :returns: Wrapping key that contains the specified static key
        :rtype: :class:`aws_encryption_sdk.internal.crypto.WrappingKey`
        """
        try:
            static_key = self._static_keys[key_id]
        except KeyError:
            private_key = rsa.generate_private_key(public_exponent=65537, key_size=4096, backend=default_backend())
            static_key = private_key.private_bytes(
                encoding=serialization.Encoding.PEM,
                format=serialization.PrivateFormat.PKCS8,
                encryption_algorithm=serialization.NoEncryption(),
            )
            self._static_keys[key_id] = static_key
        return WrappingKey(
            wrapping_algorithm=WrappingAlgorithm.RSA_OAEP_SHA1_MGF1,
            wrapping_key=static_key,
            wrapping_key_type=EncryptionKeyType.PRIVATE,
        ) 
Example #4
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 #5
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 #6
Source File: CloudConnector.py    From im with GNU General Public License v3.0 6 votes vote down vote up
def keygen():
        """
        Generates a keypair using the cryptography lib and returns a tuple (public, private)
        """
        key = rsa.generate_private_key(public_exponent=65537, key_size=2048,
                                       backend=default_backend())

        private = key.private_bytes(encoding=serialization.Encoding.PEM,
                                    format=serialization.PrivateFormat.TraditionalOpenSSL,
                                    encryption_algorithm=serialization.NoEncryption()
                                    ).decode()

        public = key.public_key().public_bytes(encoding=serialization.Encoding.OpenSSH,
                                               format=serialization.PublicFormat.OpenSSH
                                               ).decode()

        return (public, private) 
Example #7
Source File: _certificate_generator.py    From webviz-config with MIT License 6 votes vote down vote up
def create_key(key_path: str) -> rsa.RSAPrivateKey:

    key = rsa.generate_private_key(
        public_exponent=65537, key_size=2048, backend=default_backend()
    )

    with open(key_path, "wb") as filehandle:
        filehandle.write(
            key.private_bytes(
                encoding=serialization.Encoding.PEM,
                format=serialization.PrivateFormat.TraditionalOpenSSL,
                encryption_algorithm=serialization.NoEncryption(),
            )
        )

    return key 
Example #8
Source File: test_utils.py    From django-graphql-jwt with MIT License 6 votes vote down vote up
def test_rsa_jwt(self):
        private_key = rsa.generate_private_key(
            public_exponent=65537,
            key_size=2048,
            backend=default_backend(),
        )
        public_key = private_key.public_key()
        payload = utils.jwt_payload(self.user)

        with override_jwt_settings(
                JWT_PUBLIC_KEY=public_key,
                JWT_PRIVATE_KEY=private_key,
                JWT_ALGORITHM='RS256'):

            token = utils.jwt_encode(payload)
            decoded = utils.jwt_decode(token)

        self.assertEqual(payload, decoded) 
Example #9
Source File: crypto.py    From privacyidea with GNU Affero General Public License v3.0 6 votes vote down vote up
def generate_keypair(rsa_keysize=2048):
    """
    This creates an RSA key pair

    # TODO: The HSM should be used.

    The public key and private keys are returned in PKCS#1 Format.

    :return: tuple of (pubkey, privkey)
    """
    private_key = rsa.generate_private_key(
        public_exponent=65537,
        key_size=rsa_keysize,
        backend=default_backend()
        )
    public_key = private_key.public_key()
    pem_priv = to_unicode(private_key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.TraditionalOpenSSL,
        encryption_algorithm=serialization.NoEncryption()))
    pem_pub = to_unicode(public_key.public_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PublicFormat.PKCS1))
    return pem_pub, pem_priv 
Example #10
Source File: helpers.py    From cloudbridge with MIT License 6 votes vote down vote up
def generate_key_pair():
    """
    This method generates a keypair and returns it as a tuple
    of (public, private) keys.
    The public key format is OpenSSH and private key format is PEM.
    """
    key_pair = rsa.generate_private_key(
        backend=default_backend(),
        public_exponent=65537,
        key_size=2048)
    private_key = key_pair.private_bytes(
        crypt_serialization.Encoding.PEM,
        crypt_serialization.PrivateFormat.PKCS8,
        crypt_serialization.NoEncryption()).decode('utf-8')
    public_key = key_pair.public_key().public_bytes(
        crypt_serialization.Encoding.OpenSSH,
        crypt_serialization.PublicFormat.OpenSSH).decode('utf-8')
    return public_key, private_key 
Example #11
Source File: util.py    From Spectrum-Access-System with Apache License 2.0 6 votes vote down vote up
def generateCpiRsaKeys():
  """Generate a private/public RSA 2048 key pair.

  Returns:
    A tuple (private_key, public key) as PEM string encoded.
  """
  rsa_key = rsa.generate_private_key(
      public_exponent=65537, key_size=2048, backend=default_backend())
  rsa_private_key = rsa_key.private_bytes(
      encoding=serialization.Encoding.PEM,
      format=serialization.PrivateFormat.TraditionalOpenSSL,
      encryption_algorithm=serialization.NoEncryption())
  rsa_public_key = rsa_key.public_key().public_bytes(
      encoding=serialization.Encoding.PEM,
      format=serialization.PublicFormat.SubjectPublicKeyInfo)
  return rsa_private_key, rsa_public_key 
Example #12
Source File: test_cfn_keypair_provider.py    From cfn-secret-provider with Apache License 2.0 6 votes vote down vote up
def __init__(self):
        from cryptography.hazmat.primitives import serialization as crypto_serialization
        from cryptography.hazmat.primitives.asymmetric import rsa
        from cryptography.hazmat.backends import (
            default_backend as crypto_default_backend,
        )

        self.key = rsa.generate_private_key(
            backend=crypto_default_backend(), public_exponent=65537, key_size=2048
        )
        self.private_key = self.key.private_bytes(
            crypto_serialization.Encoding.PEM,
            crypto_serialization.PrivateFormat.PKCS8,
            crypto_serialization.NoEncryption(),
        ).decode("ascii")

        self.public_key = (
            self.key.public_key()
            .public_bytes(
                crypto_serialization.Encoding.OpenSSH,
                crypto_serialization.PublicFormat.OpenSSH,
            )
            .decode("ascii")
        ) 
Example #13
Source File: cfn_rsakey_provider.py    From cfn-secret-provider with Apache License 2.0 6 votes vote down vote up
def create_key(self):
        key = rsa.generate_private_key(
            backend=crypto_default_backend(),
            public_exponent=65537,
            key_size=self.get("KeySize"),
        )
        private_key = key.private_bytes(
            crypto_serialization.Encoding.PEM,
            self.key_format,
            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 #14
Source File: espsecure.py    From esptool with GNU General Public License v2.0 6 votes vote down vote up
def generate_signing_key(args):
    if os.path.exists(args.keyfile):
        raise esptool.FatalError("ERROR: Key file %s already exists" % args.keyfile)
    if args.version == "1":
        """ Generate an ECDSA signing key for signing secure boot images (post-bootloader) """
        sk = ecdsa.SigningKey.generate(curve=ecdsa.NIST256p)
        with open(args.keyfile, "wb") as f:
            f.write(sk.to_pem())
        print("ECDSA NIST256p private key in PEM format written to %s" % args.keyfile)
    elif args.version == "2":
        """ Generate a RSA 3072 signing key for signing secure boot images """
        private_key = rsa.generate_private_key(
            public_exponent=65537,
            key_size=3072,
            backend=default_backend()
        ).private_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PrivateFormat.TraditionalOpenSSL,
            encryption_algorithm=serialization.NoEncryption()
        ).decode()
        with open(args.keyfile, "wb") as f:
            f.write(private_key)
        print("RSA 3072 private key in PEM format written to %s" % args.keyfile) 
Example #15
Source File: simp_le.py    From simp_le with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(PluginIOTestMixin, self).__init__(*args, **kwargs)

        raw_key = gen_pkey(1024)
        self.all_data = IOPlugin.Data(
            account_key=jose.JWKRSA(key=rsa.generate_private_key(
                public_exponent=65537, key_size=1024,
                backend=default_backend(),
            )),
            key=ComparablePKey(raw_key),
            cert=jose.ComparableX509(crypto_util.gen_ss_cert(raw_key, ['a'])),
            chain=[
                jose.ComparableX509(crypto_util.gen_ss_cert(raw_key, ['b'])),
                jose.ComparableX509(crypto_util.gen_ss_cert(raw_key, ['c'])),
            ],
        )
        self.key_data = IOPlugin.EMPTY_DATA._replace(key=self.all_data.key) 
Example #16
Source File: cert.py    From scapy with GNU General Public License v2.0 6 votes vote down vote up
def fill_and_store(self, modulus=None, modulusLen=None, pubExp=None):
        pubExp = pubExp or 65537
        if not modulus:
            real_modulusLen = modulusLen or 2048
            private_key = rsa.generate_private_key(public_exponent=pubExp,
                                                   key_size=real_modulusLen,
                                                   backend=default_backend())
            self.pubkey = private_key.public_key()
        else:
            real_modulusLen = len(binrepr(modulus))
            if modulusLen and real_modulusLen != modulusLen:
                warning("modulus and modulusLen do not match!")
            pubNum = rsa.RSAPublicNumbers(n=modulus, e=pubExp)
            self.pubkey = pubNum.public_key(default_backend())
        # Lines below are only useful for the legacy part of pkcs1.py
        pubNum = self.pubkey.public_numbers()
        self._modulusLen = real_modulusLen
        self._modulus = pubNum.n
        self._pubExp = pubNum.e 
Example #17
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 #18
Source File: util.py    From Spectrum-Access-System with Apache License 2.0 5 votes vote down vote up
def generateCpiEcKeys():
  """Generate a private/public EC SECP256R1 key pair.

    Returns:
      A tuple (private_key, public key) as PEM string encoded.
    """
  ec_key = ec.generate_private_key(ec.SECP256R1(), default_backend())
  ec_private_key = ec_key.private_bytes(
      encoding=serialization.Encoding.PEM,
      format=serialization.PrivateFormat.TraditionalOpenSSL,
      encryption_algorithm=serialization.NoEncryption())
  ec_public_key = ec_key.public_key().public_bytes(
      encoding=serialization.Encoding.PEM,
      format=serialization.PublicFormat.SubjectPublicKeyInfo)
  return ec_private_key, ec_public_key 
Example #19
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 #20
Source File: test.py    From requests-http-signature with Apache License 2.0 5 votes vote down vote up
def test_rsa(self):
        from cryptography.hazmat.backends import default_backend
        from cryptography.hazmat.primitives.asymmetric import rsa
        from cryptography.hazmat.primitives import serialization
        private_key = rsa.generate_private_key(
            public_exponent=65537,
            key_size=2048,
            backend=default_backend()
        )
        private_key_pem = private_key.private_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PrivateFormat.PKCS8,
            encryption_algorithm=serialization.BestAvailableEncryption(passphrase)
        )
        public_key_pem = private_key.public_key().public_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PublicFormat.SubjectPublicKeyInfo
        )
        url = 'http://example.com/path?query#fragment'
        auth = HTTPSignatureAuth(algorithm="rsa-sha256", key=private_key_pem, key_id="sekret", passphrase=passphrase)
        self.session.get(url, auth=auth, headers=dict(pubkey=base64.b64encode(public_key_pem))) 
Example #21
Source File: create_x509_chain_crypto.py    From azure-iot-sdk-python with MIT License 5 votes vote down vote up
def create_private_key(key_file, password=None, key_size=4096):
    """
    Crate encrypted key for certificates.
    :param key_file: The file to store the key.
    :param password: Password for the key.
    :param key_size: The key size to use for encryption. The default is 4096.
    :return: The private key.
    """
    if password:
        encrypt_algo = serialization.BestAvailableEncryption(str.encode(password))
    else:
        encrypt_algo = serialization.NoEncryption()

    private_key = rsa.generate_private_key(
        public_exponent=PUBLIC_EXPONENT, key_size=key_size, backend=default_backend()
    )
    # Write our key to file
    with open(key_file, "wb") as f:
        f.write(
            private_key.private_bytes(
                encoding=serialization.Encoding.PEM,
                format=serialization.PrivateFormat.TraditionalOpenSSL,
                encryption_algorithm=encrypt_algo,
            )
        )

    return private_key 
Example #22
Source File: utils.py    From asap-authentication-python with MIT License 5 votes vote down vote up
def get_new_private_key_in_pem_format(self):
        private_key = ec.generate_private_key(
            ec.SECP256R1(), default_backend())
        return private_key.private_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PrivateFormat.TraditionalOpenSSL,
            encryption_algorithm=serialization.NoEncryption()
        ) 
Example #23
Source File: utils.py    From asap-authentication-python with MIT License 5 votes vote down vote up
def get_new_rsa_private_key_in_pem_format():
    """ returns a new rsa key in pem format. """
    private_key = rsa.generate_private_key(
        key_size=2048, backend=default_backend(), public_exponent=65537)
    return private_key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.TraditionalOpenSSL,
        encryption_algorithm=serialization.NoEncryption()
    ) 
Example #24
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 #25
Source File: cert.py    From scapy with GNU General Public License v2.0 5 votes vote down vote up
def fill_and_store(self, curve=None):
        curve = curve or ec.SECP256R1
        self.key = ec.generate_private_key(curve(), default_backend())
        self.pubkey = self.key.public_key() 
Example #26
Source File: dep.py    From zentral with Apache License 2.0 5 votes vote down vote up
def build_dep_token_certificate(dep_token):
    private_key = rsa.generate_private_key(
        public_exponent=65537,
        key_size=2048,
        backend=default_backend()
    )
    public_key = private_key.public_key()
    builder = x509.CertificateBuilder()
    builder = builder.subject_name(x509.Name([
        x509.NameAttribute(NameOID.COMMON_NAME, u'zentral-dep-token-{}'.format(dep_token.pk)),
    ]))
    builder = builder.issuer_name(x509.Name([
        x509.NameAttribute(NameOID.COMMON_NAME, u'zentral'),
    ]))
    now = timezone.now()
    one_day = datetime.timedelta(days=1)
    builder = builder.not_valid_before(now - one_day)
    builder = builder.not_valid_after(now + 2 * one_day)
    builder = builder.serial_number(x509.random_serial_number())
    builder = builder.public_key(public_key)
    builder = builder.add_extension(
        x509.BasicConstraints(ca=False, path_length=None), critical=True,
    )
    certificate = builder.sign(
        private_key=private_key, algorithm=hashes.SHA256(),
        backend=default_backend()
    )
    return certificate, private_key 
Example #27
Source File: cert.py    From scapy with GNU General Public License v2.0 5 votes vote down vote up
def fill_and_store(self, modulus=None, modulusLen=None, pubExp=None,
                       prime1=None, prime2=None, coefficient=None,
                       exponent1=None, exponent2=None, privExp=None):
        pubExp = pubExp or 65537
        if None in [modulus, prime1, prime2, coefficient, privExp,
                    exponent1, exponent2]:
            # note that the library requires every parameter
            # in order to call RSAPrivateNumbers(...)
            # if one of these is missing, we generate a whole new key
            real_modulusLen = modulusLen or 2048
            self.key = rsa.generate_private_key(public_exponent=pubExp,
                                                key_size=real_modulusLen,
                                                backend=default_backend())
            self.pubkey = self.key.public_key()
        else:
            real_modulusLen = len(binrepr(modulus))
            if modulusLen and real_modulusLen != modulusLen:
                warning("modulus and modulusLen do not match!")
            pubNum = rsa.RSAPublicNumbers(n=modulus, e=pubExp)
            privNum = rsa.RSAPrivateNumbers(p=prime1, q=prime2,
                                            dmp1=exponent1, dmq1=exponent2,
                                            iqmp=coefficient, d=privExp,
                                            public_numbers=pubNum)
            self.key = privNum.private_key(default_backend())
            self.pubkey = self.key.public_key()

        # Lines below are only useful for the legacy part of pkcs1.py
        pubNum = self.pubkey.public_numbers()
        self._modulusLen = real_modulusLen
        self._modulus = pubNum.n
        self._pubExp = pubNum.e 
Example #28
Source File: cert.py    From scapy with GNU General Public License v2.0 5 votes vote down vote up
def fill_and_store(self, curve=None):
        curve = curve or ec.SECP256R1
        private_key = ec.generate_private_key(curve(), default_backend())
        self.pubkey = private_key.public_key() 
Example #29
Source File: sshkeys.py    From ToonRooter with MIT License 5 votes vote down vote up
def generate_key_pair(password=None):
    from cryptography.hazmat.backends import default_backend
    from cryptography.hazmat.primitives.asymmetric import rsa

    from cryptography.hazmat.primitives import serialization

    private_key = rsa.generate_private_key(
        public_exponent=65537,
        key_size=2048,
        backend=default_backend()
    )

    key_encryption_algorithm = serialization.NoEncryption()
    if password:
        key_encryption_algorithm = serialization.BestAvailableEncryption(password)

    private_pem = private_key.private_bytes(
       encoding=serialization.Encoding.PEM,
       format=serialization.PrivateFormat.PKCS8,
       encryption_algorithm=key_encryption_algorithm
    )


    public_key = private_key.public_key()

    public_openssh = public_key.public_bytes(
       encoding=serialization.Encoding.OpenSSH,
       format=serialization.PublicFormat.OpenSSH
    )

    return (public_openssh, private_pem) 
Example #30
Source File: operations.py    From magnum with Apache License 2.0 5 votes vote down vote up
def generate_csr_and_key(common_name):
    """Return a dict with a new csr, public key and private key."""
    private_key = rsa.generate_private_key(
        public_exponent=65537,
        key_size=2048,
        backend=default_backend())

    public_key = private_key.public_key()

    csr = x509.CertificateSigningRequestBuilder().subject_name(x509.Name([
        x509.NameAttribute(x509.oid.NameOID.COMMON_NAME, common_name),
    ])).sign(private_key, hashes.SHA256(), default_backend())

    result = {
        'csr': csr.public_bytes(
            encoding=serialization.Encoding.PEM).decode("utf-8"),
        'private_key': private_key.private_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PrivateFormat.TraditionalOpenSSL,
            encryption_algorithm=serialization.NoEncryption()).decode("utf-8"),
        'public_key': public_key.public_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PublicFormat.SubjectPublicKeyInfo).decode(
                "utf-8"),
    }

    return result