A command to generate a self signed certificate for dev purposes.
    :param name: name ro be given to the cert and key
    :param dest: location on local filesystem to store the generated files
    :return:
487467
def create_dev_cert(name, dest):
    
    if not os.path.exists(dest):
        os.makedirs(dest)
    keygen.gen_ca_cert(name, dest, 3650)
1268058
public static ResourceRecordSet<CERTData> cert(String name, Collection<String> certdata) {
    return new CERTBuilder().name(name).addAll(certdata).build();
  }
232462
def sign(self, filename):
        
        sign = self.signcmd()
        certificate = self.certificate()
        if not sign:
            log.error('No signcmd defined.')
            return False
        elif not certificate and '{cert}' in sign:
            log.error('No sign certificated defined.')
            return False

        log.info('Signing {0}...'.format(filename))
        sign = os.path.expandvars(sign)
        filename = os.path.expandvars(filename)
        cert = os.path.expandvars(certificate)

        # let the previous process finish fully, or we might get some file errors
        time.sleep(2)
        return cmdexec(sign.format(filename=filename, cert=cert)) == 0
89525
def generate_certificates(base_dir: str, remove_certificates: bool=False):
    ''' '''
    public_keys_dir = os.path.join(base_dir, 'public_keys')
    secret_keys_dir = os.path.join(base_dir, 'private_keys')

    # Make the public and private key directories
    for path in (public_keys_dir, secret_keys_dir):
        if not os.path.exists(path):
            os.mkdir(path)

    # create new keys in certificates dir
    server_public_file, server_secret_file = zmq.auth.create_certificates(base_dir, "vexbot")
    client_public_file, client_secret_file = zmq.auth.create_certificates(base_dir, "client")

    vexbot_public = os.path.join(public_keys_dir, 'vexbot.key')
    client_public = os.path.join(public_keys_dir, 'client.key')

    vexbot_secret = os.path.join(secret_keys_dir, 'vexbot.key_secret')
    client_secret = os.path.join(secret_keys_dir, 'client.key_secret')

    if os.path.exists(vexbot_public) and remove_certificates:
        os.unlink(vexbot_public)
        try:
            os.unlink(vexbot_secret)
        except OSError:
            pass
    elif os.path.exists(vexbot_public) and not remove_certificates:
        os.unlink(server_public_file)
        os.unlink(server_secret_file)

    if os.path.exists(client_public) and remove_certificates:
        os.unlink(client_public)
        try:
            os.unlink(client_secret)
        except OSError:
            pass
    elif os.path.exists(client_public) and not remove_certificates:
        os.unlink(client_public_file)
        os.unlink(client_secret_file)

    # move public keys to appropriate directory
    for key_file in os.listdir(base_dir):
        if key_file.endswith(".key"):
            shutil.move(os.path.join(base_dir, key_file),
                        os.path.join(public_keys_dir, '.'))

    # move secret keys to appropriate directory
    for key_file in os.listdir(base_dir):
        if key_file.endswith(".key_secret"):
            shutil.move(os.path.join(base_dir, key_file),
                        os.path.join(secret_keys_dir, '.'))
1180657
def process_js_certs(self, data, name, idx, sub_idx):
        
        from cryptography.x509.base import load_der_x509_certificate

        ret = []
        for crt_hex in data:
            try:
                bindata = base64.b64decode(crt_hex)
                x509 = load_der_x509_certificate(bindata, self.get_backend())

                self.num_ldiff_cert += 1
                sub = self.process_x509(x509, name=name, pem=False, source='ldiff-cert')
                ret.append(sub)

            except Exception as e:
                logger.debug('Error in line JSON cert file processing %s, idx %s, subidx %s : %s'
                             % (name, idx, sub_idx, e))
                self.trace_logger.log(e)
        return ret
