private X509Certificate createSelfSignedCert(final X500Name dn, final String sigName,
                                                 final AlgorithmIdentifier sigAlgID,
                                                 final KeyPair keyPair) throws Exception {
        val certGen = new V3TBSCertificateGenerator();

        certGen.setSerialNumber(new ASN1Integer(BigInteger.valueOf(1)));
        certGen.setIssuer(dn);
        certGen.setSubject(dn);

        val startDate = LocalDateTime.now(Clock.systemUTC()).minusSeconds(1);
        certGen.setStartDate(time(startDate));

        val endDate = startDate.plus(saml2Configuration.getCertificateExpirationPeriod());
        certGen.setEndDate(time(endDate));

        certGen.setSignature(sigAlgID);
        certGen.setSubjectPublicKeyInfo(SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()));

        val sig = Signature.getInstance(sigName);

        sig.initSign(keyPair.getPrivate());

        sig.update(certGen.generateTBSCertificate().getEncoded(ASN1Encoding.DER));

        val tbsCert = certGen.generateTBSCertificate();

        val v = new ASN1EncodableVector();

        v.add(tbsCert);
        v.add(sigAlgID);
        v.add(new DERBitString(sig.sign()));

        val cert = (X509Certificate) CertificateFactory.getInstance("X.509")
            .generateCertificate(new ByteArrayInputStream(new DERSequence(v).getEncoded(ASN1Encoding.DER)));

        // check the certificate - this will confirm the encoded sig algorithm ID is correct.
        cert.verify(keyPair.getPublic());

        return cert;
    }
Generate a self-signed certificate for dn using the provided signature algorithm and key pair.

@param dn       X.500 name to associate with certificate issuer/subject.
@param sigName  name of the signature algorithm to use.
@param sigAlgID algorithm ID associated with the signature algorithm name.
@param keyPair  the key pair to associate with the certificate.
@return an X509Certificate containing the public key in keyPair.
@throws Exception
pac4j-saml/src/main/java/org/pac4j/saml/metadata/keystore/BaseSAML2KeystoreGenerator.java