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

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

Introduction

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

Prototype

public ContentSigner build(PrivateKey privateKey) throws OperatorCreationException 

Source Link

Usage

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 www  . j a  v  a 2  s  .  co 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.shredzone.acme4j.util.CertificateUtils.java

License:Apache License

/**
 * Creates a self-signed {@link X509Certificate} that can be used for
 * {@link org.shredzone.acme4j.challenge.TlsSni01Challenge}. The certificate is valid
 * for 7 days./*from ww  w.j a  v  a  2 s . c  om*/
 *
 * @param keypair
 *            A domain {@link KeyPair} to be used for the challenge
 * @param subject
 *            Subject to create a certificate for
 * @return Created certificate
 * @deprecated Will be removed when
 *             {@link org.shredzone.acme4j.challenge.TlsSni01Challenge} is removed
 */
@Deprecated
public static X509Certificate createTlsSniCertificate(KeyPair keypair, String subject) throws IOException {
    final long now = System.currentTimeMillis();
    final long validSpanMs = 7 * 24 * 60 * 60 * 1000L;
    final String signatureAlg = "SHA256withRSA";

    try {
        X500Name issuer = new X500Name("CN=acme.invalid");
        BigInteger serial = BigInteger.valueOf(now);
        Date notBefore = new Date(now);
        Date notAfter = new Date(now + validSpanMs);

        JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(issuer, serial, notBefore,
                notAfter, issuer, keypair.getPublic());

        GeneralName[] gns = new GeneralName[1];
        gns[0] = new GeneralName(GeneralName.dNSName, subject);

        certBuilder.addExtension(Extension.subjectAlternativeName, false, new GeneralNames(gns));

        JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder(signatureAlg);

        byte[] cert = certBuilder.build(signerBuilder.build(keypair.getPrivate())).getEncoded();

        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        return (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(cert));
    } catch (CertificateException | OperatorCreationException ex) {
        throw new IOException(ex);
    }
}

From source file:org.shredzone.acme4j.util.CertificateUtils.java

License:Apache License

/**
 * Creates a self-signed {@link X509Certificate} that can be used for
 * {@link TlsSni02Challenge}. The certificate is valid for 7 days.
 *
 * @param keypair/*www  .j  av a  2 s. com*/
 *            A domain {@link KeyPair} to be used for the challenge
 * @param sanA
 *            SAN-A to be used in the certificate
 * @param sanB
 *            SAN-B to be used in the certificate
 * @return Created certificate
 */
public static X509Certificate createTlsSni02Certificate(KeyPair keypair, String sanA, String sanB)
        throws IOException {
    final long now = System.currentTimeMillis();
    final long validSpanMs = 7 * 24 * 60 * 60 * 1000L;
    final String signatureAlg = "SHA256withRSA";

    try {
        X500Name issuer = new X500Name("CN=acme.invalid");
        BigInteger serial = BigInteger.valueOf(now);
        Date notBefore = new Date(now);
        Date notAfter = new Date(now + validSpanMs);

        JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(issuer, serial, notBefore,
                notAfter, issuer, keypair.getPublic());

        GeneralName[] gns = new GeneralName[2];
        gns[0] = new GeneralName(GeneralName.dNSName, sanA);
        gns[1] = new GeneralName(GeneralName.dNSName, sanB);

        certBuilder.addExtension(Extension.subjectAlternativeName, false, new GeneralNames(gns));

        JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder(signatureAlg);

        byte[] cert = certBuilder.build(signerBuilder.build(keypair.getPrivate())).getEncoded();

        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        return (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(cert));
    } catch (CertificateException | OperatorCreationException ex) {
        throw new IOException(ex);
    }
}

From source file:org.shredzone.acme4j.util.CSRBuilder.java

License:Apache License

/**
 * Signs the completed CSR./*from  www .j  a v a2s.  c  om*/
 *
 * @param keypair
 *            {@link KeyPair} to sign the CSR with
 */
