Example usage for org.bouncycastle.operator.jcajce JcaContentSignerBuilder JcaContentSignerBuilder

List of usage examples for org.bouncycastle.operator.jcajce JcaContentSignerBuilder JcaContentSignerBuilder

Introduction

In this page you can find the example usage for org.bouncycastle.operator.jcajce JcaContentSignerBuilder JcaContentSignerBuilder.

Prototype

public JcaContentSignerBuilder(String signatureAlgorithm) 

Source Link

Usage

From source file:org.opendaylight.snbi.southplugin.CertificateMgmt.java

License:Open Source License

public static byte[] sign(Certificate cert, KeyPair pair) {
    ContentSigner signGen = null;//from  w  w w  .j  a  va2 s.c om
    X509CertificateHolder certHolder = new X509CertificateHolder(cert);

    try {
        signGen = new JcaContentSignerBuilder(CertManagerConstants.CERT_ALGORITHM.SHA1withRSA.toString())
                .setProvider(CertManagerConstants.BC).build(pair.getPrivate());
    } catch (OperatorCreationException e) {
        e.printStackTrace();
        return null;
    }
    CMSSignedDataGenerator gen = new CMSSignedDataGenerator();

    try {
        gen.addSignerInfoGenerator(
                new SignerInfoGeneratorBuilder(new BcDigestCalculatorProvider()).build(signGen, certHolder));
    } catch (OperatorCreationException e) {
        e.printStackTrace();
        return null;
    }
    return certHolder.getSignature();
}

From source file:org.opendaylight.snbi.southplugin.SNBICAInterfaces.java

License:Open Source License

public PKCS10CertificationRequest generateCSRRequest(String... arguments) {
    X500NameBuilder builder = new X500NameBuilder(BCStyle.INSTANCE);
    builder.addRDN(BCStyle.CN, arguments[0]); // common name, is the Device ID
    builder.addRDN(BCStyle.OU, arguments[1]); //  organisational unit is the Domain ID
    builder.addRDN(BCStyle.SN, arguments[2]); // serial number of the SubjectDN not the certificate Serial Number.
    // other defaults
    // builder.addRDN(BCStyle.C, CertificateMgmt.defaults.get("COUNTRY"));
    //builder.addRDN(BCStyle.ST, CertificateMgmt.defaults.get("STATE"));
    // builder.addRDN(BCStyle.T, CertificateMgmt.defaults.get("TITLE"));

    //generate key pair
    KeyPair keyPair = KeyPairMgmt.generateKeyPair(CertManagerConstants.ALGORITHM.RSA);

    JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder(
            CertManagerConstants.CERT_ALGORITHM.SHA1withRSA.toString());
    ContentSigner signer = null;//from   w  ww. j av  a 2s  . c o m
    try {
        signer = csBuilder.build(keyPair.getPrivate());
    } catch (OperatorCreationException e) {
        e.printStackTrace();
        return null;
    }
    PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder(builder.build(),
            keyPair.getPublic());

    PKCS10CertificationRequest csr = p10Builder.build(signer);
    return csr;
}

From source file:org.opendaylight.snbi.southplugin.SNBICAInterfaces.java

License:Open Source License

