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.ejbca.core.ejb.authentication.web.WebAuthenticationProviderSessionBeanTest.java

License:Open Source License

private static X509Certificate generateUnbornCert(String dn, String policyId, PrivateKey privKey,
        PublicKey pubKey, String sigAlg, boolean isCA)
        throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, IllegalStateException,
        NoSuchProviderException, OperatorCreationException, CertificateException, IOException {
    int keyusage = X509KeyUsage.keyCertSign + X509KeyUsage.cRLSign;
    // Create self signed certificate
    Date firstDate = new Date();
    // Set starting date to tomorrow
    firstDate.setTime(firstDate.getTime() + (24 * 3600 * 1000));
    Date lastDate = new Date();
    // Set Expiry in two days
    lastDate.setTime(lastDate.getTime() + ((2 * 24 * 60 * 60 * 1000)));

    // Transform the PublicKey to be sure we have it in a format that the X509 certificate generator handles, it might be
    // a CVC public key that is passed as parameter
    PublicKey publicKey = null;//from   w  w w.  ja v a  2  s .co m
    if (pubKey instanceof RSAPublicKey) {
        RSAPublicKey rsapk = (RSAPublicKey) pubKey;
        RSAPublicKeySpec rSAPublicKeySpec = new RSAPublicKeySpec(rsapk.getModulus(), rsapk.getPublicExponent());
        try {
            publicKey = KeyFactory.getInstance("RSA").generatePublic(rSAPublicKeySpec);
        } catch (InvalidKeySpecException e) {
            publicKey = pubKey;
        }
    } else if (pubKey instanceof ECPublicKey) {
        ECPublicKey ecpk = (ECPublicKey) pubKey;
        try {
            ECPublicKeySpec ecspec = new ECPublicKeySpec(ecpk.getW(), ecpk.getParams()); // will throw NPE if key is "implicitlyCA"
            publicKey = KeyFactory.getInstance("EC").generatePublic(ecspec);
        } catch (InvalidKeySpecException e) {
            publicKey = pubKey;
        } catch (NullPointerException e) {
            publicKey = pubKey;
        }
    } else {
        publicKey = pubKey;
    }
    // Serialnumber is random bits, where random generator is initialized with Date.getTime() when this
    // bean is created.
    byte[] serno = new byte[8];
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    random.setSeed(new Date().getTime());
    random.nextBytes(serno);

    final SubjectPublicKeyInfo pkinfo = new SubjectPublicKeyInfo(
            (ASN1Sequence) ASN1Primitive.fromByteArray(publicKey.getEncoded()));
    X509v3CertificateBuilder certbuilder = new X509v3CertificateBuilder(CertTools.stringToBcX500Name(dn),
            new java.math.BigInteger(serno).abs(), firstDate, lastDate, CertTools.stringToBcX500Name(dn),
            pkinfo);
    // Basic constranits is always critical and MUST be present at-least in CA-certificates.
    BasicConstraints bc = new BasicConstraints(isCA);
    certbuilder.addExtension(Extension.basicConstraints, true, bc);

    // Put critical KeyUsage in CA-certificates
    if (isCA) {
        X509KeyUsage ku = new X509KeyUsage(keyusage);
        certbuilder.addExtension(Extension.keyUsage, true, ku);
    }
    // Subject and Authority key identifier is always non-critical and MUST be present for certificates to verify in Firefox.
    try {
        if (isCA) {
            ASN1InputStream spkiAsn1InputStream = new ASN1InputStream(
                    new ByteArrayInputStream(publicKey.getEncoded()));
            ASN1InputStream apkiAsn1InputStream = new ASN1InputStream(
                    new ByteArrayInputStream(publicKey.getEncoded()));
            try {
                SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo(
                        (ASN1Sequence) spkiAsn1InputStream.readObject());
                X509ExtensionUtils x509ExtensionUtils = new BcX509ExtensionUtils();
                SubjectKeyIdentifier ski = x509ExtensionUtils.createSubjectKeyIdentifier(spki);
                SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo(
                        (ASN1Sequence) apkiAsn1InputStream.readObject());
                AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki);
                certbuilder.addExtension(Extension.subjectKeyIdentifier, false, ski);
                certbuilder.addExtension(Extension.authorityKeyIdentifier, false, aki);
            } finally {
                spkiAsn1InputStream.close();
                apkiAsn1InputStream.close();
            }
        }
    } catch (IOException e) { // do nothing
    }
    // CertificatePolicies extension if supplied policy ID, always non-critical
    if (policyId != null) {
        PolicyInformation pi = new PolicyInformation(new ASN1ObjectIdentifier(policyId));
        DERSequence seq = new DERSequence(pi);
        certbuilder.addExtension(Extension.certificatePolicies, false, seq);
    }
    final ContentSigner signer = new BufferingContentSigner(new JcaContentSignerBuilder("SHA1withRSA")
            .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(privKey), 20480);
    final X509CertificateHolder certHolder = certbuilder.build(signer);
    final X509Certificate selfcert = (X509Certificate) CertTools.getCertfromByteArray(certHolder.getEncoded());

    return selfcert;
}

From source file:org.ejbca.core.model.ca.caadmin.extendedcaservices.CmsCAService.java

License:Open Source License

