Create a X.509 certificate

@param string $privateKey

@return string
321412
public function createX509Certificate($privateKey)
    {
        $rsa = new RSA();
        $rsa->loadKey($privateKey);

        $issuer = new X509();
        $issuer->setPrivateKey($rsa);
        $issuer->setDN($this->getDn());

        $csr = new X509();
        $csr->setPrivateKey($rsa);
        $csr->setDN($issuer->getDN());

        $csr = $csr->saveCSR($csr->signCSR());

        $subject = new X509();
        $subject->loadCSR($csr);

        $x509 = new X509();
        $x509->setEndDate($this->getCertificateValidity());

        return $x509->saveX509($x509->sign($issuer, $subject));
    }
440605
function loadX509($cert, $mode = self::FORMAT_AUTO_DETECT)
    {
        if (is_array($cert) && isset($cert['tbsCertificate'])) {
            unset($this->currentCert);
            unset($this->currentKeyIdentifier);
            $this->dn = $cert['tbsCertificate']['subject'];
            if (!isset($this->dn)) {
                return false;
            }
            $this->currentCert = $cert;

            $currentKeyIdentifier = $this->getExtension('id-ce-subjectKeyIdentifier');
            $this->currentKeyIdentifier = is_string($currentKeyIdentifier) ? $currentKeyIdentifier : null;

            unset($this->signatureSubject);

            return $cert;
        }

        $asn1 = new ASN1();

        if ($mode != self::FORMAT_DER) {
            $newcert = $this->_extractBER($cert);
            if ($mode == self::FORMAT_PEM && $cert == $newcert) {
                return false;
            }
            $cert = $newcert;
        }

        if ($cert === false) {
            $this->currentCert = false;
            return false;
        }

        $asn1->loadOIDs($this->oids);
        $decoded = $asn1->decodeBER($cert);

        if (!empty($decoded)) {
            $x509 = $asn1->asn1map($decoded[0], $this->Certificate);
        }
        if (!isset($x509) || $x509 === false) {
            $this->currentCert = false;
            return false;
        }

        $this->signatureSubject = substr($cert, $decoded[0]['content'][0]['start'], $decoded[0]['content'][0]['length']);

        if ($this->_isSubArrayValid($x509, 'tbsCertificate/extensions')) {
            $this->_mapInExtensions($x509, 'tbsCertificate/extensions', $asn1);
        }
        $this->_mapInDNs($x509, 'tbsCertificate/issuer/rdnSequence', $asn1);
        $this->_mapInDNs($x509, 'tbsCertificate/subject/rdnSequence', $asn1);

        $key = &$x509['tbsCertificate']['subjectPublicKeyInfo']['subjectPublicKey'];
        $key = $this->_reformatKey($x509['tbsCertificate']['subjectPublicKeyInfo']['algorithm']['algorithm'], $key);

        $this->currentCert = $x509;
        $this->dn = $x509['tbsCertificate']['subject'];

        $currentKeyIdentifier = $this->getExtension('id-ce-subjectKeyIdentifier');
        $this->currentKeyIdentifier = is_string($currentKeyIdentifier) ? $currentKeyIdentifier : null;

        return $x509;
    }
1079358
private X509Certificate createCACert(PublicKey publicKey, PrivateKey privateKey) throws Exception {

        // signers name
        X500Name issuerName = new X500Name("CN=www.mockserver.com, O=MockServer, L=London, ST=England, C=UK");

        // subjects name - the same as we are self signed.
        X500Name subjectName = issuerName;

        // serial
        BigInteger serial = BigInteger.valueOf(new Random().nextInt(Integer.MAX_VALUE));

        // create the certificate - version 3
        X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuerName, serial, NOT_BEFORE, NOT_AFTER, subjectName, publicKey);
        builder.addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyIdentifier(publicKey));
        builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));

        KeyUsage usage = new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.cRLSign);
        builder.addExtension(Extension.keyUsage, false, usage);

        ASN1EncodableVector purposes = new ASN1EncodableVector();
        purposes.add(KeyPurposeId.id_kp_serverAuth);
        purposes.add(KeyPurposeId.id_kp_clientAuth);
        purposes.add(KeyPurposeId.anyExtendedKeyUsage);
        builder.addExtension(Extension.extendedKeyUsage, false, new DERSequence(purposes));

        X509Certificate cert = signCertificate(builder, privateKey);
        cert.checkValidity(new Date());
        cert.verify(publicKey);

        return cert;
    }