public X509Certificate generateX509Certificate(PKCS10CertificationRequest request, ContentSigner signer) {
    X509Certificate rootCert = CertificateMgmt.getSavedCertificate(CertManagerConstants.BC,
            CertManagerConstants.SELF_SIGNED_CERT_FILE);
    KeyPair rootPair = KeyPairMgmt.getKeyPairFromStore(CertManagerConstants.KEY_STORE_ALIAS,
            CertManagerConstants.KEY_STORE_CERT_ALIAS, CertManagerConstants.STORE_TYPE.JKS);

    // X500Name x500Name = request.getSubject();
    // RDN cn = x500Name.getRDNs(BCStyle.SN)[0];
    // AttributeTypeAndValue[] values = cn.getTypesAndValues();
    //BigInteger serial = BigInteger.valueOf(new Long(values[0].getValue().toString()).longValue());
    BigInteger serial = BigInteger.valueOf(System.currentTimeMillis());
    Calendar now = Calendar.getInstance();
    now.add(Calendar.YEAR, -1);//  w w  w. j  av a  2s.  c  o  m
    Date notBefore = now.getTime();
    now.add(Calendar.YEAR, 4);
    Date notAfter = now.getTime();
    org.bouncycastle.asn1.x500.X500Name issuername = JcaX500NameUtil.getSubject(rootCert);
    JcaPKCS10CertificationRequest jpkcsreq = new JcaPKCS10CertificationRequest(request);
    X509v3CertificateBuilder certGen;
    try {
        certGen = new JcaX509v3CertificateBuilder(issuername, serial, notBefore, notAfter, request.getSubject(),
                jpkcsreq.getPublicKey());
    } catch (InvalidKeyException | NoSuchAlgorithmException e1) {
        e1.printStackTrace();
        return null;
    }

    if (signer == null) {
        try {
            signer = new JcaContentSignerBuilder(CertManagerConstants.CERT_ALGORITHM.SHA1withRSA.toString())
                    .setProvider(CertManagerConstants.BC).build(rootPair.getPrivate());
        } catch (OperatorCreationException e) {
            e.printStackTrace();
            return null;
        }
    }
    try {
        X509Certificate issuedCert = new JcaX509CertificateConverter().setProvider(CertManagerConstants.BC)
                .getCertificate(certGen.build(signer));
        return issuedCert;
    } catch (CertificateException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:org.openfact.common.util.CertificateUtils.java

License:Apache License

/**
 * Generates version 3 {@link X509Certificate}.
 *
 * @param keyPair the key pair//from ww w . j av  a2  s .c  om
 * @param caPrivateKey the CA private key
 * @param caCert the CA certificate
 * @param subject the subject name
 *
 * @return the x509 certificate
 *
 * @throws Exception the exception
 */
public static X509Certificate generateV3Certificate(KeyPair keyPair, PrivateKey caPrivateKey,
        X509Certificate caCert, String subject) throws Exception {

    try {
        X500Name subjectDN = new X500Name("CN=" + subject);

        // Serial Number
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        BigInteger serialNumber = BigInteger.valueOf(Math.abs(random.nextInt()));

        // Validity
        Date notBefore = new Date(System.currentTimeMillis());
        Date notAfter = new Date(System.currentTimeMillis() + (((1000L * 60 * 60 * 24 * 30)) * 12) * 3);

        // SubjectPublicKeyInfo
        SubjectPublicKeyInfo subjPubKeyInfo = new SubjectPublicKeyInfo(
                ASN1Sequence.getInstance(keyPair.getPublic().getEncoded()));

        X509v3CertificateBuilder certGen = new X509v3CertificateBuilder(
                new X500Name(caCert.getSubjectDN().getName()), serialNumber, notBefore, notAfter, subjectDN,
                subjPubKeyInfo);

        DigestCalculator digCalc = new BcDigestCalculatorProvider()
                .get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1));
        X509ExtensionUtils x509ExtensionUtils = new X509ExtensionUtils(digCalc);

        // Subject Key Identifier
        certGen.addExtension(Extension.subjectKeyIdentifier, false,
                x509ExtensionUtils.createSubjectKeyIdentifier(subjPubKeyInfo));

        // Authority Key Identifier
        certGen.addExtension(Extension.authorityKeyIdentifier, false,
                x509ExtensionUtils.createAuthorityKeyIdentifier(subjPubKeyInfo));

        // Key Usage
        certGen.addExtension(Extension.keyUsage, false,
                new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign));

        // Extended Key Usage
        KeyPurposeId[] EKU = new KeyPurposeId[2];
        EKU[0] = KeyPurposeId.id_kp_emailProtection;
        EKU[1] = KeyPurposeId.id_kp_serverAuth;

        certGen.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(EKU));

        // Basic Constraints
        certGen.addExtension(Extension.basicConstraints, true, new BasicConstraints(0));

        // Content Signer
        ContentSigner sigGen = new JcaContentSignerBuilder("SHA1WithRSAEncryption").setProvider("BC")
                .build(caPrivateKey);

        // Certificate
        return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certGen.build(sigGen));
    } catch (Exception e) {
        throw new RuntimeException("Error creating X509v3Certificate.", e);
    }
}

