Create the BinarySecurityToken node containing the x509 certificate.
181025
def create_binary_security_token(key_file):
    
    node = etree.Element(
        ns_id('BinarySecurityToken', ns.wssens),
        nsmap={ns.wssens[0]: ns.wssens[1]})
    node.set(ns_id('Id', ns.wsuns), get_unique_id())
    node.set('EncodingType', ns.wssns[1] + 'Base64Binary')
    node.set('ValueType', BINARY_TOKEN_TYPE)

    with open(key_file) as fh:
        cert = crypto.load_certificate(crypto.FILETYPE_PEM, fh.read())
        node.text = base64.b64encode(
            crypto.dump_certificate(crypto.FILETYPE_ASN1, cert))
    return node
139984
@SneakyThrows
    public X509Certificate loadCert(String certLocation) {
        CertificateFactory cf = CertificateFactory.getInstance("X509");
        Resource certRes = resourceLoader.getResource(certLocation);
        X509Certificate cert = (X509Certificate) cf.generateCertificate(certRes.getInputStream());
        return cert;
    }
372641
function generateAuthToken(bytes, callback) {
		crypto.randomBytes(bytes, function(err, randomBytes) {
			if(err) {
				return callback(err);
			}
			callback(null, randomBytes.toString('hex'));
		});
	}
17526
function openssl_x509(csr, ca_key, ca_cert, options) {
  while (csr && 'string' !== typeof csr) csr = csr.csr
  while (ca_cert && 'string' !== typeof ca_cert) ca_cert = ca_cert.cert

  if (!options) options = {}
  if (!csr) throw new Error("Parameter 'csr' is required")
  if (!ca_key) throw new Error("Parameter 'ca_key' is required")
  if (!ca_cert) throw new Error("Parameter 'ca_cert' is required")

  if (!options.extensions)
    options.extensions = extensionConfigForOpenSSL(options, 'v3_req')

  return Promise.all([
      tmpfile(csr),
      tmpfile(ca_cert),
      tmpfile(options.extensions),
      tmpfile(ec_pem.encodePrivateKey(ca_key)) ])
    .then(tmpList => {
      const [tmp_csr, tmp_ca_cert, tmp_ext, tmp_ca_key] = tmpList

      let args = ['x509', '-req', '-sha256']
      args.push('-days', options.days || 1, '-set_serial', options.serial || Date.now().toString())
      args.push('-extensions', 'v3_req', '-extfile', tmp_ext.path)
      args.push('-in', tmp_csr.path, '-CA', tmp_ca_cert.path, '-CAkey', tmp_ca_key.path)

      return finallyCleanupTmpList(openssl_stdout(args, 5), tmpList) })}
527204
def create_key(self, master_secret=b""):
        
        master_secret = deserialize.bytes_str(master_secret)
        bip32node = control.create_wallet(self.testnet,
                                          master_secret=master_secret)
        return bip32node.wif()
1242700
public X509Certificate createCertificate(InputStream certRequestInputStream, X509Certificate cert,
        PrivateKey privateKey, int lifetime, GSIConstants.CertificateType certType) throws IOException,
        GeneralSecurityException {
        return createCertificate(certRequestInputStream, cert, privateKey, lifetime, certType, (X509ExtensionSet) null,
            null);
    }
443757
def create_ssl_certificate(cert_params)
      file_path = cert_params[:output_file].sub(/\.(\w+)$/, "")
      path = prompt_for_file_path
      file_path = File.join(path, file_path) unless path.empty?
      cert_params[:domain] = prompt_for_domain

      rsa_key = generate_keypair cert_params[:key_length]
      cert = generate_certificate(rsa_key, cert_params)
      write_certificate_to_file cert, file_path, rsa_key, cert_params
      puts "*" * 70
      puts "Generated Certificates:"
      puts "- #{file_path}.pfx - PKCS12 format keypair. Contains both the public and private keys, usually used on the server."
      puts "- #{file_path}.b64 - Base64 encoded PKCS12 keypair. Contains both the public and private keys, for upload to the Azure REST API."
      puts "- #{file_path}.pem - Base64 encoded public certificate only. Required by the client to connect to the server."
      puts "Certificate Thumbprint: #{@thumbprint.to_s.upcase}"
      puts "*" * 70

      Chef::Config[:knife][:ca_trust_file] = file_path + ".pem" if Chef::Config[:knife][:ca_trust_file].nil?
      cert_data = File.read (file_path + ".b64")
      add_certificate cert_data, @winrm_cert_passphrase, "pfx", cert_params[:azure_dns_name]
      @thumbprint
    end