public void sign(KeyPair keypair) throws IOException {
    if (namelist.isEmpty()) {
        throw new IllegalStateException("No domain was set");
    }
    if (keypair == null) {
        throw new IllegalArgumentException("keypair must not be null");
    }

    try {
        GeneralName[] gns = new GeneralName[namelist.size()];
        for (int ix = 0; ix < namelist.size(); ix++) {
            gns[ix] = new GeneralName(GeneralName.dNSName, namelist.get(ix));
        }
        GeneralNames subjectAltName = new GeneralNames(gns);

        PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder(
                namebuilder.build(), keypair.getPublic());

        ExtensionsGenerator extensionsGenerator = new ExtensionsGenerator();
        extensionsGenerator.addExtension(Extension.subjectAlternativeName, false, subjectAltName);
        p10Builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest,
                extensionsGenerator.generate());

        PrivateKey pk = keypair.getPrivate();
        JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder(
                pk instanceof ECKey ? EC_SIGNATURE_ALG : SIGNATURE_ALG);
        ContentSigner signer = csBuilder.build(pk);

        csr = p10Builder.build(signer);
    } catch (OperatorCreationException ex) {
        throw new IOException("Could not generate CSR", ex);
    }
}

From source file:org.signserver.module.tsa.MSAuthCodeTimeStampSigner.java

License:Open Source License

/**
 * The main method performing the actual timestamp operation.
 * Expects the signRequest to be a GenericSignRequest contining a
 * TimeStampRequest//from www. j a  v a2  s  .  c om
 *
 * @param signRequest
 * @param requestContext
 * @return the sign response
 * @see org.signserver.server.IProcessable#processData(org.signserver.common.ProcessRequest, org.signserver.common.RequestContext)
 */