From source file:org.openhab.io.jetty.certificate.internal.CertificateGenerator.java

License:Open Source License

/**
 * Generate a new certificate and store it in the given keystore.
 *
 * @param keystore/*  www . j av a2  s .  c  om*/
 * @throws CertificateException if the certificate generation has failed.
 * @throws KeyStoreException If save of the keystore has failed.
 */
private void generateCertificate(KeyStore keystore) throws CertificateException, KeyStoreException {
    try {
        long startTime = System.currentTimeMillis();
        org.bouncycastle.jce.spec.ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec(CURVE_NAME);
        ECField field = new ECFieldFp(ecSpec.getCurve().getField().getCharacteristic());
        EllipticCurve curve = new EllipticCurve(field, ecSpec.getCurve().getA().toBigInteger(),
                ecSpec.getCurve().getB().toBigInteger());
        ECPoint pointG = new ECPoint(ecSpec.getG().getXCoord().toBigInteger(),
                ecSpec.getG().getYCoord().toBigInteger());
        ECParameterSpec spec = new ECParameterSpec(curve, pointG, ecSpec.getN(), ecSpec.getH().intValue());
        KeyPairGenerator g = KeyPairGenerator.getInstance(KEY_PAIR_GENERATOR_TYPE);
        g.initialize(spec, new SecureRandom());
        KeyPair keysPair = g.generateKeyPair();

        ECPrivateKeySpec ecPrivSpec = new ECPrivateKeySpec(((ECPrivateKey) keysPair.getPrivate()).getS(), spec);
        ECPublicKeySpec ecPublicSpec = new ECPublicKeySpec(((ECPublicKey) keysPair.getPublic()).getW(), spec);
        KeyFactory kf = KeyFactory.getInstance(KEY_FACTORY_TYPE);
        PrivateKey privateKey = kf.generatePrivate(ecPrivSpec);
        PublicKey publicKey = kf.generatePublic(ecPublicSpec);

        logger.debug("Keys generated in {} ms.", (System.currentTimeMillis() - startTime));

        X500Name issuerDN = new X500Name(X500_NAME);
        Integer randomNumber = new Random().nextInt();
        BigInteger serialNumber = BigInteger.valueOf(randomNumber >= 0 ? randomNumber : randomNumber * -1);
        Date notBefore = new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30);
        Date notAfter = new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10));
        X500Name subjectDN = new X500Name(X500_NAME);
        byte[] publickeyb = publicKey.getEncoded();
        ASN1Sequence sequence = (ASN1Sequence) ASN1Primitive.fromByteArray(publickeyb);
        SubjectPublicKeyInfo subPubKeyInfo = new SubjectPublicKeyInfo(sequence);
        X509v3CertificateBuilder v3CertGen = new X509v3CertificateBuilder(issuerDN, serialNumber, notBefore,
                notAfter, subjectDN, subPubKeyInfo);

        ContentSigner contentSigner = new JcaContentSignerBuilder(CONTENT_SIGNER_ALGORITHM)
                .build(keysPair.getPrivate());
        X509CertificateHolder certificateHolder = v3CertGen.build(contentSigner);

        Certificate certificate = java.security.cert.CertificateFactory.getInstance(CERTIFICATE_X509_TYPE)
                .generateCertificate(new ByteArrayInputStream(
                        ByteBuffer.wrap(certificateHolder.toASN1Structure().getEncoded()).array()));

        logger.debug("Total certificate generation time: {} ms.", (System.currentTimeMillis() - startTime));

        keystore.setKeyEntry(KEYSTORE_ENTRY_ALIAS, privateKey, KEYSTORE_PASSWORD.toCharArray(),
                new java.security.cert.Certificate[] { certificate });

        logger.debug("Save the keystore into {}.", keystoreFile.getAbsolutePath());

        keystore.store(new FileOutputStream(keystoreFile), KEYSTORE_PASSWORD.toCharArray());

    } catch (NoSuchAlgorithmException | InvalidKeySpecException | IOException | OperatorCreationException
            | InvalidAlgorithmParameterException e) {
        throw new CertificateException("Failed to generate the new certificate.", e);
    }
}