1175085
private Collection<? extends java.security.cert.Certificate>
        parseX509orPKCS7Cert(InputStream is)
        throws CertificateException, IOException
    {
        Collection<X509CertImpl> coll = new ArrayList<>();
        byte[] data = readOneBlock(is);
        if (data == null) {
            return new ArrayList<>(0);
        }
        try {
            PKCS7 pkcs7 = new PKCS7(data);
            X509Certificate[] certs = pkcs7.getCertificates();
            // certs are optional in PKCS #7
            if (certs != null) {
                return Arrays.asList(certs);
            } else {
                // no crls provided
                return new ArrayList<>(0);
            }
        } catch (ParsingException e) {
            while (data != null) {
                coll.add(new X509CertImpl(data));
                data = readOneBlock(is);
            }
        }
        return coll;
    }
590949
protected function generateSecurity()
    {
        $securitySystemNode = $this->xpath->query('/x:webspace/x:security/x:system');
        if ($securitySystemNode->length > 0) {
            $security = new Security();
            $security->setSystem($securitySystemNode->item(0)->nodeValue);
            $this->webspace->setSecurity($security);
        }
    }
1074176
def generate_certificate_pure_python(common_name, size=DEFAULT_KEY_SIZE,
                                        digest=DEFAULT_DIGEST):
    '''
        
    '''
    private_key = OpenSSL.crypto.PKey()
    private_key.generate_key(TYPE_RSA, size)

    request = OpenSSL.crypto.X509Req()
    subject = request.get_subject()
    setattr(subject, 'CN', common_name)
    request.set_pubkey(private_key)
    request.sign(private_key, digest)

    certificate = OpenSSL.crypto.X509()
    certificate.set_serial_number(0)
    certificate.gmtime_adj_notBefore(0)
    certificate.gmtime_adj_notAfter(60 * 60 * 24 * 365 * 5)
    certificate.set_issuer(request.get_subject())
    certificate.set_subject(request.get_subject())
    certificate.set_pubkey(request.get_pubkey())
    certificate.sign(private_key, digest)

    private_key_path = '{}/{}.key'.format(CERTIFICATES_PATH, common_name)
    if not os.path.isfile(private_key_path):
        print 'Write {}'.format(private_key_path)
        with open(private_key_path, 'w+') as private_key_file:
            private_key_file.write(
                OpenSSL.crypto.dump_privatekey(FILETYPE_PEM,
                                               private_key).decode('utf-8')
            )
        helpers.file_rights(private_key_path, mode=0400, uid=0, gid=0)
    else:
        print 'Already exist: {}'.format(private_key_path)

    certificate_path = '{}/{}.crt'.format(CERTIFICATES_PATH, common_name)
    if not os.path.isfile(certificate_path):
        print 'Write {}'.format(certificate_path)
        with open(certificate_path, 'w+') as certificate_file:
            certificate_file.write(
                OpenSSL.crypto.dump_certificate(FILETYPE_PEM,
                                                certificate).decode('utf-8')
            )
        helpers.file_rights(certificate_path, mode=0444, uid=0, gid=0)
    else:
        print 'Already exist: {}'.format(certificate_path)

    clean_links()
    make_links(common_name)
1016954
private static ByteBuf append(ByteBufAllocator allocator, boolean useDirect,
            X509Certificate cert, int count, ByteBuf pem) throws CertificateEncodingException {

        ByteBuf encoded = Unpooled.wrappedBuffer(cert.getEncoded());
        try {
            ByteBuf base64 = SslUtils.toBase64(allocator, encoded);
            try {
                if (pem == null) {
                    // We try to approximate the buffer's initial size. The sizes of
                    // certificates can vary a lot so it'll be off a bit depending
                    // on the number of elements in the array (count argument).
                    pem = newBuffer(allocator, useDirect,
                            (BEGIN_CERT.length + base64.readableBytes() + END_CERT.length) * count);
                }

                pem.writeBytes(BEGIN_CERT);
                pem.writeBytes(base64);
                pem.writeBytes(END_CERT);
            } finally {
                base64.release();
            }
        } finally {
            encoded.release();
        }

        return pem;
    }