public ProcessResponse processData(final ProcessRequest signRequest, final RequestContext requestContext)
        throws IllegalRequestException, CryptoTokenOfflineException, SignServerException {

    // Log values
    final LogMap logMap = LogMap.getInstance(requestContext);

    try {
        final ISignRequest sReq = (ISignRequest) signRequest;
        final byte[] requestbytes = (byte[]) sReq.getRequestData();

        if (requestbytes == null || requestbytes.length == 0) {
            LOG.error("Request must contain data");
            throw new IllegalRequestException("Request must contain data");
        }

        // Check that the request contains a valid TimeStampRequest object.
        if (!(signRequest instanceof GenericSignRequest)) {
            final IllegalRequestException exception = new IllegalRequestException(
                    "Recieved request wasn't an expected GenericSignRequest. ");
            LOG.error("Received request wasn't an expected GenericSignRequest");
            throw exception;
        }

        if (!((sReq.getRequestData() instanceof TimeStampRequest)
                || (sReq.getRequestData() instanceof byte[]))) {
            final IllegalRequestException exception = new IllegalRequestException(
                    "Recieved request data wasn't an expected TimeStampRequest. ");
            LOG.error("Received request data wasn't an expected TimeStampRequest");
            throw exception;
        }

        if (!validChain) {
            LOG.error("Certificate chain not correctly configured");
            throw new CryptoTokenOfflineException("Certificate chain not correctly configured");
        }

        ASN1Primitive asn1obj = ASN1Primitive.fromByteArray(Base64.decode(requestbytes));
        ASN1Sequence asn1seq = ASN1Sequence.getInstance(asn1obj);

        if (asn1seq.size() != 2) {
            LOG.error("Wrong structure, should be an ASN1Sequence with 2 elements");
            throw new IllegalRequestException("Wrong structure, should be an ASN1Sequence with 2 elements");
        }

        ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(asn1seq.getObjectAt(0));
        ASN1Sequence asn1seq1 = ASN1Sequence.getInstance(asn1seq.getObjectAt(1));

        final ContentInfo ci = new ContentInfo(asn1seq1);

        if (!oid.getId().equals(msOID)) {
            LOG.error("Invalid OID in request: " + oid.getId());
            throw new IllegalRequestException("Invalid OID in request: " + oid.getId());
        }

        if (asn1seq1.size() != 2) {
            LOG.error(
                    "Wrong structure, should be an ASN1Sequence with 2 elements as the value of element 0 in the outer ASN1Sequence");
            throw new IllegalRequestException(
                    "Wrong structure, should be an ASN1Sequence with 2 elements as the value of element 0 in the outer ASN1Sequence");
        }

        oid = ASN1ObjectIdentifier.getInstance(asn1seq1.getObjectAt(0));

        if (!oid.getId().equals(dataOID)) {
            throw new IllegalRequestException("Wrong contentType OID: " + oid.getId());
        }

        ASN1TaggedObject tag = ASN1TaggedObject.getInstance(asn1seq1.getObjectAt(1));

        if (tag.getTagNo() != 0) {
            throw new IllegalRequestException("Wrong tag no (should be 0): " + tag.getTagNo());
        }

        ASN1OctetString octets = ASN1OctetString.getInstance(tag.getObject());
        byte[] content = octets.getOctets();

        final ITimeSource timeSrc;
        final Date date;
        byte[] der;
        ICryptoInstance crypto = null;
        try {
            crypto = acquireCryptoInstance(ICryptoToken.PURPOSE_SIGN, signRequest, requestContext);

            // get signing cert certificate chain and private key
            List<Certificate> certList = this.getSigningCertificateChain(crypto);
            if (certList == null) {
                throw new SignServerException("Null certificate chain. This signer needs a certificate.");
            }

            Certificate[] certs = (Certificate[]) certList.toArray(new Certificate[certList.size()]);

            // Sign
            X509Certificate x509cert = (X509Certificate) certs[0];

            timeSrc = getTimeSource();
            if (LOG.isDebugEnabled()) {
                LOG.debug("TimeSource: " + timeSrc.getClass().getName());
            }
            date = timeSrc.getGenTime();

            if (date == null) {
                throw new ServiceUnavailableException("Time source is not available");
            }

            ASN1EncodableVector signedAttributes = new ASN1EncodableVector();
            signedAttributes.add(new Attribute(CMSAttributes.signingTime, new DERSet(new Time(date))));

            if (includeSigningCertificateAttribute) {
                try {
                    final DERInteger serial = new DERInteger(x509cert.getSerialNumber());
                    final X509CertificateHolder certHolder = new X509CertificateHolder(x509cert.getEncoded());
                    final X500Name issuer = certHolder.getIssuer();
                    final GeneralName name = new GeneralName(issuer);
                    final GeneralNames names = new GeneralNames(name);
                    final IssuerSerial is = new IssuerSerial(names, ASN1Integer.getInstance(serial));

                    final ESSCertID essCertid = new ESSCertID(
                            MessageDigest.getInstance("SHA-1").digest(x509cert.getEncoded()), is);
                    signedAttributes.add(new Attribute(PKCSObjectIdentifiers.id_aa_signingCertificate,
                            new DERSet(new SigningCertificate(essCertid))));
                } catch (NoSuchAlgorithmException e) {
                    LOG.error("Can't find SHA-1 implementation: " + e.getMessage());
                    throw new SignServerException("Can't find SHA-1 implementation", e);
                }
            }

            AttributeTable signedAttributesTable = new AttributeTable(signedAttributes);
            DefaultSignedAttributeTableGenerator signedAttributeGenerator = new DefaultSignedAttributeTableGenerator(
                    signedAttributesTable);

            final String provider = cryptoToken.getProvider(ICryptoToken.PROVIDERUSAGE_SIGN);

            SignerInfoGeneratorBuilder signerInfoBuilder = new SignerInfoGeneratorBuilder(
                    new JcaDigestCalculatorProviderBuilder().setProvider("BC").build());
            signerInfoBuilder.setSignedAttributeGenerator(signedAttributeGenerator);

            JcaContentSignerBuilder contentSigner = new JcaContentSignerBuilder(signatureAlgo);
            contentSigner.setProvider(provider);

            final SignerInfoGenerator sig = signerInfoBuilder.build(contentSigner.build(crypto.getPrivateKey()),
                    new X509CertificateHolder(x509cert.getEncoded()));

            JcaCertStore cs = new JcaCertStore(certList);

            CMSTypedData cmspba = new CMSProcessableByteArray(content);
            CMSSignedData cmssd = MSAuthCodeCMSUtils.generate(cmspba, true, Arrays.asList(sig),
                    MSAuthCodeCMSUtils.getCertificatesFromStore(cs), Collections.emptyList(), ci);

            der = ASN1Primitive.fromByteArray(cmssd.getEncoded()).getEncoded();
        } finally {
            releaseCryptoInstance(crypto, requestContext);
        }

        // Log values
        logMap.put(ITimeStampLogger.LOG_TSA_TIME, String.valueOf(date.getTime()));
        logMap.put(ITimeStampLogger.LOG_TSA_TIMESOURCE, timeSrc.getClass().getSimpleName());

        final String archiveId = createArchiveId(requestbytes,
                (String) requestContext.get(RequestContext.TRANSACTION_ID));

        final GenericSignResponse signResponse;
        byte[] signedbytes = Base64.encode(der, false);

        logMap.put(ITimeStampLogger.LOG_TSA_TIMESTAMPRESPONSE_ENCODED, new String(signedbytes));

        final Collection<? extends Archivable> archivables = Arrays.asList(
                new DefaultArchivable(Archivable.TYPE_REQUEST, REQUEST_CONTENT_TYPE, requestbytes, archiveId),
                new DefaultArchivable(Archivable.TYPE_RESPONSE, RESPONSE_CONTENT_TYPE, signedbytes, archiveId));

        if (signRequest instanceof GenericServletRequest) {
            signResponse = new GenericServletResponse(sReq.getRequestID(), signedbytes,
                    getSigningCertificate(signRequest, requestContext), archiveId, archivables,
                    RESPONSE_CONTENT_TYPE);
        } else {
            signResponse = new GenericSignResponse(sReq.getRequestID(), signedbytes,
                    getSigningCertificate(signRequest, requestContext), archiveId, archivables);
        }

        // The client can be charged for the request
        requestContext.setRequestFulfilledByWorker(true);

        return signResponse;

    } catch (IOException e) {
        final IllegalRequestException exception = new IllegalRequestException("IOException: " + e.getMessage(),
                e);
        LOG.error("IOException: ", e);
        logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, exception.getMessage());
        throw exception;
    } catch (CMSException e) {
        final SignServerException exception = new SignServerException(e.getMessage(), e);
        LOG.error("CMSException: ", e);
        logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, exception.getMessage());
        throw exception;
    } catch (OperatorCreationException e) {
        final SignServerException exception = new SignServerException(e.getMessage(), e);
        LOG.error("OperatorCreationException: ", e);
        logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, exception.getMessage());
        throw exception;
    } catch (CertificateEncodingException e) {
        final SignServerException exception = new SignServerException(e.getMessage(), e);
        LOG.error("CertificateEncodingException: ", e);
        logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, exception.getMessage());
        throw exception;
    } catch (ArrayIndexOutOfBoundsException e) {
        // the BC base64 decoder doesn't check the the base64 input length...
        final IllegalRequestException exception = new IllegalRequestException(
                "ArrayIndexOutOfBoundsException: " + e.getMessage(), e);
        LOG.error("ArrayIndexOutOfBoundsException: ", e);
        logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, exception.getMessage());
        throw exception;
    }
}