From source file:org.openqa.selenium.security.CertificateGenerator.java

License:Apache License

public KeyAndCert generateCertificate(String hostname, String certificateRevocationList) {
    X500Principal x500issuer = caCert.getCertificate().getIssuerX500Principal();
    String subject = String.format("CN=%s, OU=Test, O=CyberVillainsCA, L=Seattle, S=Washington, C=US",
            hostname);/*from   w ww  .  j  a  va  2s  . co m*/
    X500Principal x500subject = new X500Principal(subject);

    Date begin = new Date(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(1));
    Date end = new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(365));

    KeyPair keypair = pairGenerator.generateKeyPair();

    try {
        SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(
                (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(keypair.getPublic().getEncoded()))
                        .readObject());

        X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(x500issuer,
                BigInteger.valueOf(serialSeed.getAndIncrement()), begin, end, x500subject, keypair.getPublic());
        builder.addExtension(X509Extension.basicConstraints, true, new BasicConstraints(false));
        builder.addExtension(X509Extension.subjectKeyIdentifier, false, info);

        AuthorityKeyIdentifier caIdentifier = new JcaX509ExtensionUtils()
                .createAuthorityKeyIdentifier(caCert.getCertificate());
        builder.addExtension(X509Extension.authorityKeyIdentifier, false, caIdentifier);

        DERSequence typicalSSLServerExtendedKeyUsages = new DERSequence(new ASN1Encodable[] {
                new DERObjectIdentifier(SERVER_AUTH), new DERObjectIdentifier(CLIENT_AUTH), });

        builder.addExtension(X509Extension.extendedKeyUsage, false, typicalSSLServerExtendedKeyUsages);

        if (certificateRevocationList != null) {
            /* Safari on Windows requires a CRL and validates it */
            DistributionPoint crl = new DistributionPoint(
                    new DistributionPointName(DistributionPointName.FULL_NAME,
                            new GeneralName(GeneralName.uniformResourceIdentifier, certificateRevocationList)),
                    null, null);
            builder.addExtension(X509Extension.cRLDistributionPoints, false,
                    new CRLDistPoint(new DistributionPoint[] { crl }));
        }

        ContentSigner signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(BOUNCY_CASTLE)
                .build(caCert.getPrivateKey());

        X509CertificateHolder holder = builder.build(signer);
        X509Certificate cert = new JcaX509CertificateConverter().setProvider(BOUNCY_CASTLE)
                .getCertificate(holder);

        return new KeyAndCert(keypair.getPrivate(), cert);
    } catch (GeneralSecurityException e) {
        throw Throwables.propagate(e);
    } catch (IOException e) {
        throw Throwables.propagate(e);
    } catch (OperatorCreationException e) {
        throw Throwables.propagate(e);
    }
}

From source file:org.openremote.security.provider.BouncyCastleKeySigner.java

License:Open Source License

/**
 * Creates a BouncyCastle content signer that we can use to sign the X.509 certificate
 * information.//from   w w w . j  a  v a2 s  .c  o  m
 *
 * @param config
 *          configuration instance containing the signature algorithm and the private
 *          singing key used in signing the public key
 *
 * @return
 *          BouncyCastle content signer instance
 *
 * @throws  SigningException
 *            if building the BouncyCastle content signer instance fails
 */
