Python cryptography.hazmat.primitives.serialization.NoEncryption() Examples

The following are 30 code examples of cryptography.hazmat.primitives.serialization.NoEncryption(). 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.serialization , 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: _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 #4
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 #5
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 #6
Source File: key.py    From asap-authentication-python with MIT License 6 votes vote down vote up
def load(self, issuer):
        if not self._data_uri.startswith('data:application/pkcs8;kid='):
            raise PrivateKeyRetrieverException('Unrecognised data uri format.')
        splitted = self._data_uri.split(';')
        key_identifier = KeyIdentifier(unquote_plus(
            splitted[1][len('kid='):]))
        key_data = base64.b64decode(splitted[-1].split(',')[-1])
        key = serialization.load_der_private_key(
            key_data,
            password=None,
            backend=cryptography.hazmat.backends.default_backend())
        private_key_pem = key.private_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PrivateFormat.TraditionalOpenSSL,
            encryption_algorithm=serialization.NoEncryption()
        )
        return key_identifier, private_key_pem.decode('utf-8') 
Example #7
Source File: cfn_rsakey_provider.py    From cfn-secret-provider with Apache License 2.0 6 votes vote down vote up
def get_key(self):
        response = self.ssm.get_parameter(
            Name=self.name_from_physical_resource_id(), WithDecryption=True
        )
        private_key = response["Parameter"]["Value"].encode("ascii")

        key = crypto_serialization.load_pem_private_key(
            private_key, password=None, backend=crypto_default_backend()
        )

        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 #8
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 #9
Source File: certs.py    From dcos-deploy with Apache License 2.0 6 votes vote down vote up
def _convert_key(encoding_name, format_name, private_key):
    if not encoding_name and not format_name:
        return private_key
    backend = backends.default_backend()
    key_obj = serialization.load_pem_private_key(private_key.encode("utf-8"), None, backend)
    if encoding_name.lower() == "pem":
        encoding = serialization.Encoding.PEM
    elif encoding_name.lower() == "der":
        encoding = serialization.Encoding.DER
    else:
        raise Exception("Unknown key encoding: %s" % encoding_name)
    if format_name.lower() == "pkcs1":
        format = serialization.PrivateFormat.TraditionalOpenSSL
    elif format_name.lower() == "pkcs8":
        format = serialization.PrivateFormat.PKCS8
    else:
        raise Exception("Unknown key format: %s" % format_name)

    target_key = key_obj.private_bytes(encoding=encoding, format=format, encryption_algorithm=serialization.NoEncryption())
    return target_key.decode("utf-8") 
Example #10
Source File: test_client.py    From txacme with MIT License 6 votes vote down vote up
def _test_issue(self, name):
        def got_cert(certr):
            key_bytes = self.issued_key.private_bytes(
                encoding=serialization.Encoding.PEM,
                format=serialization.PrivateFormat.TraditionalOpenSSL,
                encryption_algorithm=serialization.NoEncryption())
            FilePath('issued.crt').setContent(certr.body)
            FilePath('issued.key').setContent(key_bytes)
            return certr

        action = start_action(action_type=u'integration:issue')
        with action.context():
            self.issued_key = generate_private_key('rsa')
            csr = csr_for_names([name], self.issued_key)
            return (
                DeferredContext(
                    self.client.request_issuance(CertificateRequest(csr=csr)))
                .addCallback(got_cert)
                .addActionFinish()) 
Example #11
Source File: endpoint.py    From txacme with MIT License 6 votes vote down vote up
def load_or_create_client_key(pem_path):
    """
    Load the client key from a directory, creating it if it does not exist.

    .. note:: The client key that will be created will be a 2048-bit RSA key.

    :type pem_path: ``twisted.python.filepath.FilePath``
    :param pem_path: The certificate directory
        to use, as with the endpoint.
    """
    acme_key_file = pem_path.asTextMode().child(u'client.key')
    if acme_key_file.exists():
        key = serialization.load_pem_private_key(
            acme_key_file.getContent(),
            password=None,
            backend=default_backend())
    else:
        key = generate_private_key(u'rsa')
        acme_key_file.setContent(
            key.private_bytes(
                encoding=serialization.Encoding.PEM,
                format=serialization.PrivateFormat.TraditionalOpenSSL,
                encryption_algorithm=serialization.NoEncryption()))
    return JWKRSA(key=key) 