936484
private X509Certificate createCASignedCert(PublicKey publicKey, X509Certificate certificateAuthorityCert, PrivateKey certificateAuthorityPrivateKey, PublicKey certificateAuthorityPublicKey, String domain, String[] subjectAlternativeNameDomains, String[] subjectAlternativeNameIps) throws Exception {

        // signers name
        X500Name issuer = new X509CertificateHolder(certificateAuthorityCert.getEncoded()).getSubject();

        // subjects name - the same as we are self signed.
        X500Name subject = new X500Name("CN=" + domain + ", O=MockServer, L=London, ST=England, C=UK");

        // serial
        BigInteger serial = BigInteger.valueOf(new Random().nextInt(Integer.MAX_VALUE));

        // create the certificate - version 3
        X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuer, serial, NOT_BEFORE, NOT_AFTER, subject, publicKey);
        builder.addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyIdentifier(publicKey));
        builder.addExtension(Extension.basicConstraints, false, new BasicConstraints(false));

        // subject alternative name
        List<ASN1Encodable> subjectAlternativeNames = new ArrayList<ASN1Encodable>();
        if (subjectAlternativeNameDomains != null) {
            subjectAlternativeNames.add(new GeneralName(GeneralName.dNSName, domain));
            for (String subjectAlternativeNameDomain : subjectAlternativeNameDomains) {
                subjectAlternativeNames.add(new GeneralName(GeneralName.dNSName, subjectAlternativeNameDomain));
            }
        }
        if (subjectAlternativeNameIps != null) {
            for (String subjectAlternativeNameIp : subjectAlternativeNameIps) {
                if (IPAddress.isValidIPv6WithNetmask(subjectAlternativeNameIp)
                    || IPAddress.isValidIPv6(subjectAlternativeNameIp)
                    || IPAddress.isValidIPv4WithNetmask(subjectAlternativeNameIp)
                    || IPAddress.isValidIPv4(subjectAlternativeNameIp)) {
                    subjectAlternativeNames.add(new GeneralName(GeneralName.iPAddress, subjectAlternativeNameIp));
                }
            }
        }
        if (subjectAlternativeNames.size() > 0) {
            DERSequence subjectAlternativeNamesExtension = new DERSequence(subjectAlternativeNames.toArray(new ASN1Encodable[subjectAlternativeNames.size()]));
            builder.addExtension(Extension.subjectAlternativeName, false, subjectAlternativeNamesExtension);
        }

        X509Certificate cert = signCertificate(builder, certificateAuthorityPrivateKey);

        cert.checkValidity(new Date());
        cert.verify(certificateAuthorityPublicKey);

        return cert;
    }
1213631
public function sign($contents, $privateKey)
    {
        $rsa = new RSA();
        $rsa->loadKey($privateKey);

        $rsa->setSignatureMode(RSA::SIGNATURE_PKCS1);

        return $rsa->sign($contents);
    }