private ContentSigner createContentSigner(Configuration config) throws SigningException {
    // BouncyCastle API to create a content signer for the certificate...

    JcaContentSignerBuilder contentSignerBuilder = new JcaContentSignerBuilder(
            config.getSignatureAlgorithm().toString());

    // Explicitly set the security provider as BouncyCastle. The BC provider is dynamically
    // loaded into the JVM if necessary...

    contentSignerBuilder.setProvider(SecurityProvider.BC.getProviderInstance());

    // Sign the public key...

    try {
        return contentSignerBuilder.build(config.getPrivateSigningKey());
    }

    catch (OperatorCreationException exception) {
        throw new SigningException("Unable to sign the certificate with the given private key : {0}", exception,
                exception.getMessage());
    }
}

From source file:org.owasp.webscarab.util.SunCertificateUtils.java

License:Open Source License

public static X509Certificate sign(X500Principal subject, PublicKey pubKey, X500Principal issuer,
        PublicKey caPubKey, PrivateKey caKey, Date begin, Date ends, BigInteger serialNo,
        X509Certificate baseCrt)//from  ww  w. jav  a2  s  . c o m
        throws GeneralSecurityException, CertIOException, OperatorCreationException, IOException {

    if (baseCrt != null) {
        subject = baseCrt.getSubjectX500Principal();
    }

    JcaX509v3CertificateBuilder certificateBuilder;
    certificateBuilder = new JcaX509v3CertificateBuilder(issuer, serialNo, begin, ends, subject, pubKey);

    if (subject.equals(issuer)) {
        certificateBuilder.addExtension(X509Extension.basicConstraints, true, new BasicConstraints(5));
    } else {
        JcaX509ExtensionUtils jxeu = new JcaX509ExtensionUtils();

        if (baseCrt != null) {
            byte[] sans = baseCrt.getExtensionValue(X509Extension.subjectAlternativeName.getId());
            if (sans != null) {
                certificateBuilder.copyAndAddExtension(X509Extension.subjectAlternativeName, true, baseCrt);
            }
        }

        SubjectKeyIdentifier subjectKeyIdentifier = jxeu.createSubjectKeyIdentifier(pubKey);
        certificateBuilder.addExtension(X509Extension.subjectKeyIdentifier, false, subjectKeyIdentifier);

        AuthorityKeyIdentifier authorityKeyIdentifier = jxeu.createAuthorityKeyIdentifier(caPubKey);
        certificateBuilder.addExtension(X509Extension.authorityKeyIdentifier, false, authorityKeyIdentifier);

        certificateBuilder.addExtension(X509Extension.basicConstraints, true, new BasicConstraints(false));

        NetscapeCertType netscapeCertType = new NetscapeCertType(
                NetscapeCertType.sslClient | NetscapeCertType.sslServer);
        certificateBuilder.addExtension(MiscObjectIdentifiers.netscapeCertType, false, netscapeCertType);

        KeyUsage keyUsage = new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment);
        certificateBuilder.addExtension(X509Extension.keyUsage, true, keyUsage);

        ExtendedKeyUsage extendedKeyUsage = new ExtendedKeyUsage(
                new KeyPurposeId[] { KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth });
        certificateBuilder.addExtension(X509Extension.extendedKeyUsage, false, extendedKeyUsage);
    }

    JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder(SIGALG);
    X509CertificateHolder holder = certificateBuilder.build(signerBuilder.build(caKey));

    /*
     * Next certificate factory trick is needed to make sure that the
     * certificate delivered to the caller is provided by the default
     * security provider instead of BouncyCastle. If we don't do this trick
     * we might run into trouble when trying to use the CertPath validator.
     */
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    X509Certificate certificate;
    certificate = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(holder.getEncoded()));
    return certificate;
}

From source file:org.panbox.core.crypto.CryptCore.java

License:Open Source License

/**
 * Creates a self signed certificate valid for 10 years (necessary to store
 * public keys in keystore)/*from w  w w .ja  va 2 s  . c om*/
 * 
 * @param privKey
 * @param pubKey
 * @param eMail
 * @param name
 * @return the certificate or NULL if there is an error
 */
