generate a CA key and certificate key pair.
    :param filename: prefix for the key and cert file
    :param dirname: name of the directory
    :param days: days of the certificate being valid
    :param silent: whether to suppress output
429348
def gen_ca_cert(filename, dirname, days, silent=False):
    
    keyfile = os.path.join(dirname, '{}.key'.format(filename))
    ca_crt = os.path.join(dirname, '{}.crt'.format(filename))
    gen_private_key(keyfile, silent)
    gen_self_signed_cert(ca_crt, keyfile, days, silent)
712419
protected void createKeystore() {

		java.security.cert.Certificate signingCert = null;
		PrivateKey  caPrivKey  = null;

		if(_caCert == null || _caPrivKey == null)
		{
			try
			{
				log.debug("Keystore or signing cert & keypair not found.  Generating...");

				KeyPair caKeypair = getRSAKeyPair();
				caPrivKey = caKeypair.getPrivate();
				signingCert = CertificateCreator.createTypicalMasterCert(caKeypair);

				log.debug("Done generating signing cert");
				log.debug(signingCert);

				_ks.load(null, _keystorepass);

				_ks.setCertificateEntry(_caCertAlias, signingCert);
				_ks.setKeyEntry(_caPrivKeyAlias, caPrivKey, _keypassword, new java.security.cert.Certificate[] {signingCert});

				File caKsFile = new File(root, _caPrivateKeystore);

				OutputStream os = new FileOutputStream(caKsFile);
				_ks.store(os, _keystorepass);

				log.debug("Wrote JKS keystore to: " +
						caKsFile.getAbsolutePath());

				// also export a .cer that can be imported as a trusted root
				// to disable all warning dialogs for interception

				File signingCertFile = new File(root, EXPORTED_CERT_NAME);

				FileOutputStream cerOut = new FileOutputStream(signingCertFile);

				byte[] buf = signingCert.getEncoded();

				log.debug("Wrote signing cert to: " + signingCertFile.getAbsolutePath());

				cerOut.write(buf);
				cerOut.flush();
				cerOut.close();

				_caCert = (X509Certificate)signingCert;
				_caPrivKey  = caPrivKey;
			}
			catch(Exception e)
			{
				log.error("Fatal error creating/storing keystore or signing cert.", e);
				throw new Error(e);
			}
		}
		else
		{
			log.debug("Successfully loaded keystore.");
			log.debug(_caCert);

		}

	}
1097990
def get_system_cert_file():
    
    if os.name == 'posix':
        filename = "/etc/ssl/certs/ca-certificates.crt"
        if os.path.isfile(filename):
            return filename
    msg = "no system certificate file found"
    raise ValueError(msg)
72854
def getCert(certHost=vos.vos.SERVER, certfile=None,
            certQuery="/cred/proxyCert?daysValid=",daysValid=2):
    """"""

    if certfile is None:
        certfile = os.path.join(os.getenv("HOME","/tmp"),".ssl/cadcproxy.pem")

    dirname = os.path.dirname(certfile)
    try:
        os.makedirs(dirname)
    except OSError as e:
        if os.path.isdir(dirname):
            pass
        elif e.errno == 20 or e.errno == 17:
            sys.stderr.write(str(e)+": %s \n" % dirname)
            sys.stderr.write("Expected %s to be a directory.\n" % ( dirname))
            sys.exit(e.errno)
        else:
            raise e
    
    # Example taken from voidspace.org.uk
    # create a password manager
    password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()

    (username, passwd) = getUserPassword(host=certHost)

    # Add the username and password.
    # If we knew the realm, we could use it instead of ``None``.
    top_level_url = "http://"+certHost
    password_mgr.add_password(None, top_level_url, username, passwd)
    
    handler = urllib2.HTTPBasicAuthHandler(password_mgr)
    
    # create "opener" (OpenerDirector instance)
    opener = urllib2.build_opener(handler)
    
    # Install the opener.   
    urllib2.install_opener(opener)

    # Now all calls to urllib2.urlopen use our opener.
    url="http://"+certHost+certQuery+str(daysValid)
    r= urllib2.urlopen(url)
    w= file(certfile,'w')
    while True:
        buf=r.read()
        if not buf:
            break
        w.write(buf)
    w.close()
    r.close()
    return
640476
def setDirname(self, dirname):
        
        # Make sure the dirname always ends in
        # a path separator character
        sep = utils._getPathSep(dirname)
        if not dirname.endswith(sep):
            dirname += sep

        self._dir = utils.asString(dirname)
