private X509Certificate generateCertificate(final KeyPair keypair) throws Exception {
        val dn = new X500Name("CN=" + hostname);
        val notBefore = new GregorianCalendar();
        val notOnOrAfter = new GregorianCalendar();
        notOnOrAfter.set(Calendar.YEAR, notOnOrAfter.get(Calendar.YEAR) + certificateLifetimeInYears);

        val builder = new JcaX509v3CertificateBuilder(
            dn,
            new BigInteger(X509_CERT_BITS_SIZE, RandomUtils.getNativeInstance()),
            notBefore.getTime(),
            notOnOrAfter.getTime(),
            dn,
            keypair.getPublic()
        );

        val extUtils = new JcaX509ExtensionUtils();
        builder.addExtension(Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(keypair.getPublic()));
        builder.addExtension(Extension.subjectAlternativeName, false, GeneralNames.getInstance(new DERSequence(buildSubjectAltNames())));

        val certHldr = builder.build(new JcaContentSignerBuilder(certificateAlgorithm).build(keypair.getPrivate()));
        val cert = new JcaX509CertificateConverter().getCertificate(certHldr);
        cert.checkValidity(new Date());
        cert.verify(keypair.getPublic());

        return cert;
    }
This is {@link DefaultSamlIdPCertificateAndKeyWriter}.

@author Misagh Moayyed
@since 5.3.0
support/cas-server-support-saml-idp-core/src/main/java/org/apereo/cas/support/saml/idp/metadata/writer/DefaultSamlIdPCertificateAndKeyWriter.java