Example #12
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 #13
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 #14
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 #15
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 #16
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 #17
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 #18
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 #19
Source File: Snowflake.py    From content with MIT License 5 votes vote down vote up
def get_connection_params(args):
    """
    Construct and return the connection parameters

    parameter: (dict) args
        The command arguments of the command function calling this helper function

    returns:
        Snowflake connection params
    """
    params: dict = {}
    set_provided(params, 'user', USER)
    set_provided(params, 'password', PASSWORD)
    set_provided(params, 'account', ACCOUNT)
    set_provided(params, 'authenticator', AUTHENTICATOR)
    set_provided(params, 'region', REGION)
    set_provided(params, 'insecure_mode', INSECURE)
    set_provided(params, 'warehouse', args.get('warehouse'), WAREHOUSE)
    set_provided(params, 'database', args.get('database'), DATABASE)
    set_provided(params, 'schema', args.get('schema'), SCHEMA)
    set_provided(params, 'role', args.get('role'), ROLE)
    if CERTIFICATE:
        p_key = serialization.load_pem_private_key(CERTIFICATE, password=CERT_PASSWORD, backend=default_backend())
        pkb = p_key.private_bytes(
            encoding=serialization.Encoding.DER,
            format=serialization.PrivateFormat.PKCS8,
            encryption_algorithm=serialization.NoEncryption()
        )
        params['private_key'] = pkb
    return params 
Example #20
Source File: ed448.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def private_bytes(self, encoding, format, encryption_algorithm):
        if (
            encoding is serialization.Encoding.Raw or
            format is serialization.PublicFormat.Raw
        ):
            if (
                format is not serialization.PrivateFormat.Raw or
                encoding is not serialization.Encoding.Raw or not
                isinstance(encryption_algorithm, serialization.NoEncryption)
            ):
                raise ValueError(
                    "When using Raw both encoding and format must be Raw "
                    "and encryption_algorithm must be NoEncryption()"
                )

            return self._raw_private_bytes()

        if (
            encoding in serialization._PEM_DER and
            format is not serialization.PrivateFormat.PKCS8
        ):
            raise ValueError(
                "format must be PKCS8 when encoding is PEM or DER"
            )

        return self._backend._private_key_bytes(
            encoding, format, encryption_algorithm, self._evp_pkey, None
        ) 
Example #21
Source File: x448.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def private_bytes(self, encoding, format, encryption_algorithm):
        if (
            encoding is serialization.Encoding.Raw or
            format is serialization.PublicFormat.Raw
        ):
            if (
                format is not serialization.PrivateFormat.Raw or
                encoding is not serialization.Encoding.Raw or not
                isinstance(encryption_algorithm, serialization.NoEncryption)
            ):
                raise ValueError(
                    "When using Raw both encoding and format must be Raw "
                    "and encryption_algorithm must be NoEncryption()"
                )

            return self._raw_private_bytes()

        if (
            encoding in serialization._PEM_DER and
            format is not serialization.PrivateFormat.PKCS8
        ):
            raise ValueError(
                "format must be PKCS8 when encoding is PEM or DER"
            )

        return self._backend._private_key_bytes(
            encoding, format, encryption_algorithm, self._evp_pkey, None
        ) 
Example #22
Source File: ed25519.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def private_bytes(self, encoding, format, encryption_algorithm):
        if (
            encoding is serialization.Encoding.Raw or
            format is serialization.PublicFormat.Raw
        ):
            if (
                format is not serialization.PrivateFormat.Raw or
                encoding is not serialization.Encoding.Raw or not
                isinstance(encryption_algorithm, serialization.NoEncryption)
            ):
                raise ValueError(
                    "When using Raw both encoding and format must be Raw "
                    "and encryption_algorithm must be NoEncryption()"
                )

            return self._raw_private_bytes()

        if (
            encoding in serialization._PEM_DER and
            format is not serialization.PrivateFormat.PKCS8
        ):
            raise ValueError(
                "format must be PKCS8 when encoding is PEM or DER"
            )

        return self._backend._private_key_bytes(
            encoding, format, encryption_algorithm, self._evp_pkey, None
        ) 
Example #23
Source File: ed448.py    From teleport with Apache License 2.0 5 votes vote down vote up
def private_bytes(self, encoding, format, encryption_algorithm):
        if (
            encoding is serialization.Encoding.Raw or
            format is serialization.PublicFormat.Raw
        ):
            if (
                format is not serialization.PrivateFormat.Raw or
                encoding is not serialization.Encoding.Raw or not
                isinstance(encryption_algorithm, serialization.NoEncryption)
            ):
                raise ValueError(
                    "When using Raw both encoding and format must be Raw "
                    "and encryption_algorithm must be NoEncryption()"
                )

            return self._raw_private_bytes()

        if (
            encoding in serialization._PEM_DER and
            format is not serialization.PrivateFormat.PKCS8
        ):
            raise ValueError(
                "format must be PKCS8 when encoding is PEM or DER"
            )

        return self._backend._private_key_bytes(
            encoding, format, encryption_algorithm, self._evp_pkey, None
        ) 