32144
public X509Credential createCredential(X509Certificate[] certs, PrivateKey privateKey, int bits, int lifetime,
       GSIConstants.DelegationType delegType, X509ExtensionSet extSet, String cnValue) throws GeneralSecurityException {

        X509Certificate[] bcCerts = getX509CertificateObjectChain(certs);

        return createCredential(bcCerts, privateKey, bits, lifetime, decideProxyType(bcCerts[0], delegType), extSet, cnValue);
    }
1007036
def save(self, x509):
        """"""

        self.x509 = x509
        with open_tls_file(self.file_path, 'w',
                           private=self.is_private()) as fh:
            fh.write(str(self))
144621
public static PKIXCertPathBuilderResult verifyChain(X509Certificate testCert, X509Certificate... additionalCerts) {
        try {
            // Check for self-signed certificate
            if (isSelfSigned(testCert)) {
                throw new RuntimeException("The certificate is self-signed.  Nothing to verify.");
            }

            // Prepare a set of all certificates
            // chain builder must have all certs, including cert to validate
            // http://stackoverflow.com/a/10788392
            Set<X509Certificate> certs = new HashSet<X509Certificate>();
            certs.add(testCert);
            certs.addAll(Arrays.asList(additionalCerts));

            // Attempt to build the certification chain and verify it
            // Create the selector that specifies the starting certificate
            X509CertSelector selector = new X509CertSelector();
            selector.setCertificate(testCert);

            // Create the trust anchors (set of root CA certificates)
            Set<TrustAnchor> trustAnchors = new HashSet<TrustAnchor>();
            for (X509Certificate cert : additionalCerts) {
                if (isSelfSigned(cert)) {
                    trustAnchors.add(new TrustAnchor(cert, null));
                }
            }

            // Configure the PKIX certificate builder
            PKIXBuilderParameters pkixParams = new PKIXBuilderParameters(trustAnchors, selector);
            pkixParams.setRevocationEnabled(false);
            pkixParams.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(certs), BC));

            // Build and verify the certification chain
            CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", BC);
            PKIXCertPathBuilderResult verifiedCertChain = (PKIXCertPathBuilderResult) builder.build(pkixParams);

            // The chain is built and verified
            return verifiedCertChain;
        } catch (CertPathBuilderException e) {
            throw new RuntimeException("Error building certification path: " + testCert.getSubjectX500Principal(), e);
        } catch (Exception e) {
            throw new RuntimeException("Error verifying the certificate: " + testCert.getSubjectX500Principal(), e);
        }
    }
506240
function generateSetupToken (tokenPath) {
  mkdirp.sync(path.dirname(tokenPath))

  var token = crypto.randomBytes(256).toString('hex')
  try {
    fs.writeFileSync(tokenPath, token, 'utf8')
  } catch (e) {
    throw new Error('Unable to save setup token to ' + tokenPath)
  }
  return token
}
776305
def create_ipsecpolicy(self, name, **kwargs):
        '''
        
        '''
        body = {'name': name}
        if 'transform_protocol' in kwargs:
            body['transform_protocol'] = kwargs['transform_protocol']
        if 'auth_algorithm' in kwargs:
            body['auth_algorithm'] = kwargs['auth_algorithm']
        if 'encapsulation_mode' in kwargs:
            body['encapsulation_mode'] = kwargs['encapsulation_mode']
        if 'encryption_algorithm' in kwargs:
            body['encryption_algorithm'] = kwargs['encryption_algorithm']
        if 'pfs' in kwargs:
            body['pfs'] = kwargs['pfs']
        if 'units' in kwargs:
            body['lifetime'] = {'units': kwargs['units']}
        if 'value' in kwargs:
            if 'lifetime' not in body:
                body['lifetime'] = {}
            body['lifetime']['value'] = kwargs['value']
        return self.network_conn.create_ipsecpolicy(body={'ipsecpolicy': body})