283302
def create_key(file_):
    
    pkey = crypto.PKey()
    pkey.generate_key(crypto.TYPE_RSA, 2048)

    file_.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey))
    file_.flush()
403699
def cli_sign_jar(argument_list=None):
    

    usage_message = "jarutil s [OPTIONS] jar_file cert_file " \
                    "key_file key_alias"

    parser = argparse.ArgumentParser(usage=usage_message)

    parser.add_argument("jar_file", type=str,
                        help="JAR file to sign")
    parser.add_argument("cert_file", type=str,
                        help="Certificate file (PEM format)")
    parser.add_argument("key_file", type=str,
                        help="Private key file (PEM format)")
    parser.add_argument("key_alias", type=str,
                        help="JAR \"key alias\" to use")

    parser.add_argument("-d", "--digest", action="store", default="SHA-256",
                        # TODO: factor to a constant
                        help="Digest algorithm used for signing")

    parser.add_argument("-c", "--chain", action="append",
                        dest="extra_certs", default=[],
                        help="Additional certificates to embed into the"
                        " signature (PEM format). More than one \"-c\" option"
                        " can be provided.")

    parser.add_argument("-o", "--output", action="store", default=None,
                        help="Filename to put signed jar. If not provided, the"
                        " signature is added to the original jar file.")

    args = parser.parse_args(argument_list)

    try:
        sign(args.jar_file, args.cert_file, args.key_file, args.key_alias,
             args.extra_certs, args.digest, args.output)

    except CannotFindKeyTypeError:
        print("Cannot determine private key type in %s" % args.key_file)
        return 1

    except MissingManifestError:
        print("Manifest missing in jar file %s" % args.jar_file)
        return 2

    return 0
241596
def cert(self):
        
        if self.cert_files is not None:
            return self.cert_files

        certs = self.certs or '/certs/'
        ssl_path = os.path.join(os.pardir, certs)
        try:
            cert_path = os.listdir(ssl_path)
        except FileNotFoundError:
            raise CertsError(certs)
        except OSError:   # Python 2 compatability
            raise CertsError(certs)

        cert = None
        key = None
        for file in cert_path:
            ext = os.path.splitext(file)[-1]
            if ext in ['.crt', '.cert']:
                cert = os.path.join(ssl_path, file)
            elif ext == '.key':
                key = os.path.join(ssl_path, file)
        if cert is None or key is None:
            raise CertsError(certs)
        return [cert, key]
360193
def gen_private_key(filepath, silent=False):
    
    cmd = 'openssl genrsa -out {} 2048'.format(filepath)
    message = 'generate private key {}'.format(filepath)
    call_openssl(cmd, message, silent)
1196186
def write_keyring(path, key, uid=-1, gid=-1):
    
    # Note that we *require* to avoid deletion of the temp file
    # otherwise we risk not being able to copy the contents from
    # one file system to the other, hence the `delete=False`
    tmp_file = tempfile.NamedTemporaryFile('wb', delete=False)
    tmp_file.write(key)
    tmp_file.close()
    keyring_dir = os.path.dirname(path)
    if not path_exists(keyring_dir):
        makedir(keyring_dir, uid, gid)
    shutil.move(tmp_file.name, path)