From source file:org.signserver.server.cryptotokens.CryptoTokenHelper.java

License:Open Source License

private static X509Certificate getSelfCertificate(String myname, long validity, String sigAlg, KeyPair keyPair,
        String provider) throws OperatorCreationException, CertificateException {
    final long currentTime = new Date().getTime();
    final Date firstDate = new Date(currentTime - 24 * 60 * 60 * 1000);
    final Date lastDate = new Date(currentTime + validity * 1000);

    // Add all mandatory attributes
    if (LOG.isDebugEnabled()) {
        LOG.debug("keystore signing algorithm " + sigAlg);
    }//from  w ww.ja  v a  2  s  . com

    final PublicKey publicKey = keyPair.getPublic();
    if (publicKey == null) {
        throw new IllegalArgumentException("Public key is null");
    }

    X509v3CertificateBuilder cg = new JcaX509v3CertificateBuilder(new X500Principal(myname),
            BigInteger.valueOf(firstDate.getTime()), firstDate, lastDate, new X500Principal(myname), publicKey);
    final JcaContentSignerBuilder contentSignerBuilder = new JcaContentSignerBuilder(sigAlg);
    contentSignerBuilder.setProvider(provider);

    final ContentSigner contentSigner = contentSignerBuilder.build(keyPair.getPrivate());

    return new JcaX509CertificateConverter().getCertificate(cg.build(contentSigner));
}

From source file:org.signserver.server.cryptotokens.KeystoreCryptoTokenTest.java

License:Open Source License