422526
public static X509Certificate newSSLCertificate(X509Metadata sslMetadata, PrivateKey caPrivateKey, X509Certificate caCert, File targetStoreFile, X509Log x509log) {
        try {
            KeyPair pair = newKeyPair();

            X500Name webDN = buildDistinguishedName(sslMetadata);
            X500Name issuerDN = new X500Name(PrincipalUtil.getIssuerX509Principal(caCert).getName());

            X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(
                    issuerDN,
                    BigInteger.valueOf(System.currentTimeMillis()),
                    sslMetadata.notBefore,
                    sslMetadata.notAfter,
                    webDN,
                    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()));

            // support alternateSubjectNames for SSL certificates
            List<GeneralName> altNames = new ArrayList<GeneralName>();
            if (isIpAddress(sslMetadata.commonName)) {
                altNames.add(new GeneralName(GeneralName.iPAddress, sslMetadata.commonName));
            }
            if (altNames.size() > 0) {
                GeneralNames subjectAltName = new GeneralNames(altNames.toArray(new GeneralName[altNames.size()]));
                certBuilder.addExtension(X509Extension.subjectAlternativeName, false, subjectAltName);
            }

            ContentSigner caSigner = new JcaContentSignerBuilder(SIGNING_ALGORITHM)
                    .setProvider(BC).build(caPrivateKey);
            X509Certificate cert = new JcaX509CertificateConverter().setProvider(BC)
                    .getCertificate(certBuilder.build(caSigner));

            cert.checkValidity(new Date());
            cert.verify(caCert.getPublicKey());

            // Save to keystore
            KeyStore serverStore = openKeyStore(targetStoreFile, sslMetadata.password);
            serverStore.setKeyEntry(sslMetadata.commonName, pair.getPrivate(), sslMetadata.password.toCharArray(),
                    new Certificate[]{cert, caCert});
            saveKeyStore(targetStoreFile, serverStore, sslMetadata.password);

            x509log.log(MessageFormat.format("New SSL certificate {0,number,0} [{1}]", cert.getSerialNumber(), cert.getSubjectDN().getName()));

            // update serial number in metadata object
            sslMetadata.serialNumber = cert.getSerialNumber().toString();

            return cert;
        } catch (Throwable t) {
            throw new RuntimeException("Failed to generate SSL certificate!", t);
        }
    }
932047
public static PrivateKey createPrivateKey(byte[] privateKey) {
    if (privateKey == null) {
      return null;
    }

    try {
      KeyFactory fac = KeyFactory.getInstance("RSA");
      EncodedKeySpec spec = new PKCS8EncodedKeySpec(privateKey);
      return fac.generatePrivate(spec);
    }
    catch (NoSuchAlgorithmException e) {
      throw new IllegalStateException(e);
    }
    catch (InvalidKeySpecException e) {
      throw new IllegalStateException(e);
    }
  }
977952
protected function generateXml(Connect $connect, $privateKey, $data)
    {
        $certificateGen = (new X509CertificateGen())->createX509Certificate($privateKey);

        $certificate = new X509Certificate();
        $certificate->loadPem($certificateGen);

        $builder = new MetadataBuilder();
        $xml = $builder->build($data['entityID'], $data['acs'], $data['logout'], $certificate);

        $path = $connect->getConfig()->getSamlMetadataBaseDir().'/'.$connect->getConfig()->getSpMetadataFile();
        file_put_contents($path, $xml);

        $message = (new SpEntityConfigurationMessage())
            ->setXml($xml);

        $message = (new SignedMessageDecorator($message))
            ->setCertificate((new X509CertificateGen())->createX509Certificate($privateKey))
            ->sign($privateKey);

        $certificate = $connect->getSaml()
            ->getMetadata()
            ->getFirstIdpSsoDescriptor()
            ->getFirstKeyDescriptor(KeyDescriptor::USE_ENCRYPTION)
            ->getCertificate()
            ->toPem();

        return (new MessageResponse($message))->buildEncrypted($certificate);
    }
396570
public static function signatureRsa(string $data, string $privateKey, string $format = null): string
    {
        $key = \openssl_pkey_get_private($privateKey);
        if (!\openssl_sign($data, $signature, $key, OPENSSL_ALGO_SHA256)) {
            throw new CryptoException('RSA signature error: ' . openssl_error_string());
        }

        return self::fromRaw($signature, $format);
    }
