def dump_cert_data(key_file: pathlib.Path, cert_file: pathlib.Path, keystore: crypto.PKCS12) -> None: with cert_file.open("wt") as f: f.write( crypto.dump_certificate( crypto.FILETYPE_PEM, keystore.get_certificate()).decode("utf-8")) with key_file.open("wt") as f: f.write( crypto.dump_privatekey(crypto.FILETYPE_PEM, keystore.get_privatekey()).decode("utf-8"))
def p12create(p12file): try: p12 = PKCS12() p12.set_certificate(pub) p12.set_privatekey(privkey) p12.set_friendlyname(alias) p12data = p12.export(passw, iter=2048, maciter=1) except: return 'Failed to create p12 Object of p12create() method' try: newfile = open(p12file, 'wb+') newfile.write(p12data) newfile.close() except: print("Problem in p12create method. Couldn't write file: %s" % (p12file))
def to_pkcs12(self, password): p12 = PKCS12() # convert M2Crypto keys & certs into OpenSSL's format using DER # yes, a bit wasteful as we're going into one OpenSSL wrapper to # another. perhaps settle on an OpenSSL wrapper at some point. cert_pem = self.get_cert().to_pem() p12.set_certificate(load_certificate(FILETYPE_PEM, cert_pem)) key_pem = self.get_private_key().to_pem() p12.set_privatekey(load_privatekey(FILETYPE_PEM, key_pem)) cvt_cacerts = [] for cacert in self.addl_certs: cvt_cacert = cacert.to_pem() cvt_cacerts.append(load_certificate(FILETYPE_PEM, cvt_cacert)) return p12.export(password)
def save_p12(cert, private, file_name, passphrase=None): host_folder = os.getenv(HOST_FOLDER_EXPORTS_PATH_ENV_KEY) if file_name and host_folder: openssl_cert = X509.from_cryptography(cert) openssl_priv_key = PKey.from_cryptography_key(private) p12 = PKCS12() p12.set_privatekey(openssl_priv_key) p12.set_certificate(openssl_cert) p12bin = p12.export(passphrase) file_path = PATH_TO_EXPORTS_FOLDER + '/{}.p12'.format(file_name) if os.path.isfile(file_path): raise ValueError with open(file_path, 'wb') as f: f.write(p12bin) return host_folder + '/{}.p12'.format(file_name)
def dump_keystore(pkcs12_file: pathlib.Path, keystore: crypto.PKCS12, passphrase: str) -> None: with pkcs12_file.open("wb") as f: f.write(keystore.export(passphrase=passphrase.encode()))
def request_certificate(csr: crypto.X509Req, token_id: str, client_cert: crypto.PKCS12, domains: [str], cert_file: str = None, cert_type: str = "DVSSL"): """Request certificate from StartSSL. :param csr: The csr with which to request the certificate. :param token_id: The token id to present to StartSSL. :param client_cert: The client certificate to present to StartSSL. :param domains: The list of domains to add to the request. :param cert_file: The file name relative to SSL_DIR to store the certificate if issued. Pass None to disable. :param cert_type: The type of certificate to request from StartSSL. :return: Returns a tuple containing the StartSSL request status and the certificate in PEM format if successful. """ # # # ------ INNER CLASS DECLARATIONS ------ # # # # Class to manage making sensitive temporary files securely (ensuring deletion, etc.) class make_temp_file: def __init__(self, suffix: str = None, prefix: str = None, dir_path: str = None, text: bool = False): self.temp_file = tempfile.mkstemp(suffix, prefix, dir_path, text) def __enter__(self): """Returns a tuple of the file object and its full path.""" return self.temp_file def __exit__(self, exc_type, exc_val, exc_tb): try: os.close(self.temp_file[0]) except OSError: # needs to be ignored so that the file as attempted to be destroyed print("Temporary file could not be closed.", file=sys.stderr) os.remove(self.temp_file[1]) # This file must be destroyed. If it errors out, let the error bubble up # # # ------ START OF FUNCTION ------ # # # # Create temporary file for requests library with make_temp_file('tmp', 'ProcessCerts', text=True) as temp_file: # Write unencrypted key temporarily to disk, will be destroyed by "with" when done os.write(temp_file[0], crypto.dump_certificate(crypto.FILETYPE_PEM, client_cert.get_certificate()) + crypto.dump_privatekey(crypto.FILETYPE_PEM, client_cert.get_privatekey())) # Request certificate r = requests.post( CertSecurityGlobals.DEBUG_API if CertSecurityGlobals.DEBUG_MODE else CertSecurityGlobals.PRODUCTION_API, data={'RequestData': json.dumps({ "tokenID": token_id, "actionType": "ApplyCertificate", "certType": cert_type, "domains": ",".join(domains), "CSR": crypto.dump_certificate_request(crypto.FILETYPE_PEM, csr).decode("utf-8") })}, cert=temp_file[1] ) # Decode response try: response_json = r.json() except ValueError: raise CertSecurityError( "Response sent was not JSON. Type: {0} Response:\n{1}".format(r.headers.get('content-type'), r.text)) # Bad request if not response_json['status'] == 1: raise CertSecurityError(response_json['shortMsg'], response_json['errorCode']) # CSR issuance status if response_json['data']['orderStatus'] == 1: # The request is pending print("The certificate has been successfully submitted and is pending issuance.\n" "\t Order ID: " + response_json['orderID']) return {'status': response_json['data']['orderStatus']} elif response_json['data']['orderStatus'] == 3: # The request was rejected print("The certificate request has been rejected.", file=sys.stderr) return {'status': response_json['data']['orderStatus']} elif response_json['data']['orderStatus'] != 2: # Unspecified error raise CertSecurityError(response_json['data']['orderStatus'], "Received an invalid response!") else: # The request was issued print("The certificate has been successfully issued.") # Get certificate cert_received = crypto.load_certificate(crypto.FILETYPE_PEM, base64.b64decode(response_json['data'][ 'certificate'], validate=True)) inter_cert = crypto.load_certificate(crypto.FILETYPE_PEM, base64.b64decode(response_json['data'][ 'intermediateCertificate'], validate=True)) # Save certificate if requested if cert_file: cert_file = os.path.join(CertSecurityGlobals.SSL_DIR, cert_file) for file_format, f in write_all_formats(cert_file): f.write(crypto.dump_certificate(file_format, cert_received)) return {'status': response_json['data']['orderStatus'], 'cert': cert_received, 'intermediate': inter_cert}
def CreateP12(self, Key, Cert, p12File, passphrase=None): p12 = PKCS12() p12.set_certificate(Cert) p12.set_privatekey(Key) p12File.write(p12.export(passphrase=passphrase))