@Override
public ExtendedCAServiceResponse extendedService(final CryptoToken cryptoToken,
        final ExtendedCAServiceRequest request) throws ExtendedCAServiceRequestException,
        IllegalExtendedCAServiceRequestException, ExtendedCAServiceNotActiveException {
    if (log.isTraceEnabled()) {
        log.trace(">extendedService");
    }/*w w w  . j  a v a 2 s  .c  o m*/
    if (!(request instanceof CmsCAServiceRequest)) {
        throw new IllegalExtendedCAServiceRequestException();
    }
    if (getStatus() != ExtendedCAServiceInfo.STATUS_ACTIVE) {
        final String msg = intres.getLocalizedMessage("caservice.notactive", "CMS");
        log.error(msg);
        throw new ExtendedCAServiceNotActiveException(msg);
    }
    ExtendedCAServiceResponse returnval = null;
    final X509Certificate signerCert = (X509Certificate) certificatechain.get(0);
    final CmsCAServiceRequest serviceReq = (CmsCAServiceRequest) request;
    // Create the signed data
    final CMSSignedDataGenerator gen1 = new CMSSignedDataGenerator();
    try {
        byte[] resp = serviceReq.getDoc();
        // Add our signer info and sign the message
        if ((serviceReq.getMode() & CmsCAServiceRequest.MODE_SIGN) != 0) {
            final List<X509Certificate> x509CertChain = new ArrayList<X509Certificate>();
            for (Certificate certificate : certificatechain) {
                x509CertChain.add((X509Certificate) certificate);
            }
            gen1.addCertificates(new CollectionStore(CertTools.convertToX509CertificateHolder(x509CertChain)));
            JcaDigestCalculatorProviderBuilder calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder()
                    .setProvider(BouncyCastleProvider.PROVIDER_NAME);
            JcaSignerInfoGeneratorBuilder builder = new JcaSignerInfoGeneratorBuilder(
                    calculatorProviderBuilder.build());
            ASN1ObjectIdentifier oid = AlgorithmTools
                    .getSignAlgOidFromDigestAndKey(CMSSignedGenerator.DIGEST_SHA1, privKey.getAlgorithm());
            String signatureAlgorithmName = AlgorithmTools.getAlgorithmNameFromOID(oid);
            JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder(signatureAlgorithmName)
                    .setProvider(BouncyCastleProvider.PROVIDER_NAME);
            ContentSigner contentSigner = signerBuilder.build(privKey);
            gen1.addSignerInfoGenerator(builder.build(contentSigner, signerCert));
            final CMSTypedData msg = new CMSProcessableByteArray(resp);
            final CMSSignedData s = gen1.generate(msg, true);
            resp = s.getEncoded();
        }
        if ((serviceReq.getMode() & CmsCAServiceRequest.MODE_ENCRYPT) != 0) {
            CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();
            edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(getCMSCertificate())
                    .setProvider(BouncyCastleProvider.PROVIDER_NAME));
            JceCMSContentEncryptorBuilder jceCMSContentEncryptorBuilder = new JceCMSContentEncryptorBuilder(
                    PKCSObjectIdentifiers.des_EDE3_CBC).setProvider(BouncyCastleProvider.PROVIDER_NAME);
            CMSEnvelopedData ed = edGen.generate(new CMSProcessableByteArray(resp),
                    jceCMSContentEncryptorBuilder.build());
            resp = ed.getEncoded();
        }
        if ((serviceReq.getMode() & CmsCAServiceRequest.MODE_DECRYPT) != 0) {
            final CMSEnvelopedData ed = new CMSEnvelopedData(resp);
            final RecipientInformationStore recipients = ed.getRecipientInfos();
            final X500Name issuer = X500Name
                    .getInstance(getCMSCertificate().getIssuerX500Principal().getEncoded());
            final KeyTransRecipientId id = new KeyTransRecipientId(issuer,
                    getCMSCertificate().getSerialNumber());
            final RecipientInformation recipient = recipients.get(id);
            if (recipient != null) {
                JceKeyTransEnvelopedRecipient rec = new JceKeyTransEnvelopedRecipient(this.privKey);
                // Provider for decrypting the symmetric key 
                rec.setContentProvider(BouncyCastleProvider.PROVIDER_NAME);
                rec.setProvider(cryptoToken.getSignProviderName());
                // We can use a different provider for decrypting the content, for example of we used a PKCS#11 provider above we could use the BC provider below
                resp = recipient.getContent(rec);
            }
        }
        returnval = new CmsCAServiceResponse(resp);
    } catch (CMSException e) {
        log.error("Error in CmsCAService", e);
        throw new ExtendedCAServiceRequestException(e);
    } catch (IOException e) {
        log.error("Error in CmsCAService", e);
        throw new ExtendedCAServiceRequestException(e);
    } catch (OperatorCreationException e) {
        log.error("Error in CmsCAService", e);
        throw new ExtendedCAServiceRequestException(e);
    } catch (CertificateEncodingException e) {
        log.error("Error in CmsCAService", e);
        throw new ExtendedCAServiceRequestException(e);
    }
    if (log.isTraceEnabled()) {
        log.trace("<extendedService");
    }
    return returnval;
}

From source file:org.ejbca.core.protocol.ocsp.OCSPUnidClient.java

License:Open Source License

/**
 * @param serialNr serial number of the certificate to verify
 * @param cacert issuer of the certificate to verify
 * @param useGet if true GET will be used instead of POST as HTTP method
 * @return response can contain and an error code but the fnr is allways null, never returns null.
 * @throws OCSPException // w  w  w. j av a 2s  .co  m
 * @throws IOException
 * @throws OperatorCreationException if Signer couldn't be created
 * @throws KeyStoreException 
 * @throws NoSuchAlgorithmException 
 * @throws CertificateException 
 * @throws KeyManagementException 
 * @throws UnrecoverableKeyException 
 */
public OCSPUnidResponse lookup(BigInteger serialNr, X509Certificate cacert, boolean useGet)
        throws OCSPException, IOException, OperatorCreationException, UnrecoverableKeyException,
        KeyManagementException, CertificateException, NoSuchAlgorithmException, KeyStoreException {
    if (this.httpReqPath == null) {
        // If we didn't pass a url to the constructor and the cert does not have the URL, we will fail...
        OCSPUnidResponse ret = new OCSPUnidResponse();
        ret.setErrorCode(OCSPUnidResponse.ERROR_NO_OCSP_URI);
        return ret;
    }
    final OCSPReqBuilder gen = new OCSPReqBuilder();
    final CertificateID certId = new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(),
            (X509Certificate) cacert, serialNr);
    gen.addRequest(certId);
    if (!useGet) {
        // Add a nonce to the request
        gen.setRequestExtensions(this.extensions);
    }
    final OCSPReq req;
    if (this.signKey != null) {
        final X509Certificate localCertChain[] = this.certChain != null ? this.certChain
                : new X509Certificate[] { (X509Certificate) cacert };
        final JcaX509CertificateHolder[] certificateHolderChain = CertTools
                .convertToX509CertificateHolder(localCertChain);
        gen.setRequestorName(certificateHolderChain[0].getSubject());
        req = gen.build(
                new BufferingContentSigner(new JcaContentSignerBuilder("SHA1withRSA")
                        .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(this.signKey), 20480),
                certificateHolderChain);
    } else {
        req = gen.build();
    }
    // write request if directory exists.
    File ocspReqDir = new File(requestDirectory);
    if (ocspReqDir.isDirectory()) {
        OutputStream os = new FileOutputStream(new File(ocspReqDir, serialNr.toString()));
        os.write(req.getEncoded());
        os.close();
    }
    // Send the request and receive a BasicResponse
    return sendOCSPRequest(req.getEncoded(), cacert, useGet);
}