1066629
async function generateCsr(opts, csrConfig, key) {
    let tempConfigFilePath;

    /* Write key to disk */
    const tempKeyFilePath = tempfile();
    await fs.writeFileAsync(tempKeyFilePath, key);
    opts.key = tempKeyFilePath;

    /* Write config to disk */
    if (csrConfig) {
        tempConfigFilePath = tempfile();
        await fs.writeFileAsync(tempConfigFilePath, csrConfig);
        opts.config = tempConfigFilePath;
    }

    /* Create CSR */
    const result = await openssl('req', opts);

    /* Clean up */
    await fs.unlinkAsync(tempKeyFilePath);

    if (tempConfigFilePath) {
        await fs.unlinkAsync(tempConfigFilePath);
    }

    return result;
}
267044
public static void prepareX509Infrastructure(X509Metadata metadata, File serverKeyStore, File serverTrustStore, X509Log x509log) {
        // make the specified folder, if necessary
        File folder = serverKeyStore.getParentFile();
        folder.mkdirs();

        // Fathom CA certificate
        File caKeyStore = new File(folder, CA_KEY_STORE);
        if (!caKeyStore.exists()) {
            logger.info(MessageFormat.format("Generating {0} ({1})", CA_CN, caKeyStore.getAbsolutePath()));
            X509Certificate caCert = newCertificateAuthority(metadata, caKeyStore, x509log);
            saveCertificate(caCert, new File(caKeyStore.getParentFile(), "ca.cer"));
        }

        // Fathom CRL
        File caRevocationList = new File(folder, CA_REVOCATION_LIST);
        if (!caRevocationList.exists()) {
            logger.info(MessageFormat.format("Generating {0} CRL ({1})", CA_CN, caRevocationList.getAbsolutePath()));
            newCertificateRevocationList(caRevocationList, caKeyStore, metadata.password);
            x509log.log("new certificate revocation list created");
        }

        // create web SSL certificate signed by CA
        if (!serverKeyStore.exists()) {
            logger.info(MessageFormat.format("Generating SSL certificate for {0} signed by {1} ({2})", metadata.commonName, CA_CN, serverKeyStore.getAbsolutePath()));
            PrivateKey caPrivateKey = getPrivateKey(CA_ALIAS, caKeyStore, metadata.password);
            X509Certificate caCert = getCertificate(CA_ALIAS, caKeyStore, metadata.password);
            newSSLCertificate(metadata, caPrivateKey, caCert, serverKeyStore, x509log);
        }

        // server certificate trust store holds trusted public certificates
        if (!serverTrustStore.exists()) {
            logger.info(MessageFormat.format("Importing {0} into trust store ({1})", CA_ALIAS, serverTrustStore.getAbsolutePath()));
            X509Certificate caCert = getCertificate(CA_ALIAS, caKeyStore, metadata.password);
            addTrustedCertificate(CA_ALIAS, caCert, serverTrustStore, metadata.password);
        }
    }
953413
def generate_signing_key(args):
    
    if os.path.exists(args.keyfile):
        raise esptool.FatalError("ERROR: Key file %s already exists" % args.keyfile)
    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)
1283042
def save_certificate(certificate)
      return unless certificate
      return HerokuOutput.new(common_domain_name, certificate).output unless ENV['DYNO'].nil?
      output_dir = File.join(Rails.root, @options[:output_cert_dir])
      return FileOutput.new(common_domain_name, certificate, output_dir).output if File.directory?(output_dir)
      Rails.logger.error("Output directory: '#{output_dir}' does not exist!")
    end
880289
def generate_keystore(key_alias, key_folder='./', root_cert='', truststore='', password='', organization='', organization_unit='', locality='', country='', key_size=2048, verbose=True, overwrite=False):

    '''  '''

    title = 'generate_keystore'
    
# import dependencies
    import os
    from subprocess import call, STDOUT, Popen, PIPE
    DEVNULL = open(os.devnull, 'w')

# define system call
    def _call(sys_command, ignore='', prompt_input='', title=''):
        if title and verbose:
            print('%s ... ' % title, end='', flush=True)
        p = Popen(sys_command, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT)
        if prompt_input:
            stdout, stderr = p.communicate(str('%s\n' % prompt_input).encode('utf-8'))
        if p.returncode != 0:
            cmd_err = p.stdout.read().decode()
            if not cmd_err:
                pass
            elif ignore:
                if not cmd_err.find(ignore) > -1:
                    raise Exception(cmd_err)
            else:
                if title and verbose:
                    print('ERROR.')
                raise Exception(cmd_err)
        if title and verbose:
            print('done.')

# verify libraries
    try:
        call('openssl version', shell=True, stdout=DEVNULL)
    except:
        raise Exception('%s requires openssl library. try: sudo apt-get install openssl' % title)
    try:
        _call('keytool -help', ignore='Key and Certificate Management Tool')
    except:
        raise Exception('%s requires keytool library. try: sudo apt-get install openjdk-8-jre' % title)

# validate input
    if not isinstance(key_alias, str):
        raise ValueError('%s(key_alias="...") must be a string datatype.' % title)
    if not key_size in (2048, 4096):
        raise ValueError('%s(key_size=%s must be either 2048 or 4096' % (title, key_size))
    import re
    input_fields = {
        'organization': organization,
        'organization_unit': organization_unit,
        'locality': locality,
        'country': country
    }
    for key, value in input_fields.items():
        if re.findall('[^\w_\-\s]', value):
            raise ValueError('%s(%s="%s") must contain only alphanumeric characters, _, - and spaces.' % (title, key, value))