private static X509Certificate createSelfSignedX509Certificate(PrivateKey privKey, PublicKey pubKey,
        String eMail, String name) {
    // Generate self-signed certificate
    X500NameBuilder builder = new X500NameBuilder(BCStyle.INSTANCE);
    builder.addRDN(BCStyle.OU, "Panbox");
    builder.addRDN(BCStyle.O, "Panbox");
    builder.addRDN(BCStyle.CN, "localhost");

    if (eMail != null) {
        builder.addRDN(BCStyle.EmailAddress, eMail);
    }

    if (name != null) {
        builder.addRDN(BCStyle.NAME, name);
    }

    Calendar cal = Calendar.getInstance();
    Date notBefore = cal.getTime();

    cal.add(Calendar.YEAR, PanboxConstants.CERTIFICATE_LIFETIME_YEARS);
    Date notAfter = cal.getTime();

    BigInteger serial = BigInteger.valueOf(System.currentTimeMillis());

    X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(builder.build(), serial, notBefore,
            notAfter, builder.build(), pubKey);

    X509Certificate cert = null;
    try {
        ContentSigner sigGen = new JcaContentSignerBuilder("SHA256WithRSAEncryption")
                .setProvider(KeyConstants.PROV_BC).build(privKey);

        cert = new JcaX509CertificateConverter().setProvider(KeyConstants.PROV_BC)
                .getCertificate(certGen.build(sigGen));

        cert.checkValidity(new Date());

        cert.verify(cert.getPublicKey());

    } catch (NoSuchAlgorithmException | InvalidKeyException | OperatorCreationException | CertificateException
            | NoSuchProviderException | SignatureException e) {
        logger.warn("Exception caught in CryptCore.createSelfSignedX509Certificate, returning null", e);
    }

    return cert;
}

From source file:org.parosproxy.paros.security.SslCertificateServiceImpl.java

License:Apache License

@Override
public KeyStore createCertForHost(String hostname)
        throws NoSuchAlgorithmException, InvalidKeyException, CertificateException, NoSuchProviderException,
        SignatureException, KeyStoreException, IOException, UnrecoverableKeyException {

    if (hostname == null) {
        throw new IllegalArgumentException("Error, 'hostname' is not allowed to be null!");
    }/*from  w w w  .j  a va2s  . c  o  m*/

    if (this.caCert == null || this.caPrivKey == null || this.caPubKey == null) {
        throw new MissingRootCertificateException(
                this.getClass() + " wasn't initialized! Got to options 'Dynamic SSL Certs' and create one.");
    }

    final KeyPair mykp = this.createKeyPair();
    final PrivateKey privKey = mykp.getPrivate();
    final PublicKey pubKey = mykp.getPublic();

    X500NameBuilder namebld = new X500NameBuilder(BCStyle.INSTANCE);
    namebld.addRDN(BCStyle.CN, hostname);
    namebld.addRDN(BCStyle.OU, "Zed Attack Proxy Project");
    namebld.addRDN(BCStyle.O, "OWASP");
    namebld.addRDN(BCStyle.C, "xx");
    namebld.addRDN(BCStyle.EmailAddress, "owasp-zed-attack-proxy@lists.owasp.org");

    X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(
            new X509CertificateHolder(caCert.getEncoded()).getSubject(),
            BigInteger.valueOf(serial.getAndIncrement()),
            new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30),
            new Date(System.currentTimeMillis() + 100 * (1000L * 60 * 60 * 24 * 30)), namebld.build(), pubKey);

    certGen.addExtension(Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifier(pubKey.getEncoded()));
    certGen.addExtension(Extension.basicConstraints, false, new BasicConstraints(false));

    ContentSigner sigGen;
    try {
        sigGen = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider("BC").build(caPrivKey);
    } catch (OperatorCreationException e) {
        throw new CertificateException(e);
    }
    final X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC")
            .getCertificate(certGen.build(sigGen));
    cert.checkValidity(new Date());
    cert.verify(caPubKey);

    final KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);
    final Certificate[] chain = new Certificate[2];
    chain[1] = this.caCert;
    chain[0] = cert;
    ks.setKeyEntry(ZAPROXY_JKS_ALIAS, privKey, PASSPHRASE, chain);
    return ks;
}