From source file:org.ejbca.core.protocol.ocsp.ProtocolOcspHttpPerfTest.java

License:Open Source License

/** Tests ocsp message
 * @throws Exception error/*from   w w w. j a v  a2 s  .  co m*/
 */
@Test
public void test01OcspGood() throws Exception {
    log.trace(">test02OcspGood()");

    // And an OCSP request
    OCSPReqBuilder gen = new OCSPReqBuilder();
    final Certificate ocspTestCert = getTestCert();
    gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), (X509Certificate) cacert,
            CertTools.getSerialNumber(ocspTestCert)));
    OCSPReq req = null;
    if (dosigning) {
        gen.setRequestorName(certChain[0].getSubject());
        req = gen.build(new BufferingContentSigner(new JcaContentSignerBuilder(signingAlg)
                .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(privKey), 20480), certChain);
    } else {
        req = gen.build();
    }

    // Send the request and receive a singleResponse
    SingleResp singleResp = sendOCSPPost(req.getEncoded(), null);

    CertificateID certId = singleResp.getCertID();
    assertEquals("Serno in response does not match serno in request.", certId.getSerialNumber(),
            CertTools.getSerialNumber(ocspTestCert));
    Object status = singleResp.getCertStatus();
    assertEquals("Status is not null (good)", status, null);
    log.trace("<test02OcspGood()");
}

From source file:org.ejbca.core.protocol.ocsp.ProtocolOcspHttpTest.java

License:Open Source License

@Test
public void test07SignedOcsp() throws Exception {
    assertTrue("This test can only be run on a full EJBCA installation.",
            ((HttpURLConnection) new URL(httpReqPath + '/').openConnection()).getResponseCode() == 200);

    // find a CA (TestCA?) create a user and generate his cert
    // send OCSP req to server and get good response
    // change status of cert to bad status
    // send OCSP req and get bad status
    // (send crap message and get good error)
    try {//from  w  w w  .  j  a  v  a 2 s .c  o m
        KeyPair keys = createUserCert(caid);

        // And an OCSP request
        OCSPReqBuilder gen = new OCSPReqBuilder();
        gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), cacert,
                ocspTestCert.getSerialNumber()));
        Extension[] extensions = new Extension[1];
        extensions[0] = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false,
                new DEROctetString("123456789".getBytes()));
        gen.setRequestExtensions(new Extensions(extensions));

        X509CertificateHolder chain[] = new X509CertificateHolder[2];
        chain[0] = new JcaX509CertificateHolder(ocspTestCert);
        chain[1] = new JcaX509CertificateHolder(cacert);
        gen.setRequestorName(chain[0].getSubject());
        OCSPReq req = gen.build(new JcaContentSignerBuilder("SHA1WithRSA")
                .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(keys.getPrivate()), chain);

        // First test with a signed OCSP request that can be verified
        Collection<Certificate> cacerts = new ArrayList<Certificate>();
        cacerts.add(cacert);
        CaCertificateCache certcache = CaCertificateCache.INSTANCE;
        certcache.loadCertificates(cacerts);
        X509Certificate signer = checkRequestSignature("127.0.0.1", req, certcache);
        assertNotNull(signer);
        assertEquals(ocspTestCert.getSerialNumber().toString(16), signer.getSerialNumber().toString(16));

        // Try with an unsigned request, we should get a SignRequestException
        req = gen.build();
        boolean caught = false;
        try {
            signer = checkRequestSignature("127.0.0.1", req, certcache);
        } catch (SignRequestException e) {
            caught = true;
        }
        assertTrue(caught);

        // sign with a keystore where the CA-certificate is not known
        KeyStore store = KeyStore.getInstance("PKCS12", "BC");
        ByteArrayInputStream fis = new ByteArrayInputStream(ks3);
        store.load(fis, "foo123".toCharArray());
        Certificate[] certs = KeyTools.getCertChain(store, "privateKey");
        chain[0] = new JcaX509CertificateHolder((X509Certificate) certs[0]);
        chain[1] = new JcaX509CertificateHolder((X509Certificate) certs[1]);
        PrivateKey pk = (PrivateKey) store.getKey("privateKey", "foo123".toCharArray());
        req = gen.build(new BufferingContentSigner(new JcaContentSignerBuilder("SHA1WithRSA").build(pk), 20480),
                chain);
        // Send the request and receive a singleResponse, this response should
        // throw an SignRequestSignatureException
        caught = false;
        try {
            signer = checkRequestSignature("127.0.0.1", req, certcache);
        } catch (SignRequestSignatureException e) {
            caught = true;
        }
        assertTrue(caught);

        // sign with a keystore where the signing certificate has expired
        store = KeyStore.getInstance("PKCS12", "BC");
        fis = new ByteArrayInputStream(ksexpired);
        store.load(fis, "foo123".toCharArray());
        certs = KeyTools.getCertChain(store, "ocspclient");
        chain[0] = new JcaX509CertificateHolder((X509Certificate) certs[0]);
        chain[1] = new JcaX509CertificateHolder((X509Certificate) certs[1]);
        pk = (PrivateKey) store.getKey("ocspclient", "foo123".toCharArray());
        req = gen.build(new BufferingContentSigner(new JcaContentSignerBuilder("SHA1WithRSA").build(pk), 20480),
                chain);
        // Send the request and receive a singleResponse, this response should
        // throw an SignRequestSignatureException
        caught = false;
        try {
            signer = checkRequestSignature("127.0.0.1", req, certcache);
        } catch (SignRequestSignatureException e) {
            caught = true;
        }
        assertTrue(caught);
    } finally {
        endEntityManagementSession.deleteUser(admin, "ocsptest");
    }

}