/** Creates a self signed certificate. */
private X509Certificate getSelfCertificate(String alias, long validity, KeyPair keyPair) throws Exception {
    final long currentTime = new Date().getTime();
    final Date firstDate = new Date(currentTime - 24 * 60 * 60 * 1000);
    final Date lastDate = new Date(currentTime + validity * 1000);
    final X509v3CertificateBuilder cg = new JcaX509v3CertificateBuilder(new X500Principal(alias),
            BigInteger.valueOf(firstDate.getTime()), firstDate, lastDate, new X500Principal(alias),
            keyPair.getPublic());//w  w  w  .  j a v  a  2 s.c  om
    final JcaContentSignerBuilder contentSignerBuilder = new JcaContentSignerBuilder("SHA1withRSA");
    contentSignerBuilder.setProvider("BC");
    final ContentSigner contentSigner = contentSignerBuilder.build(keyPair.getPrivate());
    return new JcaX509CertificateConverter().getCertificate(cg.build(contentSigner));
}

From source file:org.soulwing.credo.service.crypto.bc.BcCertificationRequestBuilder.java

License:Apache License

/**
 * {@inheritDoc}/*from  www .j  a  v a  2 s  .  com*/
 */
@Override
public CertificationRequestWrapper build(PrivateKeyWrapper privateKey) throws CertificationRequestException {
    PKCS10CertificationRequestBuilder builder = new JcaPKCS10CertificationRequestBuilder(subject,
            publicKey.derive());
    JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder("SHA1WithRSA");
    try {
        ContentSigner signer = signerBuilder.build(privateKey.derive());
        PKCS10CertificationRequest csr = builder.build(signer);
        return new BcCertificationRequestWrapper(csr);
    } catch (OperatorCreationException ex) {
        throw new CertificationRequestException(ex);
    }
}

From source file:org.tastefuljava.minica.X509CertificateBuilder.java

License:Open Source License

public X509Certificate build()
        throws OperatorCreationException, CertificateException, IOException, NoSuchAlgorithmException {
    if (publicKey == null) {
        KeyPair pair = generateKeyPair(algorithm, keySize);
        publicKey = pair.getPublic();/*from   w w w.j  a v  a2s . c o m*/
        privateKey = pair.getPrivate();
    }
    if (issuer == null) {
        issuer = principal;
        issuerKey = privateKey;
    }
    JcaX509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(issuer, sn, start, end, principal,
            publicKey);
    if (basicConstraints < 0) {
        certGen.addExtension(X509Extension.basicConstraints, true, new BasicConstraints(false));
    } else if (basicConstraints != Integer.MAX_VALUE) {
        certGen.addExtension(X509Extension.basicConstraints, true, new BasicConstraints(basicConstraints));
    }
    JcaContentSignerBuilder builder = new JcaContentSignerBuilder(signatureAlgorithm);
    builder.setProvider("BC");
    ContentSigner signr = builder.build(issuerKey);
    X509CertificateHolder certHolder = certGen.build(signr);
    return decode(certHolder.getEncoded());
}

From source file:org.wso2.carbon.certificate.mgt.core.impl.CertificateGeneratorNegativeTests.java

License:Open Source License

@Test(description = "This test case tests behaviour when Certificate Operator creation error occurs", expectedExceptions = KeystoreException.class)
public void negativeTestGenerateCertificateFromCSR2() throws Exception {
    CertificateGenerator generator = new CertificateGenerator();
    //Prepare mock objects
    JcaContentSignerBuilder mock = Mockito.mock(JcaContentSignerBuilder.class);
    Mockito.when(mock.setProvider(Matchers.eq(CertificateManagementConstants.PROVIDER))).thenReturn(mock);
    Mockito.when(mock.build(Matchers.any(PrivateKey.class)))
            .thenThrow(new OperatorCreationException("OPERATOR"));
    PowerMockito.whenNew(JcaContentSignerBuilder.class).withAnyArguments().thenReturn(mock);
    //prepare input parameters
    CSRGenerator csrGeneration = new CSRGenerator();
    KeyStoreReader keyStoreReader = new KeyStoreReader();
    KeyPair keyPair = csrGeneration.generateKeyPair("RSA", 1024);
    byte[] csrData = csrGeneration.generateCSR("SHA256WithRSA", keyPair);
    PKCS10CertificationRequest certificationRequest;
    PrivateKey privateKeyCA = keyStoreReader.getCAPrivateKey();
    X509Certificate certCA = (X509Certificate) keyStoreReader.getCACertificate();
    certificationRequest = new PKCS10CertificationRequest(csrData);
    generator.generateCertificateFromCSR(privateKeyCA, certificationRequest,
            certCA.getIssuerX500Principal().getName());
}