# construct key folder
    from os import path, makedirs, remove
    if not path.exists(key_folder):
        makedirs(key_folder)
    elif not path.isdir(key_folder):
        raise ValueError('%s(key_folder="%s") must be a directory.' % (title, key_folder))

# validate cert path
    cert_path = path.join(key_folder, '%s.crt' % key_alias)
    if path.exists(cert_path) and not overwrite:
        raise ValueError('%s.crt already exists in %s. to overwrite, set overwrite=true' % (key_alias, key_folder))

# validate root path
    from copy import deepcopy
    root_cert_copy = deepcopy(root_cert)
    if root_cert_copy:
        if not path.exists(root_cert_copy):
            root_cert_copy = path.join(key_folder, root_cert_copy)
            if not path.exists(root_cert_copy):
                raise ValueError('%s(root_cert="%s") is not a valid path.' % (title, root_cert_copy))
        root_node, root_ext = path.splitext(root_cert_copy)
        root_key = root_node + '.key'
        if not root_ext in ('.crt', '.pem'):
            raise ValueError('%s(root_cert="%s") must be a .crt or .pem file type.' % (title, root_cert_copy))
        elif not path.exists(root_key):
            key_path, key_name = path.split(root_key)
            raise ValueError('%s(root_cert="%s") requires a matching private key %s' % (title, root_cert_copy, key_name))
        root_path = root_cert_copy
        key_path = root_path.replace('.crt', '.key')
    else:
        key_path = path.join(key_folder, 'root.key')
        root_path = path.join(key_folder, 'root.crt')
        if path.exists(root_path) and not overwrite:
            raise ValueError('root.crt already exists in %s. to overwrite, set overwrite=true' % key_folder)

# validate truststore path
    truststore_copy = deepcopy(truststore)
    if truststore_copy:
        if not path.exists(truststore_copy):
            truststore_copy = path.join(key_folder, truststore_copy)
            if not path.exists(truststore_copy):
                raise ValueError('%s(truststore="%s") is not a valid path.' % (title, truststore_copy))
        trust_node, trust_ext = path.splitext(truststore_copy)
        if not trust_ext in ('.jks'):
            raise ValueError('%s(truststore="%s") must be a .jks file type.' % (title, truststore_copy))
        truststore_path = truststore_copy
        trust_root, trust_node = path.split(truststore_path)
        trust_alias, trust_ext = path.splitext(trust_node)
    else:
        truststore_path = path.join(key_folder, 'truststore.jks')
        trust_alias = 'truststore'
        if path.exists(truststore_path) and not overwrite:
            raise ValueError('%s.jks already exists in %s. to overwrite, set overwrite=true' % (trust_alias, key_folder))

# format DNAME fields
    if not organization:
        organization = 'None'
    if not organization_unit:
        organization_unit = 'None'
    if not locality:
        locality = 'None'
    if not country:
        country = 'None'

# create root certificate
    if not root_cert_copy:
        subject_args = '/CN=root/OU=%s/O=%s/L=%s/C=%s' % (
            organization_unit,
            organization,
            locality,
            country
        )
        root_subject = '-subj %s' % subject_args.replace(' ', '\ ')
        password_text = '-passout pass:%s' % password
        sys_command = 'openssl req -newkey rsa:%s -x509 -nodes -keyout %s -out %s -days 36500 %s %s' % (key_size, key_path, root_path, root_subject, password_text)
        _call(sys_command, ignore='writing new private key', title='Generating root certificate')

# generate server cert
    server_dname = '-dname "CN=%s, OU=%s, O=%s, L=%s, C=%s"' % (
        key_alias, organization_unit, organization, locality, country
    )
    keystore_path = path.join(key_folder, '%s.jks' % key_alias)
    if path.exists(keystore_path) and not overwrite:
        raise ValueError('%s.jks already exists in %s. to overwrite, set overwrite=true' % (key_alias, key_folder))
    elif path.exists(keystore_path):
        remove(keystore_path)
    sys_command = 'keytool -genkey -keyalg RSA -alias %s -validity 36500 -keystore %s -storepass %s -keypass %s -keysize %s %s' % (key_alias, keystore_path, password, password, key_size, server_dname)
    _call(sys_command, ignore='JKS keystore uses a proprietary format', title='Generating keystore for %s' % key_alias)