From source file:org.ejbca.core.protocol.ocsp.ProtocolOcspSignedHttpTest.java

License:Open Source License

/** Tests ocsp message
 * @throws Exception error// w ww.  j  a  va 2  s.c o m
 */
@Test
public void test01OcspGood() throws Exception {
    log.trace(">test01OcspGood()");

    // find a CA (TestCA?) create a user and generate his cert
    // send OCSP req to server and get good response
    // change status of cert to bad status
    // send OCSP req and get bad status
    // (send crap message and get good error)

    // Make user that we know...
    boolean userExists = endEntityManagementSession.existsUser(END_ENTITY_NAME);
    if (!userExists) {
        endEntityManagementSession.addUser(admin, END_ENTITY_NAME, "foo123", "C=SE,O=AnaTom,CN=OCSPTest", null,
                "ocsptest@anatom.se", false, SecConst.EMPTY_ENDENTITYPROFILE,
                CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, EndEntityTypes.ENDUSER.toEndEntityType(),
                SecConst.TOKEN_SOFT_PEM, 0, caid);
        log.debug("created user: ocsptest, foo123, C=SE, O=AnaTom, CN=OCSPTest");
    } else {
        log.debug("User ocsptest already exists.");
        EndEntityInformation userData = new EndEntityInformation(END_ENTITY_NAME, "C=SE,O=AnaTom,CN=OCSPTest",
                caid, null, "ocsptest@anatom.se", EndEntityConstants.STATUS_NEW,
                EndEntityTypes.ENDUSER.toEndEntityType(), SecConst.EMPTY_ENDENTITYPROFILE,
                CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, null, null, SecConst.TOKEN_SOFT_PEM, 0,
                null);
        userData.setPassword("foo123");
        endEntityManagementSession.changeUser(admin, userData, false);
        log.debug("Reset status to NEW");
    }
    try {
        // Generate certificate for the new user
        KeyPair keys = KeyTools.genKeys("512", "RSA");

        // user that we know exists...
        ocspTestCert = (X509Certificate) signSession.createCertificate(admin, "ocsptest", "foo123",
                new PublicKeyWrapper(keys.getPublic()));
        assertNotNull("Failed to create a certificate", ocspTestCert);

        // And an OCSP request
        OCSPReqBuilder gen = new OCSPReqBuilder();
        gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), cacert,
                ocspTestCert.getSerialNumber()));
        Extension[] extensions = new Extension[1];
        extensions[0] = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false,
                new DEROctetString("123456789".getBytes()));
        gen.setRequestExtensions(new Extensions(extensions));
        X509CertificateHolder chain[] = new JcaX509CertificateHolder[2];
        chain[0] = new JcaX509CertificateHolder(ocspTestCert);
        chain[1] = new JcaX509CertificateHolder(cacert);
        gen.setRequestorName(chain[0].getSubject());
        OCSPReq req = gen.build(new BufferingContentSigner(new JcaContentSignerBuilder("SHA1withRSA")
                .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(keys.getPrivate()), 20480), chain);
        // Send the request and receive a singleResponse
        SingleResp[] singleResps = helper.sendOCSPPost(req.getEncoded(), "123456789",
                OCSPResponseStatus.SUCCESSFUL, 200);
        assertEquals("Number of of SingResps should be 1.", 1, singleResps.length);
        SingleResp singleResp = singleResps[0];

        CertificateID certId = singleResp.getCertID();
        assertEquals("Serno in response does not match serno in request.", certId.getSerialNumber(),
                ocspTestCert.getSerialNumber());
        Object status = singleResp.getCertStatus();
        assertEquals("Status is not null (good)", null, status);

        // Try with an unsigned request, we should get a status code 5 back from the server (signature required)
        req = gen.build();
        // Send the request and receive a singleResponse, this response should have error code SIGNATURE_REQUIRED
        singleResps = helper.sendOCSPPost(req.getEncoded(), "123456789", OCSPResponseStatus.SIG_REQUIRED, 200);
        assertNull(singleResps);

        // sign with a keystore where the CA-certificate is not known
        KeyStore store = KeyStore.getInstance("PKCS12", "BC");
        ByteArrayInputStream fis = new ByteArrayInputStream(ks3);
        store.load(fis, "foo123".toCharArray());
        Certificate[] certs = KeyTools.getCertChain(store, "privateKey");
        chain[0] = new JcaX509CertificateHolder((X509Certificate) certs[0]);
        chain[1] = new JcaX509CertificateHolder((X509Certificate) certs[1]);
        PrivateKey pk = (PrivateKey) store.getKey("privateKey", "foo123".toCharArray());
        req = gen.build(new BufferingContentSigner(new JcaContentSignerBuilder("SHA1withRSA").build(pk), 20480),
                chain);
        // Send the request and receive a singleResponse, this response should have error code UNAUTHORIZED (6)
        singleResps = helper.sendOCSPPost(req.getEncoded(), "123456789", OCSPResponseStatus.UNAUTHORIZED, 200);
        assertNull(singleResps);
    } finally {
        endEntityManagementSession.deleteUser(roleMgmgToken, END_ENTITY_NAME);
    }
    log.trace("<test01OcspGood()");
}

From source file:org.ejbca.core.protocol.scep.ScepResponseMessage.java

License:Open Source License