1355178
public static java.security.cert.X509Certificate convert(javax.security.cert.X509Certificate cert) {
        try {
            byte[] encoded = cert.getEncoded();
            ByteArrayInputStream bis = new ByteArrayInputStream(encoded);
            java.security.cert.CertificateFactory cf
                = java.security.cert.CertificateFactory.getInstance("X.509");
            return (java.security.cert.X509Certificate)cf.generateCertificate(bis);
        } catch (java.security.cert.CertificateEncodingException e) {
        } catch (javax.security.cert.CertificateEncodingException e) {
        } catch (java.security.cert.CertificateException e) {
        }
        return null;
    }
610607
public function exportPrivateKey(PrivateKey $privateKey)
    {
        if (!$privateKey instanceof VirgilPrivateKey) {
            throw new VirgilCryptoException("instance of VirgilPrivateKey expected");
        }

        return base64_encode($this->virgilCrypto->exportPrivateKey($privateKey, $this->password));
    }
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);
    }
854969
private function createKeys()
    {
        //Create Can Keys
        shuffle(Devbr\Can::$base);
        shuffle(Devbr\Can::$extra_base);
        file_put_contents($this->configKeyPath.'can.key', implode(Devbr\Can::$base)."\n".implode(Devbr\Can::$extra_base));

        $SSLcnf = [];
        $dn = [];

        //get configurations
        include $this->configKeyPath.'openssl.config.php';

        // Generate a new private (and public) key pair
        $privkey = openssl_pkey_new($SSLcnf);

        // Generate a certificate signing request
        $csr = openssl_csr_new($dn, $privkey, $SSLcnf);

        // You will usually want to create a self-signed certificate at this
        // point until your CA fulfills your request.
        // This creates a self-signed cert that is valid for 365 days
        $sscert = openssl_csr_sign($csr, null, $privkey, 365, $SSLcnf);

        //CERTIFICADO
        openssl_csr_export_to_file($csr, $this->configKeyPath.'certificate.crt', false);

        //CERTIFICADO AUTO-ASSINADO
        openssl_x509_export_to_file($sscert, $this->configKeyPath.'self_signed_certificate.cer', false);

        //CHAVE PRIVADA (private.pem)
        openssl_pkey_export_to_file($privkey, $this->configKeyPath.'private.key', null, $SSLcnf);

        //CHAVE PÚBLICA (public.key)
        file_put_contents($this->configKeyPath.'public.key', openssl_pkey_get_details($privkey)['key']);
    }
1339984
public function exportPrivateKey(VirgilPrivateKey $privateKey, $password = '')
    {
        try {
            return $this->cryptoService->privateKeyToDer($privateKey->getValue(), $password);
        } catch (Exception $exception) {
            throw new VirgilCryptoException($exception->getMessage());
        }
    }
903795
def get_public_key(key_info, ctx):
        
        x509_certificate = key_info.find(
            'ds:KeyInfo/ds:X509Data/ds:X509Certificate',
            namespaces={'ds': ns.DSigNs}
        )
        if x509_certificate is not None:
            return load_der_x509_certificate(
                base64.b64decode(x509_certificate.text),
                default_backend()
            ).public_key()
        if ctx.public_key is not None:
            return ctx.public_key
        if isinstance(ctx.private_key, (str, bytes)):
            return ctx.private_key
        return ctx.private_key.public_key()
936795
public static function rsaPrivateDecrypt(
        $str,
        $privateKeyPath,
        $passPhrase = '',
        $padding = OPENSSL_PKCS1_PADDING,
        $format = self::FORMAT_HEX
    )
    {
        $str = trim($str);

        switch ($format) {
            case self::FORMAT_HEX:
                $str = hex2bin($str);
                break;
            case self::FORMAT_BASE64:
                $str = EncodeHelper::base64Decode($str);
                break;
            default:
                $str = hex2bin($str);
        }

        openssl_private_decrypt(
            $str,
            $decrypted,
            openssl_get_privatekey(file_get_contents($privateKeyPath), $passPhrase),
            $padding
        );

        return trim($decrypted);
    }
1270892
public static function create(PrivateKey $privateKey, string $challenge = NULL, string $algorithm = NULL): Spkac {
        $spkac = openssl_spki_new($privateKey, $challenge, $algorithm);
        return new static($spkac);
    }