557411
def GenerateKeys(config, overwrite_keys=False):
  """"""
  if not hasattr(key_utils, "MakeCACert"):
    raise OpenSourceKeyUtilsRequiredError(
        "Generate keys can only run with open source key_utils.")
  if (config.Get("PrivateKeys.server_key", default=None) and
      not overwrite_keys):
    print(config.Get("PrivateKeys.server_key"))
    raise KeysAlreadyExistError(
        "Config %s already has keys, use --overwrite_keys to "
        "override." % config.parser)

  length = grr_config.CONFIG["Server.rsa_key_length"]
  print("All keys will have a bit length of %d." % length)
  print("Generating executable signing key")
  executable_key = rdf_crypto.RSAPrivateKey.GenerateKey(bits=length)
  config.Set("PrivateKeys.executable_signing_private_key",
             executable_key.AsPEM())
  config.Set("Client.executable_signing_public_key",
             executable_key.GetPublicKey().AsPEM())

  print("Generating CA keys")
  ca_key = rdf_crypto.RSAPrivateKey.GenerateKey(bits=length)
  ca_cert = key_utils.MakeCACert(ca_key)
  config.Set("CA.certificate", ca_cert.AsPEM())
  config.Set("PrivateKeys.ca_key", ca_key.AsPEM())

  print("Generating Server keys")
  server_key = rdf_crypto.RSAPrivateKey.GenerateKey(bits=length)
  server_cert = key_utils.MakeCASignedCert(u"grr", server_key, ca_cert, ca_key)
  config.Set("Frontend.certificate", server_cert.AsPEM())
  config.Set("PrivateKeys.server_key", server_key.AsPEM())

  print("Generating secret key for csrf protection.")
  _GenerateCSRFKey(config)
809355
def generateCertificate(cls):
        
        key = generate_key()
        cert = generate_certificate(key)
        return cls(key=key, cert=cert)
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;
}
1125176
def normalize_cert_dir():
    '''
        
    '''
    current_cn = get_crt_common_name()

    if not os.path.isdir(COZY_CONFIG_PATH):
        print 'Need to create {}'.format(COZY_CONFIG_PATH)
        os.mkdir(COZY_CONFIG_PATH, 0755)

    if not os.path.isdir(CERTIFICATES_PATH):
        print 'Need to create {}'.format(CERTIFICATES_PATH)
        os.mkdir(CERTIFICATES_PATH, 0755)

    if not os.path.isdir(ACME_PRIVATE_PATH):
        print 'Need to create {}'.format(ACME_PRIVATE_PATH)
        os.mkdir(ACME_PRIVATE_PATH, 0700)

    if os.path.isfile(OLD_CERTIFICATE_PATH) and \
            not os.path.islink(OLD_CERTIFICATE_PATH):
        target = '{}/{}.crt'.format(CERTIFICATES_PATH, current_cn)
        print 'Move {} to {}'.format(CERTIFICATES_PATH, target)
        os.rename(OLD_CERTIFICATE_PATH, target)
    else:
        print 'Nothing to do for {}'.format(OLD_CERTIFICATE_PATH)

    if os.path.isfile(OLD_PRIVATE_KEY_PATH) and \
            not os.path.islink(OLD_PRIVATE_KEY_PATH):
        target = '{}/{}.key'.format(CERTIFICATES_PATH, current_cn)
        print 'Move {} to {}'.format(OLD_PRIVATE_KEY_PATH, target)
        os.rename(OLD_PRIVATE_KEY_PATH, target)
    else:
        print 'Nothing to do for {}'.format(OLD_PRIVATE_KEY_PATH)

    if current_cn:
        make_links(current_cn)
1351953
function(key, dest, containerName) {

      // Attempt to connect to redis
      return getRedisClient()

      // Run the redis query and then quit
      .then(function(redis) {
        log.debug(format('Setting DNS. %s => %s', key, dest));
        return Promise.fromNode(function(cb) {
          redis.multi()
          .del(key)
          .rpush(key, containerName)
          .rpush(key, dest)
          .exec(cb);
        })
        .then(function() {
          redis.quit();
        });
      });

    }
683504
def verify_certs(*args):
    '''
    
    '''
    msg = ("Could not find a certificate: {0}\n"
            "If you want to quickly generate a self-signed certificate, "
            "use the tls.create_self_signed_cert function in Salt")

    for arg in args:
        if not os.path.exists(arg):
            raise Exception(msg.format(arg))
743926
def _cert_file(name, cert_type):
    '''
    
    '''
    return os.path.join(LE_LIVE, name, '{0}.pem'.format(cert_type))
1066681
def create_ssl_certs(self):
        
        for key, file in self.ssl.items():
            file["file"] = self.create_temp_file(file["suffix"], file["content"])
1314381
def _generateGUID(slnfile, name):
    """"""
    m = hashlib.md5()
    # Normalize the slnfile path to a Windows path (\ separators) so
    # the generated file has a consistent GUID even if we generate
    # it on a non-Windows platform.
    m.update(bytearray(ntpath.normpath(str(slnfile)) + str(name),'utf-8'))
    solution = m.hexdigest().upper()
    # convert most of the signature to GUID form (discard the rest)
    solution = "{" + solution[:8] + "-" + solution[8:12] + "-" + solution[12:16] + "-" + solution[16:20] + "-" + solution[20:32] + "}"
    return solution