@Override
public boolean create() throws CertificateEncodingException, CRLException {
    boolean ret = false;
    try {/*from ww  w.  java2  s.  co m*/
        if (status.equals(ResponseStatus.SUCCESS)) {
            log.debug("Creating a STATUS_OK message.");
        } else {
            if (status.equals(ResponseStatus.FAILURE)) {
                log.debug("Creating a STATUS_FAILED message (or returning false).");
                if (failInfo.equals(FailInfo.WRONG_AUTHORITY)) {
                    return false;
                }
                if (failInfo.equals(FailInfo.INCORRECT_DATA)) {
                    return false;
                }
            } else {
                log.debug("Creating a STATUS_PENDING message.");
            }
        }

        CMSTypedData msg;
        // Create encrypted response if this is success and NOT a CRL response message
        if (status.equals(ResponseStatus.SUCCESS)) {

            CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();
            // Add the issued certificate to the signed portion of the CMS (as signer, degenerate case)
            List<X509Certificate> certList = new ArrayList<X509Certificate>();
            if (cert != null) {
                log.debug("Adding certificates to response message");
                certList.add((X509Certificate) cert);
                // Add the CA cert, it's optional but Cisco VPN client complains if it isn't there
                if (includeCACert) {
                    if (caCert != null) {
                        // If we have an explicit CAcertificate
                        log.debug("Including explicitly set CA certificate in SCEP response.");
                        certList.add((X509Certificate) caCert);
                    } else {
                        // If we don't have an explicit caCert, we think that the signCert is the CA cert
                        // If we have an explicit caCert, the signCert is probably the RA certificate, and we don't include that one
                        log.debug("Including message signer certificate in SCEP response.");
                        certList.add((X509Certificate) signCertChain.iterator().next());
                    }
                }
            }
            // Create the signed CMS message to be contained inside the envelope
            // this message does not contain any message, and no signerInfo
            CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
            gen.addCertificates(new CollectionStore(CertTools.convertToX509CertificateHolder(certList)));
            if (crl != null) {
                gen.addCRL(new JcaX509CRLHolder((X509CRL) crl));
            }

            CMSSignedData s = gen.generate(new CMSAbsentContent(), false);

            // Envelope the CMS message
            if (recipientKeyInfo != null) {
                try {
                    X509Certificate rec = (X509Certificate) CertTools.getCertfromByteArray(recipientKeyInfo);
                    log.debug("Added recipient information - issuer: '" + CertTools.getIssuerDN(rec)
                            + "', serno: '" + CertTools.getSerialNumberAsString(rec));
                    edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(rec)
                            .setProvider(BouncyCastleProvider.PROVIDER_NAME));
                } catch (CertificateParsingException e) {
                    throw new IllegalArgumentException("Can not decode recipients self signed certificate!", e);
                }
            } else {
                edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator((X509Certificate) cert)
                        .setProvider(BouncyCastleProvider.PROVIDER_NAME));
            }
            try {
                JceCMSContentEncryptorBuilder jceCMSContentEncryptorBuilder = new JceCMSContentEncryptorBuilder(
                        SMIMECapability.dES_CBC).setProvider(BouncyCastleProvider.PROVIDER_NAME);
                CMSEnvelopedData ed = edGen.generate(new CMSProcessableByteArray(s.getEncoded()),
                        jceCMSContentEncryptorBuilder.build());
                if (log.isDebugEnabled()) {
                    log.debug("Enveloped data is " + ed.getEncoded().length + " bytes long");
                }
                msg = new CMSProcessableByteArray(ed.getEncoded());
            } catch (IOException e) {
                throw new IllegalStateException("Unexpected IOException caught", e);
            }
        } else {
            // Create an empty message here
            //msg = new CMSProcessableByteArray("PrimeKey".getBytes());
            msg = new CMSProcessableByteArray(new byte[0]);
        }

        // Create the outermost signed data
        CMSSignedDataGenerator gen1 = new CMSSignedDataGenerator();

        // add authenticated attributes...status, transactionId, sender- and recipientNonce and more...
        Hashtable<ASN1ObjectIdentifier, Attribute> attributes = new Hashtable<ASN1ObjectIdentifier, Attribute>();
        ASN1ObjectIdentifier oid;
        Attribute attr;
        DERSet value;

        // Message type (certrep)
        oid = new ASN1ObjectIdentifier(ScepRequestMessage.id_messageType);
        value = new DERSet(new DERPrintableString("3"));
        attr = new Attribute(oid, value);
        attributes.put(attr.getAttrType(), attr);

        // TransactionId
        if (transactionId != null) {
            oid = new ASN1ObjectIdentifier(ScepRequestMessage.id_transId);
            log.debug("Added transactionId: " + transactionId);
            value = new DERSet(new DERPrintableString(transactionId));
            attr = new Attribute(oid, value);
            attributes.put(attr.getAttrType(), attr);
        }

        // status
        oid = new ASN1ObjectIdentifier(ScepRequestMessage.id_pkiStatus);
        value = new DERSet(new DERPrintableString(status.getStringValue()));
        attr = new Attribute(oid, value);
        attributes.put(attr.getAttrType(), attr);

        if (status.equals(ResponseStatus.FAILURE)) {
            oid = new ASN1ObjectIdentifier(ScepRequestMessage.id_failInfo);
            log.debug("Added failInfo: " + failInfo.getValue());
            value = new DERSet(new DERPrintableString(failInfo.getValue()));
            attr = new Attribute(oid, value);
            attributes.put(attr.getAttrType(), attr);
        }

        // senderNonce
        if (senderNonce != null) {
            oid = new ASN1ObjectIdentifier(ScepRequestMessage.id_senderNonce);
            log.debug("Added senderNonce: " + senderNonce);
            value = new DERSet(new DEROctetString(Base64.decode(senderNonce.getBytes())));
            attr = new Attribute(oid, value);
            attributes.put(attr.getAttrType(), attr);
        }

        // recipientNonce
        if (recipientNonce != null) {
            oid = new ASN1ObjectIdentifier(ScepRequestMessage.id_recipientNonce);
            log.debug("Added recipientNonce: " + recipientNonce);
            value = new DERSet(new DEROctetString(Base64.decode(recipientNonce.getBytes())));
            attr = new Attribute(oid, value);
            attributes.put(attr.getAttrType(), attr);
        }

        // Add our signer info and sign the message
        Certificate cacert = signCertChain.iterator().next();
        log.debug("Signing SCEP message with cert: " + CertTools.getSubjectDN(cacert));
        String signatureAlgorithmName = AlgorithmTools.getAlgorithmNameFromDigestAndKey(digestAlg,
                signKey.getAlgorithm());
        try {
            ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithmName)
                    .setProvider(provider).build(signKey);
            JcaDigestCalculatorProviderBuilder calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder()
                    .setProvider(BouncyCastleProvider.PROVIDER_NAME);
            JcaSignerInfoGeneratorBuilder builder = new JcaSignerInfoGeneratorBuilder(
                    calculatorProviderBuilder.build());
            builder.setSignedAttributeGenerator(
                    new DefaultSignedAttributeTableGenerator(new AttributeTable(attributes)));
            gen1.addSignerInfoGenerator(builder.build(contentSigner, (X509Certificate) cacert));
        } catch (OperatorCreationException e) {
            throw new IllegalStateException("BouncyCastle failed in creating signature provider.", e);
        }
        // The un-encoded response message itself
        final CMSSignedData signedData = gen1.generate(msg, true);
        try {
            responseMessage = signedData.getEncoded();
        } catch (IOException e) {
            throw new IllegalStateException("Unexpected IOException caught.", e);
        }
        if (responseMessage != null) {
            ret = true;
        }
    } catch (CMSException e) {
        log.error("Error creating CMS message: ", e);
    }

    return ret;
}

