Automatically create RSA keys if they are missing

This commit is contained in:
Kishi85 2019-01-08 08:14:42 +01:00
parent 93377fd3a9
commit 622c4866da
2 changed files with 26 additions and 2 deletions

View File

@ -53,11 +53,13 @@ def cert_get(domains, settings):
key_file = settings['server_key']
if not os.path.isfile(key_file):
raise FileNotFoundError("The server key file (%s) is missing!" % key_file)
print("Server key not found at '{0}'. Creating RSA key.".format(key_file))
tools.new_rsa_key(key_file)
acc_file = settings['account_key']
if not os.path.isfile(acc_file):
raise FileNotFoundError("The account key file (%s) is missing!" % acc_file)
print("Account key not found at '{0}'. Creating RSA key.".format(acc_file))
tools.new_rsa_key(acc_file)
filename = hashlib.md5(domains).hexdigest()
_, csr_file = tempfile.mkstemp(".csr", "%s." % filename)

View File

@ -14,6 +14,7 @@ import os
from cryptography import x509
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.x509.oid import NameOID
@ -66,6 +67,27 @@ def new_cert_request(names, key):
return req
# @brief generate a new rsa key
# @param path path where the new key file should be written
def new_rsa_key(path, key_size=4096):
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=key_size,
backend=default_backend()
)
pem = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption()
)
with open(path, 'wb') as pem_out:
pem_out.write(pem)
try:
os.chmod(path, int("0400", 8))
except OSError:
print('Warning: Could not set file permissions on {0}!'.format(path))
# @brief convert certificate to PEM format
# @param cert certificate object in pyopenssl format
# @return the certificate in PEM format