<commit_before># Copyright 2014 delroth, All rights reserved,
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Handles all the CA related operations of sslenroll."""

import datetime
import functools
import os.path
import random
import socket

from OpenSSL import crypto

from sslenroll.config import cfg


def netscape_spki_from_b64(b64):
    """Converts a base64 encoded Netscape SPKI DER to a crypto.NetscapeSPKI.

    PyOpenSSL does not yet support doing that by itself, so some work around
    through FFI and "internals-patching" trickery is required to perform this
    conversion. https://github.com/pyca/pyopenssl/issues/177 tracks the issue
    upstream.
    """
    if not hasattr(netscape_spki_from_b64, 'NETSCAPE_SPKI_b64_decode'):
        from cffi import FFI as CFFI
        from OpenSSL._util import ffi as _sslffi, lib as _ssllib
        cffi = CFFI()
        cffi.cdef('void* NETSCAPE_SPKI_b64_decode(const char *str, int len);')
        lib = cffi.dlopen('libssl.so')
        def wrapper(b64, lib=lib):
            if isinstance(b64, str):
                b64 = b64.encode('ascii')
            b64_ptr = _sslffi.new('char[]', b64)
            spki_obj = lib.NETSCAPE_SPKI_b64_decode(b64_ptr, len(b64))
            if spki_obj == cffi.NULL:
                raise ValueError("Invalid SPKI base64")
            def free(spki_obj, ref=b64_ptr):
                _ssllib.NETSCAPE_SPKI_free(spki_obj)
            return _sslffi.gc(spki_obj, free)
        netscape_spki_from_b64.func = wrapper

    ret = crypto.NetscapeSPKI()
    ret._spki = netscape_spki_from_b64.func(b64)
    return ret


def _try_load_ca_private_key(path):
    """Checks that the provided private key is usable and returns it."""
    pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, open(path, 'rb').read())
    if pkey.bits() < 2048:
        raise ValueError("I'm sorry Dave, I can't let you use a small "
                         "RSA key.")
    pkey.check()
    return pkey


def _generate_ca_private_key(path):
    """Generates a new private key and saves it to the given path."""
    DEFAULT_KEY_ALG = crypto.TYPE_RSA
    DEFAULT_KEY_BITS = 2048

    pkey = crypto.PKey()
    pkey.generate_key(DEFAULT_KEY_ALG, DEFAULT_KEY_BITS)
    data = crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey)
    open(path, 'wb').write(data)

<commit_msg>ca: pkey generation should return the pkey object<commit_after># Copyright 2014 delroth, All rights reserved,
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Handles all the CA related operations of sslenroll."""

import datetime
import functools
import os.path
import random
import socket

from OpenSSL import crypto

from sslenroll.config import cfg


def netscape_spki_from_b64(b64):
    """Converts a base64 encoded Netscape SPKI DER to a crypto.NetscapeSPKI.

    PyOpenSSL does not yet support doing that by itself, so some work around
    through FFI and "internals-patching" trickery is required to perform this
    conversion. https://github.com/pyca/pyopenssl/issues/177 tracks the issue
    upstream.
    """
    if not hasattr(netscape_spki_from_b64, 'NETSCAPE_SPKI_b64_decode'):
        from cffi import FFI as CFFI
        from OpenSSL._util import ffi as _sslffi, lib as _ssllib
        cffi = CFFI()
        cffi.cdef('void* NETSCAPE_SPKI_b64_decode(const char *str, int len);')
        lib = cffi.dlopen('libssl.so')
        def wrapper(b64, lib=lib):
            if isinstance(b64, str):
                b64 = b64.encode('ascii')
            b64_ptr = _sslffi.new('char[]', b64)
            spki_obj = lib.NETSCAPE_SPKI_b64_decode(b64_ptr, len(b64))
            if spki_obj == cffi.NULL:
                raise ValueError("Invalid SPKI base64")
            def free(spki_obj, ref=b64_ptr):
                _ssllib.NETSCAPE_SPKI_free(spki_obj)
            return _sslffi.gc(spki_obj, free)
        netscape_spki_from_b64.func = wrapper

    ret = crypto.NetscapeSPKI()
    ret._spki = netscape_spki_from_b64.func(b64)
    return ret


def _try_load_ca_private_key(path):
    """Checks that the provided private key is usable and returns it."""
    pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, open(path, 'rb').read())
    if pkey.bits() < 2048:
        raise ValueError("I'm sorry Dave, I can't let you use a small "
                         "RSA key.")
    pkey.check()
    return pkey


def _generate_ca_private_key(path):
    """Generates a new private key and saves it to the given path."""
    DEFAULT_KEY_ALG = crypto.TYPE_RSA
    DEFAULT_KEY_BITS = 2048

    pkey = crypto.PKey()
    pkey.generate_key(DEFAULT_KEY_ALG, DEFAULT_KEY_BITS)
    data = crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey)
    open(path, 'wb').write(data)

    return pkey


{'fraction_non_alphanumeric': 0.0856842474154547, 'fraction_numerical': 0.020676362362011563, 'mean_word_length': 3.157319737800437, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 3, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5168058', 'n_tokens_mistral': 1917, 'n_tokens_neox': 1798, 'n_words': 569}