From source file:org.ejbca.ui.cli.ca.CaImportCaCertCommandTest.java

License:Open Source License

@Before
public void setUp() throws Exception {
    temp = File.createTempFile("chain", ".pem");

    caInitCommand = new CaInitCommand();

    caImportCaCertCommand = new CaImportCACertCommand();
    CaTestCase.removeTestCA(CA_NAME);//from w ww.j  a  v  a  2s.co m

    // Create a handmade External CA
    KeyPair keys = KeyTools.genKeys("1024", "RSA");
    X509Certificate externalCACert = CertTools.genSelfCert("CN=External CA", 365, null, keys.getPrivate(),
            keys.getPublic(), AlgorithmConstants.SIGALG_SHA1_WITH_RSA, true);

    ArrayList<Certificate> mylist = new ArrayList<Certificate>();
    mylist.add(externalCACert);
    FileOutputStream fos = new FileOutputStream(temp);
    fos.write(CertTools.getPemFromCertificateChain(mylist));
    fos.close();
    SIGNED_BY_EXTERNAL_ARGS[SIGNED_BY_EXTERNAL_ARGS.length - 1] = temp.getAbsolutePath();
    assertEquals(CommandResult.SUCCESS, caInitCommand.execute(SIGNED_BY_EXTERNAL_ARGS));
    CAInfo cainfo = caSession.getCAInfo(admin, CA_NAME);
    assertNotNull("CA signed by external CA was not created.", cainfo);
    assertEquals(
            "Creating a CA signed by an external CA should initially create it in status 'waiting for certificate response'",
            CAConstants.CA_WAITING_CERTIFICATE_RESPONSE, cainfo.getStatus());

    // Read the generated CSR, requires knowledge of what filename it creates
    byte[] bytes = FileTools.readFiletoBuffer(CA_NAME + "_csr.der");
    PKCS10RequestMessage msg = new PKCS10RequestMessage(bytes);
    // Create a new certificate with the subjectDN and publicKey from the request
    Date firstDate = new Date();
    Date lastDate = new Date();
    lastDate.setTime(lastDate.getTime() + (365 * (24 * 60 * 60 * 1000)));
    byte[] serno = new byte[8];
    Random random = new Random();
    random.setSeed(firstDate.getTime());
    random.nextBytes(serno);
    final SubjectPublicKeyInfo pkinfo = SubjectPublicKeyInfo
            .getInstance(msg.getRequestPublicKey().getEncoded());
    X509v3CertificateBuilder certbuilder = new X509v3CertificateBuilder(
            CertTools.stringToBcX500Name(externalCACert.getSubjectDN().toString()), new BigInteger(serno).abs(),
            firstDate, lastDate, CertTools.stringToBcX500Name(msg.getRequestDN()), pkinfo);
    BasicConstraints bc = new BasicConstraints(true);
    certbuilder.addExtension(Extension.basicConstraints, true, bc);
    X509KeyUsage ku = new X509KeyUsage(X509KeyUsage.keyCertSign + X509KeyUsage.cRLSign);
    certbuilder.addExtension(Extension.keyUsage, true, ku);
    final ContentSigner signer = new BufferingContentSigner(new JcaContentSignerBuilder("SHA1WithRSA")
            .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(keys.getPrivate()), 20480);
    final X509CertificateHolder certHolder = certbuilder.build(signer);
    cert = CertTools.getCertfromByteArray(certHolder.getEncoded(), X509Certificate.class);

}

From source file:org.ejbca.ui.cli.ca.CaImportCRLCommand.java

License:Open Source License