205199
def export(gandi, resource, output, force, intermediate):
    
    ids = []
    for res in resource:
        ids.extend(gandi.certificate.usable_ids(res))

    if output and len(ids) > 1:
        gandi.echo('Too many certs found, you must specify which cert you '
                   'want to export')
        return

    for id_ in set(ids):
        cert = gandi.certificate.info(id_)
        if 'cert' not in cert:
            continue

        if cert['status'] != 'valid':
            gandi.echo('The certificate must be in valid status to be '
                       'exported (%s).' % id_)
            continue

        cert_filename = cert['cn'].replace('*.', 'wildcard.', 1)
        crt_filename = output or cert_filename + '.crt'
        if not force and os.path.isfile(crt_filename):
            gandi.echo('The file %s already exists.' % crt_filename)
            continue

        crt = gandi.certificate.pretty_format_cert(cert)
        if crt:
            with open(crt_filename, 'w') as crt_file:
                crt_file.write(crt)
                gandi.echo('wrote %s' % crt_filename)

        package = cert['package']
        if 'bus' in package and intermediate:
            gandi.echo('Business certs do not need intermediates.')
        elif intermediate:
            crtf = 'pem'
            sha_version = cert['sha_version']
            type_ = package.split('_')[1]
            extra = ('sgc' if 'SGC' in package
                     and 'pro' in package
                     and sha_version == 1 else 'default')

            if extra == 'sgc':
                crtf = 'pem'

            inters = gandi.certificate.urls[sha_version][type_][extra][crtf]
            if isinstance(inters, basestring):
                inters = [inters]

            fhandle = open(cert_filename + '.inter.crt', 'w+b')
            for inter in inters:
                if inter.startswith('http'):
                    data = requests.get(inter).text
                else:
                    data = inter
                fhandle.write(data.encode('latin1'))

            gandi.echo('wrote %s' % cert_filename + '.inter.crt')
            fhandle.close()

        return crt
750029
def process_jks(self, data, name):
        
        if self.jks_file_passwords is None and self.args.jks_pass_file is not None:
            self.jks_file_passwords = []
            if not os.path.exists(self.args.jks_pass_file):
                logger.warning('JKS password file %s does not exist' % self.args.jks_pass_file)
            with open(self.args.jks_pass_file) as fh:
                self.jks_file_passwords = sorted(list(set([x.strip() for x in fh])))
                
        if self.jks_file_passwords is None:
            self.jks_file_passwords = []

        try:
            ks = self.try_open_jks(data, name)
            if ks is None:
                logger.warning('Could not open JKS file: %s, password not valid, '
                               'try specify passwords in --jks-pass-file' % name)
                return

            # certs
            from cryptography.x509.base import load_der_x509_certificate

            ret = []
            for alias, cert in list(ks.certs.items()):
                try:
                    x509 = load_der_x509_certificate(cert.cert, self.get_backend())

                    self.num_jks_cert += 1
                    sub = self.process_x509(x509, name=name, pem=False, source='jks-cert', aux='cert-%s' % alias)
                    ret.append(sub)

                except Exception as e:
                    logger.debug('Error in JKS cert processing %s, alias %s : %s' % (name, alias, e))
                    self.trace_logger.log(e)

            # priv key chains
            for alias, pk in list(ks.private_keys.items()):
                for idx, cert in enumerate(pk.cert_chain):
                    try:
                        x509 = load_der_x509_certificate(cert[1], self.get_backend())

                        self.num_jks_cert += 1
                        sub = self.process_x509(x509, name=name, pem=False, source='jks-cert-chain',
                                                aux='cert-chain-%s-%s' % (alias, idx))
                        ret.append(sub)

                    except Exception as e:
                        logger.debug('Error in JKS priv key cert-chain processing %s, alias %s %s : %s'
                                     % (name, alias, idx, e))
                        self.trace_logger.log(e)
            return ret

        except ImportException:
            return [TestResult(fname=name, type='jks-cert', error='cannot-import')]

        except Exception as e:
            logger.warning('Exception in JKS processing: %s' % e)
            return None
1117387
def __generate_key(self, config):
        
        cwd = config.get('ssh_path', self._install_directory())
        if config.is_affirmative('create', default="yes"):
            if not os.path.exists(cwd):
                os.makedirs(cwd)
            if not os.path.exists(os.path.join(cwd, config.get('keyname'))):
                command = "ssh-keygen -t %(type)s -f %(keyname)s -N  " % config.to_dict()
                lib.call(command, cwd=cwd, output_log_level=logging.DEBUG)
        if not config.has('ssh_path'):
            config.set('ssh_path', cwd)
        config.set('ssh_key_path', os.path.join(config.get('ssh_path'), config.get('keyname')))