Example #24
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 #25
Source File: simp_le.py    From simp_le with GNU General Public License v3.0 5 votes vote down vote up
def dump_pem_jwk(data):
    """Dump JWK as PEM."""
    return data.key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.TraditionalOpenSSL,
        encryption_algorithm=serialization.NoEncryption(),
    ).strip() 
Example #26
Source File: m2crypto.py    From py-ipv8 with GNU Lesser General Public License v3.0 5 votes vote down vote up
def key_to_pem(self):
        "Convert a key to the PEM format."

        return self.ec.private_bytes(serialization.Encoding.PEM,
                                     serialization.PrivateFormat.TraditionalOpenSSL,
                                     serialization.NoEncryption()) 
Example #27
Source File: cert_manager.py    From SROS-grpc-services with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def generate_csr(self):
        if not self.private_key:
            key = rsa.generate_private_key(
                public_exponent=65537,
                key_size=self.key_size,
                backend=default_backend(),
            )
        else:
            key = self.private_key

        csr_builder = x509.CertificateSigningRequestBuilder(
            subject_name=self.subject_name
        )

        if self.ip_addr_list:
            csr_builder = csr_builder.add_extension(
                self.subject_alt_name, critical=True
            )

        csr = csr_builder.sign(key, hashes.SHA256(), default_backend())
        self.pem_csr = csr.public_bytes(serialization.Encoding.PEM)

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

        return csr 
Example #28
Source File: x25519.py    From teleport with Apache License 2.0 5 votes vote down vote up
def private_bytes(self, encoding, format, encryption_algorithm):
        if (
            encoding is serialization.Encoding.Raw or
            format is serialization.PublicFormat.Raw
        ):
            if (
                format is not serialization.PrivateFormat.Raw or
                encoding is not serialization.Encoding.Raw or not
                isinstance(encryption_algorithm, serialization.NoEncryption)
            ):
                raise ValueError(
                    "When using Raw both encoding and format must be Raw "
                    "and encryption_algorithm must be NoEncryption()"
                )

            return self._raw_private_bytes()

        if (
            encoding in serialization._PEM_DER and
            format is not serialization.PrivateFormat.PKCS8
        ):
            raise ValueError(
                "format must be PKCS8 when encoding is PEM or DER"
            )

        return self._backend._private_key_bytes(
            encoding, format, encryption_algorithm, self._evp_pkey, None
        ) 
Example #29
Source File: ed25519.py    From teleport with Apache License 2.0 5 votes vote down vote up
def private_bytes(self, encoding, format, encryption_algorithm):
        if (
            encoding is serialization.Encoding.Raw or
            format is serialization.PublicFormat.Raw
        ):
            if (
                format is not serialization.PrivateFormat.Raw or
                encoding is not serialization.Encoding.Raw or not
                isinstance(encryption_algorithm, serialization.NoEncryption)
            ):
                raise ValueError(
                    "When using Raw both encoding and format must be Raw "
                    "and encryption_algorithm must be NoEncryption()"
                )

            return self._raw_private_bytes()

        if (
            encoding in serialization._PEM_DER and
            format is not serialization.PrivateFormat.PKCS8
        ):
            raise ValueError(
                "format must be PKCS8 when encoding is PEM or DER"
            )

        return self._backend._private_key_bytes(
            encoding, format, encryption_algorithm, self._evp_pkey, None
        ) 
Example #30
Source File: ed25519.py    From teleport with Apache License 2.0 5 votes vote down vote up
def private_bytes(self, encoding, format, encryption_algorithm):
        if (
            encoding is serialization.Encoding.Raw or
            format is serialization.PublicFormat.Raw
        ):
            if (
                format is not serialization.PrivateFormat.Raw or
                encoding is not serialization.Encoding.Raw or not
                isinstance(encryption_algorithm, serialization.NoEncryption)
            ):
                raise ValueError(
                    "When using Raw both encoding and format must be Raw "
                    "and encryption_algorithm must be NoEncryption()"
                )

            return self._raw_private_bytes()

        if (
            encoding in serialization._PEM_DER and
            format is not serialization.PrivateFormat.PKCS8
        ):
            raise ValueError(
                "format must be PKCS8 when encoding is PEM or DER"
            )

        return self._backend._private_key_bytes(
            encoding, format, encryption_algorithm, self._evp_pkey, None
        )