@Override
public CommandResult execute(ParameterContainer parameters) {
    log.trace(">execute()");
    CryptoProviderTools.installBCProvider();

    try {//w w w . j  a  va  2s. c  o  m
        // Parse arguments
        final String caname = parameters.get(CA_NAME_KEY);
        final String crl_file = parameters.get(CRL_FILE_KEY);
        final String operationsMode = parameters.get(OPERATION_KEY);
        final boolean strict = operationsMode.equalsIgnoreCase(STRICT_OP);
        final boolean adaptive = operationsMode.equalsIgnoreCase(ADAPTIVE_OP);
        if (!strict && !adaptive && !operationsMode.equalsIgnoreCase(LENIENT_OP)) {
            //None of the above.
            log.error("Operations mode must be one of " + STRICT_OP + ", " + LENIENT_OP + " or " + ADAPTIVE_OP
                    + ".");
            return CommandResult.CLI_FAILURE;
        }
        // Fetch CA and related info
        final CAInfo cainfo = getCAInfo(getAuthenticationToken(), caname);
        final X509Certificate cacert = (X509Certificate) cainfo.getCertificateChain().iterator().next();
        final String issuer = CertTools.stringToBCDNString(cacert.getSubjectDN().toString());
        log.info("CA: " + issuer);
        // Read the supplied CRL and verify that it is issued by the specified CA
        final X509CRL x509crl = (X509CRL) CertTools.getCertificateFactory()
                .generateCRL(new FileInputStream(crl_file));
        if (!x509crl.getIssuerX500Principal().equals(cacert.getSubjectX500Principal())) {
            throw new IOException("CRL wasn't issued by this CA");
        }
        x509crl.verify(cacert.getPublicKey());
        int crl_no = CrlExtensions.getCrlNumber(x509crl).intValue();
        log.info("Processing CRL #" + crl_no);
        int miss_count = 0; // Number of certs not already in database
        int revoked = 0; // Number of certs activly revoked by this algorithm
        int already_revoked = 0; // Number of certs already revoked in database and ignored in non-strict mode
        final String missing_user_name = MISSING_USERNAME_PREFIX + caname;
        @SuppressWarnings("unchecked")
        Set<X509CRLEntry> entries = (Set<X509CRLEntry>) x509crl.getRevokedCertificates();
        if (entries != null) {
            for (final X509CRLEntry entry : entries) {
                final BigInteger serialNr = entry.getSerialNumber();
                final String serialHex = serialNr.toString(16).toUpperCase();
                final String username = EjbRemoteHelper.INSTANCE
                        .getRemoteSession(CertificateStoreSessionRemote.class)
                        .findUsernameByCertSerno(serialNr, issuer);
                // If this certificate exists and has an assigned username, we keep using that. Otherwise we create this coupling to a user.
                if (username == null) {
                    log.info("Certificate '" + serialHex + "' missing in the database");
                    if (strict) {
                        throw new IOException(
                                "Aborted! Running in strict mode and is missing certificate in database.");
                    }
                    miss_count++;
                    if (!adaptive) {
                        continue;
                    }
                    final Date time = new Date(); // time from which certificate is valid
                    final KeyPair key_pair = KeyTools.genKeys("2048", AlgorithmConstants.KEYALGORITHM_RSA);

                    final SubjectPublicKeyInfo pkinfo = new SubjectPublicKeyInfo(
                            (ASN1Sequence) ASN1Primitive.fromByteArray(key_pair.getPublic().getEncoded()));
                    final X500Name dnName = new X500Name(
                            "CN=Dummy Missing in Imported CRL, serialNumber=" + serialHex);
                    final Date notAfter = new Date(time.getTime() + 1000L * 60 * 60 * 24 * 365 * 10); // 10 years of life
                    final X509v3CertificateBuilder certbuilder = new X509v3CertificateBuilder(
                            X500Name.getInstance(cacert.getSubjectX500Principal().getEncoded()), serialNr, time,
                            notAfter, dnName, pkinfo);
                    final ContentSigner signer = new BufferingContentSigner(
                            new JcaContentSignerBuilder("SHA1withRSA")
                                    .setProvider(BouncyCastleProvider.PROVIDER_NAME)
                                    .build(key_pair.getPrivate()),
                            20480);
                    final X509CertificateHolder certHolder = certbuilder.build(signer);
                    final X509Certificate certificate = (X509Certificate) CertTools
                            .getCertfromByteArray(certHolder.getEncoded());

                    final String fingerprint = CertTools.getFingerprintAsString(certificate);
                    // We add all certificates that does not have a user already to "missing_user_name"
                    final EndEntityInformation missingUserEndEntityInformation = EjbRemoteHelper.INSTANCE
                            .getRemoteSession(EndEntityAccessSessionRemote.class)
                            .findUser(getAuthenticationToken(), missing_user_name);
                    if (missingUserEndEntityInformation == null) {
                        // Add the user and change status to REVOKED
                        log.debug("Loading/updating user " + missing_user_name);
                        final EndEntityInformation userdataNew = new EndEntityInformation(missing_user_name,
                                CertTools.getSubjectDN(certificate), cainfo.getCAId(), null, null,
                                EndEntityConstants.STATUS_NEW, new EndEntityType(EndEntityTypes.ENDUSER),
                                SecConst.EMPTY_ENDENTITYPROFILE,
                                CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, null, null,
                                SecConst.TOKEN_SOFT_BROWSERGEN, SecConst.NO_HARDTOKENISSUER, null);
                        userdataNew.setPassword("foo123");
                        EjbRemoteHelper.INSTANCE.getRemoteSession(EndEntityManagementSessionRemote.class)
                                .addUser(getAuthenticationToken(), userdataNew, false);
                        log.info("User '" + missing_user_name + "' has been added.");
                        EjbRemoteHelper.INSTANCE.getRemoteSession(EndEntityManagementSessionRemote.class)
                                .setUserStatus(getAuthenticationToken(), missing_user_name,
                                        EndEntityConstants.STATUS_REVOKED);
                        log.info("User '" + missing_user_name + "' has been updated.");
                    }
                    EjbRemoteHelper.INSTANCE.getRemoteSession(CertificateStoreSessionRemote.class)
                            .storeCertificate(getAuthenticationToken(), certificate, missing_user_name,
                                    fingerprint, CertificateConstants.CERT_ACTIVE,
                                    CertificateConstants.CERTTYPE_ENDENTITY,
                                    CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, null,
                                    new Date().getTime());
                    log.info("Dummy certificate  '" + serialHex + "' has been stored.");
                }
                // This check will not catch a certificate with status CertificateConstants.CERT_ARCHIVED
                if (!strict && EjbRemoteHelper.INSTANCE.getRemoteSession(CertificateStoreSessionRemote.class)
                        .isRevoked(issuer, serialNr)) {
                    log.info("Certificate '" + serialHex + "' is already revoked");
                    already_revoked++;
                    continue;
                }
                log.info("Revoking '" + serialHex + "' " + "(" + serialNr.toString() + ")");
                try {
                    int reason = getCRLReasonValue(entry);
                    log.info("Reason code: " + reason);
                    EjbRemoteHelper.INSTANCE.getRemoteSession(EndEntityManagementSessionRemote.class)
                            .revokeCert(getAuthenticationToken(), serialNr, entry.getRevocationDate(), issuer,
                                    reason, false);
                    revoked++;
                } catch (AlreadyRevokedException e) {
                    already_revoked++;
                    log.warn("Failed to revoke '" + serialHex
                            + "'. (Status might be 'Archived'.) Error message was: " + e.getMessage());
                }
            }
        } // if (entries != null)
        if (EjbRemoteHelper.INSTANCE.getRemoteSession(CrlStoreSessionRemote.class).getLastCRLNumber(issuer,
                false) < crl_no) {
            EjbRemoteHelper.INSTANCE.getRemoteSession(CrlStoreSessionRemote.class).storeCRL(
                    getAuthenticationToken(), x509crl.getEncoded(), CertTools.getFingerprintAsString(cacert),
                    crl_no, issuer, x509crl.getThisUpdate(), x509crl.getNextUpdate(), -1);
        } else {
            if (strict) {
                throw new IOException("CRL #" + crl_no + " or higher is already in the database");
            }
        }
        log.info("\nSummary:\nRevoked " + revoked + " certificates");
        if (already_revoked > 0) {
            log.info(already_revoked + " certificates were already revoked");
        }
        if (miss_count > 0) {
            log.info("There were " + miss_count
                    + (adaptive ? " dummy certificates added to" : " certificates missing in")
                    + " the database");
        }
        log.info("CRL #" + crl_no + " stored in the database");
    } catch (Exception e) {
        //FIXME: This is all kinds of suboptimal.
        log.info("Error: " + e.getMessage());
        return CommandResult.FUNCTIONAL_FAILURE;
    }
    log.trace("<execute()");
    return CommandResult.SUCCESS;
}