# convert cert to pkcs12
    sys_command = 'keytool -importkeystore -srckeystore %s -destkeystore %s -deststoretype pkcs12 -storepass %s -keypass %s' % (keystore_path, keystore_path, password, password)
    _call(sys_command, prompt_input=password, title='Converting keystore to pkcs12 standard')
    remove('%s.old' % keystore_path)

# generate certificate request
    request_path = path.join(key_folder, '%s.csr' % key_alias)
    sys_command = 'keytool -certreq -alias %s -file %s -keystore %s -storepass %s -keypass %s %s' % (
        key_alias, request_path, keystore_path, password, password, server_dname
    )
    _call(sys_command, title='Generating certificate signing request for %s'% key_alias)

# sign server cert with root cert
    cert_path = path.join(key_folder, '%s.crt' % key_alias)
    sys_command = 'openssl x509 -req -CA %s -CAkey %s -in %s -out %s -days 36500 -CAcreateserial -passin pass:%s' % (root_path, key_path, request_path, cert_path, password)
    _call(sys_command, ignore='Getting CA Private Key', title='Signing certificate for %s with root certificate' % key_alias)

# add root cert to server keystore
    root_root, root_node = path.split(root_path)
    root_alias, root_ext = path.splitext(root_node)
    sys_command = 'keytool -importcert -keystore %s -alias %s -file %s -noprompt -keypass %s -storepass %s' % (keystore_path, root_alias, root_path, password, password)
    _call(sys_command, ignore='Certificate was added to keystore', title='Adding root certificate to keystore for %s' % key_alias)

# add server cert to server keystore
    sys_command = 'keytool -importcert -keystore %s -alias %s -file %s -noprompt -keypass %s -storepass %s' % (keystore_path, key_alias, cert_path, password, password)
    _call(sys_command, ignore='Certificate reply was installed in keystore', title='Adding certificate for %s to keystore for %s' % (key_alias, key_alias))

# add root certificate to truststore
    if not truststore_copy:
        if path.exists(truststore_path):
            remove(truststore_path)
        sys_command = 'keytool -importcert -keystore %s -alias %s -file %s -noprompt -keypass %s -storepass %s' % (truststore_path, root_alias, root_path, password, password)
        _call(sys_command, ignore='Certificate was added to keystore', title='Generating truststore for root certificate')

# add server cert to truststore
    sys_command = 'keytool -importcert -keystore %s -alias %s -file %s -noprompt -keypass %s -storepass %s' % (truststore_path, key_alias, cert_path, password, password)
    _call(sys_command, ignore='Certificate was added to keystore', title='Adding certificate for %s to truststore' % key_alias)

# remove .srl files
    from os import listdir
    for file_name in listdir('./'):
        if file_name == '.srl':
            remove(file_name)
    for file_name in listdir(key_folder):
        file_alias, file_ext = path.splitext(file_name)
        if file_ext == '.srl':
            remove(path.join(key_folder, file_name))

    return True
985006
def _makeCertificate(key, email, _utcnow=datetime.utcnow):
    
    # Create a certificate for this key.
    cert = X509()
    cert.set_pubkey(key)

    # Set the subject.
    subject = cert.get_subject()
    subject.CN = u"Crypto 101 Client"
    subject.emailAddress = email

    # Expiration dates. Mandatory.
    now = _utcnow()
    start = now.replace(hour=0, minute=0, second=0)
    cert.set_notBefore(start.strftime(_ASN1_GENERALIZEDTIME_FORMAT))
    end = start.replace(year=start.year + 5)
    cert.set_notAfter(end.strftime(_ASN1_GENERALIZEDTIME_FORMAT))

    # Self-sign.
    cert.set_issuer(cert.get_subject())
    cert.sign(key, "sha512")

    return cert
338172
def make_filename_hash(key):
    
    key_repr = repr(key).replace(BASE_DIR, '').encode('utf8')
    # This is really stupid but necessary for making the repr()s be the same on
    # Python 2 and 3 and thus allowing the test suite to run on both.
    # TODO better solutions include: not using a repr, not embedding hashes in
    # the expected test results
    if sys.platform == 'win32':
        # this is to make sure the hash is the same on win and unix platforms
        key_repr = key_repr.replace(b'\\\\', b'/')
    key_repr = re.sub(b"\\bu'", b"'", key_repr)
    key_hash = hashlib.md5(key_repr).digest()
    return base64.b64encode(key_hash, b'__').decode('ascii').rstrip('=')