178983
public static X509Certificate newClientCertificate(X509Metadata clientMetadata,
                                                       PrivateKey caPrivateKey, X509Certificate caCert, File targetFolder) {
        try {
            KeyPair pair = newKeyPair();

            X500Name userDN = buildDistinguishedName(clientMetadata);
            X500Name issuerDN = new X500Name(PrincipalUtil.getIssuerX509Principal(caCert).getName());

            // create a new certificate signed by the Fathom CA certificate
            X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(
                    issuerDN,
                    BigInteger.valueOf(System.currentTimeMillis()),
                    clientMetadata.notBefore,
                    clientMetadata.notAfter,
                    userDN,
                    pair.getPublic());

            JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
            certBuilder.addExtension(X509Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(pair.getPublic()));
            certBuilder.addExtension(X509Extension.basicConstraints, false, new BasicConstraints(false));
            certBuilder.addExtension(X509Extension.authorityKeyIdentifier, false, extUtils.createAuthorityKeyIdentifier(caCert.getPublicKey()));
            certBuilder.addExtension(X509Extension.keyUsage, true, new KeyUsage(KeyUsage.keyEncipherment | KeyUsage.digitalSignature));
            if (!Strings.isNullOrEmpty(clientMetadata.emailAddress)) {
                GeneralNames subjectAltName = new GeneralNames(
                        new GeneralName(GeneralName.rfc822Name, clientMetadata.emailAddress));
                certBuilder.addExtension(X509Extension.subjectAlternativeName, false, subjectAltName);
            }

            ContentSigner signer = new JcaContentSignerBuilder(SIGNING_ALGORITHM).setProvider(BC).build(caPrivateKey);

            X509Certificate userCert = new JcaX509CertificateConverter().setProvider(BC).getCertificate(certBuilder.build(signer));
            PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) pair.getPrivate();
            bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
                    extUtils.createSubjectKeyIdentifier(pair.getPublic()));

            // confirm the validity of the user certificate
            userCert.checkValidity();
            userCert.verify(caCert.getPublicKey());
            userCert.getIssuerDN().equals(caCert.getSubjectDN());

            // verify user certificate chain
            verifyChain(userCert, caCert);

            targetFolder.mkdirs();

            // save certificate, stamped with unique name
            String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
            String id = date;
            File certFile = new File(targetFolder, id + ".cer");
            int count = 0;
            while (certFile.exists()) {
                id = date + "_" + Character.toString((char) (0x61 + count));
                certFile = new File(targetFolder, id + ".cer");
                count++;
            }

            // save user private key, user certificate and CA certificate to a PKCS#12 store
            File p12File = new File(targetFolder, clientMetadata.commonName + ".p12");
            if (p12File.exists()) {
                p12File.delete();
            }
            KeyStore userStore = openKeyStore(p12File, clientMetadata.password);
            userStore.setKeyEntry(MessageFormat.format("Fathom ({0}) {1} {2}", clientMetadata.serverHostname, clientMetadata.userDisplayname, id), pair.getPrivate(), null, new Certificate[]{userCert});
            userStore.setCertificateEntry(MessageFormat.format("Fathom ({0}) Certificate Authority", clientMetadata.serverHostname), caCert);
            saveKeyStore(p12File, userStore, clientMetadata.password);

            // save user private key, user certificate, and CA certificate to a PEM store
            File pemFile = new File(targetFolder, clientMetadata.commonName + ".pem");
            if (pemFile.exists()) {
                pemFile.delete();
            }
            PEMWriter pemWriter = new PEMWriter(new FileWriter(pemFile));
            pemWriter.writeObject(pair.getPrivate(), "DES-EDE3-CBC", clientMetadata.password.toCharArray(), new SecureRandom());
            pemWriter.writeObject(userCert);
            pemWriter.writeObject(caCert);
            pemWriter.flush();
            pemWriter.close();

            // save certificate after successfully creating the key stores
            saveCertificate(userCert, certFile);

            // update serial number in metadata object
            clientMetadata.serialNumber = userCert.getSerialNumber().toString();

            return userCert;
        } catch (Throwable t) {
            throw new RuntimeException("Failed to generate client certificate!", t);
        }
    }