From source file:org.ejbca.ui.cli.ca.CaInitCommandTest.java

License:Open Source License

/** Test happy path for creating a CA signed by an external CA. */
@Test//from  w  w w.j  a  v  a2s .  c om
public void testCASignedByExternal() throws Exception {
    // Create a handmade External CA
    KeyPair keys = KeyTools.genKeys("1024", "RSA");
    X509Certificate externalCACert = CertTools.genSelfCert("CN=External CA", 365, null, keys.getPrivate(),
            keys.getPublic(), AlgorithmConstants.SIGALG_SHA1_WITH_RSA, true);
    final String fp1 = CertTools.getFingerprintAsString(externalCACert);
    String fp2 = null;
    File temp = File.createTempFile("chain", ".pem");
    File csr = new File(CA_NAME + "_csr.der");
    File certfile = new File(CA_NAME + "_cert.der");
    try {
        ArrayList<Certificate> mylist = new ArrayList<Certificate>();
        mylist.add(externalCACert);
        FileOutputStream fos = new FileOutputStream(temp);
        fos.write(CertTools.getPemFromCertificateChain(mylist));
        fos.close();
        SIGNED_BY_EXTERNAL_ARGS[SIGNED_BY_EXTERNAL_ARGS.length - 1] = temp.getAbsolutePath();
        assertEquals(CommandResult.SUCCESS, caInitCommand.execute(SIGNED_BY_EXTERNAL_ARGS));
        CAInfo cainfo = caSession.getCAInfo(admin, CA_NAME);
        assertNotNull("CA signed by external CA was not created.", cainfo);
        assertEquals(
                "Creating a CA signed by an external CA should initially create it in status 'waiting for certificate response'",
                CAConstants.CA_WAITING_CERTIFICATE_RESPONSE, cainfo.getStatus());

        // Read the generated CSR, requires knowledge of what filename it creates
        byte[] bytes = FileTools.readFiletoBuffer(CA_NAME + "_csr.der");
        PKCS10RequestMessage msg = new PKCS10RequestMessage(bytes);
        // Create a new certificate with the subjectDN and publicKey from the request
        Date firstDate = new Date();
        Date lastDate = new Date();
        lastDate.setTime(lastDate.getTime() + (365 * (24 * 60 * 60 * 1000)));
        byte[] serno = new byte[8];
        Random random = new Random();
        random.setSeed(firstDate.getTime());
        random.nextBytes(serno);
        final SubjectPublicKeyInfo pkinfo = new SubjectPublicKeyInfo(
                (ASN1Sequence) ASN1Primitive.fromByteArray(msg.getRequestPublicKey().getEncoded()));
        X509v3CertificateBuilder certbuilder = new X509v3CertificateBuilder(
                CertTools.stringToBcX500Name(externalCACert.getSubjectDN().toString()),
                new java.math.BigInteger(serno).abs(), firstDate, lastDate,
                CertTools.stringToBcX500Name(msg.getRequestDN()), pkinfo);
        BasicConstraints bc = new BasicConstraints(true);
        certbuilder.addExtension(Extension.basicConstraints, true, bc);
        X509KeyUsage ku = new X509KeyUsage(X509KeyUsage.keyCertSign + X509KeyUsage.cRLSign);
        certbuilder.addExtension(Extension.keyUsage, true, ku);
        final ContentSigner signer = new BufferingContentSigner(new JcaContentSignerBuilder("SHA1WithRSA")
                .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(keys.getPrivate()), 20480);
        final X509CertificateHolder certHolder = certbuilder.build(signer);
        final X509Certificate cert = (X509Certificate) CertTools.getCertfromByteArray(certHolder.getEncoded());
        fp2 = CertTools.getFingerprintAsString(cert);
        // Now we have issued a certificate, import it
        mylist = new ArrayList<Certificate>();
        mylist.add(cert);
        fos = new FileOutputStream(certfile);
        fos.write(CertTools.getPemFromCertificateChain(mylist));
        fos.close();
        IMPORT_SIGNED_BY_EXTERNAL_ARGS[IMPORT_SIGNED_BY_EXTERNAL_ARGS.length - 1] = certfile.getAbsolutePath();
        assertEquals(CommandResult.SUCCESS, caImportCaCertCommand.execute(IMPORT_SIGNED_BY_EXTERNAL_ARGS));
        cainfo = caSession.getCAInfo(admin, CA_NAME);
        assertNotNull("CA signed by external CA does not exist.", cainfo);
        assertEquals(
                "importing a certificate to a CA signed by an external CA should result in status 'active'",
                CAConstants.CA_ACTIVE, cainfo.getStatus());
    } finally {
        temp.deleteOnExit();
        csr.deleteOnExit();
        certfile.deleteOnExit();
        // Clean up imported certificates from database
        internalCertStoreSession.removeCertificate(fp1);
        internalCertStoreSession.removeCertificate(fp2);
    }
}