Example usage for java.security.cert Certificate getPublicKey

List of usage examples for java.security.cert Certificate getPublicKey

Introduction

In this page you can find the example usage for java.security.cert Certificate getPublicKey.

Prototype

public abstract PublicKey getPublicKey();

Source Link

Document

Gets the public key from this certificate.

Usage

From source file:org.ejbca.core.protocol.cmp.CrmfKeyUpdateTest.java

/**
 * Sends a KeyUpdateRequest with a different key and the configurations is NOT to allow the use of the same keys. 
 * Successful operation is expected and a new certificate is received.
 * //from w w w .  j ava 2 s .c  o m
 * - Pre-configuration: Sets the operational mode to client mode (cmp.raoperationalmode=normal)
 * - Pre-configuration: Sets cmp.allowautomaticrenewal to 'true' and tests that the resetting of configuration has worked.
 * - Pre-configuration: Sets cmp.allowupdatewithsamekey to 'false'
 * - Creates a new user and obtains a certificate, cert, for this user. Tests whether obtaining the certificate was successful.
 * - Generates a CMP KeyUpdate Request and tests that such request has been created.
 * - Signs the CMP request using cert and attaches cert to the CMP request. Tests that the CMP request is still not null
 * - Sends the request using HTTP and receives a response.
 * - Examines the response:
 *       - Checks that the response is not empty or null
 *       - Checks that the protection algorithm is sha1WithRSAEncryption
 *       - Check that the signer is the expected CA
 *       - Verifies the response signature
 *       - Checks that the response's senderNonce is 16 bytes long
 *       - Checks that the request's senderNonce is the same as the response's recipientNonce
 *       - Checks that the request and the response has the same transactionID
 *       - Obtains the certificate from the response
 *       - Checks that the obtained certificate has the right subjectDN and issuerDN
 * 
 * @throws Exception
 */
@Test
public void test06UpdateWithDifferentKey() throws Exception {
    if (log.isTraceEnabled()) {
        log.trace(">test08UpdateWithDifferentKey");
    }

    this.cmpConfiguration.setRAMode(this.cmpAlias, false);
    this.cmpConfiguration.setKurAllowAutomaticUpdate(this.cmpAlias, true);
    this.cmpConfiguration.setKurAllowSameKey(this.cmpAlias, false);
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

    //--------------- create the user and issue his first certificate -----------------
    createUser(this.username, this.userDN.toString(), "foo123");
    KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
    final Certificate certificate;
    certificate = this.signSession.createCertificate(ADMIN, this.username, "foo123",
            new PublicKeyWrapper(keys.getPublic()));
    assertNotNull("Failed to create a test certificate", certificate);

    KeyPair newkeys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
    AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
    PKIMessage req = genRenewalReq(this.userDN, this.cacert, this.nonce, this.transid, newkeys, false, null,
            null, pAlg, new DEROctetString(this.nonce));
    assertNotNull("Failed to generate a CMP renewal request", req);
    CertReqMessages kur = (CertReqMessages) req.getBody().getContent();
    int reqId = kur.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();

    CMPCertificate[] extraCert = getCMPCert(certificate);
    req = CmpMessageHelper.buildCertBasedPKIProtection(req, extraCert, keys.getPrivate(),
            pAlg.getAlgorithm().getId(), "BC");
    assertNotNull(req);
    //******************************************''''''
    final Signature sig = Signature.getInstance(req.getHeader().getProtectionAlg().getAlgorithm().getId(),
            "BC");
    sig.initVerify(certificate.getPublicKey());
    sig.update(CmpMessageHelper.getProtectedBytes(req));
    boolean verified = sig.verify(req.getProtection().getBytes());
    assertTrue("Signing the message failed.", verified);
    //***************************************************

    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(req);
    byte[] ba = bao.toByteArray();
    // Send request and receive response
    byte[] resp = sendCmpHttp(ba, 200, this.cmpAlias);
    checkCmpResponseGeneral(resp, this.issuerDN, this.userDN, this.cacert, this.nonce, this.transid, true, null,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    X509Certificate cert = checkKurCertRepMessage(this.userDN, this.cacert, resp, reqId);
    assertNotNull("Failed to renew the certificate", cert);
    assertTrue("The new certificate's keys are incorrect.", cert.getPublicKey().equals(newkeys.getPublic()));
    assertFalse("The new certificate's keys are the same as the old certificate's keys.",
            cert.getPublicKey().equals(keys.getPublic()));

    if (log.isTraceEnabled()) {
        log.trace("<test08UpdateWithDifferentKey");
    }
}

From source file:org.ejbca.core.protocol.cmp.AuthenticationModulesTest.java

/**
 * Tests that EndEntityAuthentication module can be successfully used in client mode when the end entity's password is not stored in clear text.
 * //w ww.ja  v  a  2  s .  c  o  m
 * @throws Exception
 */
@Test
public void test21CrmfRequestClientModeEECNotClearPassword() throws Exception {
    this.cmpConfiguration.setAuthenticationModule(ALIAS, CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE);
    this.cmpConfiguration.setAuthenticationParameters(ALIAS, "-");
    this.cmpConfiguration.setRAMode(ALIAS, false);
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

    final X500Name testUserDN = new X500Name("CN=cmptestuser21,C=SE");
    final String testUsername = "cmptestuser21";
    String fingerprint = null;
    String fingerprint2 = null;
    try {
        KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
        AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);

        createUser(testUsername, testUserDN.toString(), "foo123", false, this.caid,
                SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
        Certificate cert = this.signSession.createCertificate(ADMIN, testUsername, "foo123",
                new PublicKeyWrapper(keys.getPublic()));
        fingerprint = CertTools.getFingerprintAsString(cert);

        //Edit the status of the user to NEW
        createUser(testUsername, testUserDN.toString(), "foo123", false, this.caid,
                SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
        PKIMessage msg = genCertReq(issuerDN, testUserDN, keys, this.cacert, this.nonce, this.transid, false,
                null, null, null, null, pAlg, null);
        assertNotNull("Generating CrmfRequest failed.", msg);
        CMPCertificate[] extraCert = getCMPCert(cert);
        msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, keys.getPrivate(),
                pAlg.getAlgorithm().getId(), "BC");
        assertNotNull(msg);
        //******************************************''''''
        final Signature sig = Signature.getInstance(msg.getHeader().getProtectionAlg().getAlgorithm().getId(),
                "BC");
        sig.initVerify(cert.getPublicKey());
        sig.update(CmpMessageHelper.getProtectedBytes(msg));
        boolean verified = sig.verify(msg.getProtection().getBytes());
        assertTrue("Signing the message failed.", verified);
        //***************************************************

        final ByteArrayOutputStream bao = new ByteArrayOutputStream();
        final DEROutputStream out = new DEROutputStream(bao);
        out.writeObject(msg);
        final byte[] ba = bao.toByteArray();

        // Send request and receive response
        final byte[] resp = sendCmpHttp(ba, 200, ALIAS);
        CertReqMessages ir = (CertReqMessages) msg.getBody().getContent();
        Certificate cert2 = checkCmpCertRepMessage(testUserDN, this.cacert, resp,
                ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue());
        assertNotNull("CrmfRequest did not return a certificate", cert2);
        fingerprint2 = CertTools.getFingerprintAsString(cert2);
    } finally {
        try {
            this.endEntityManagementSession.revokeAndDeleteUser(ADMIN, testUsername, ReasonFlags.unused);
        } catch (Exception e) {// do nothing
        }

        this.internalCertStoreSession.removeCertificate(fingerprint);
        this.internalCertStoreSession.removeCertificate(fingerprint2);
    }
}

From source file:org.ejbca.core.protocol.cmp.AuthenticationModulesTest.java

/** Test CMP initial request against EJBCA CMP in client mode (operationmode=normal) using End Entity certificate signature authentication, 
 * i.e. the request is signed by a certificate of the same end entity making the request, and this signature is used for authenticating the end entity.
 * Test:// w  ww .j  a  va 2  s  . co  m
 * - Request signed by a fake certificate, i.e. one that is not in the database (FAIL)
 * - Request signed by a certificate that beloongs to another user (FAIL)
 * - Request signed by a proper certificate but where user status is not NEW (FAIL)
 * - Request signed by a proper, but revoked certificate (FAIL)
 * - A working request signed by a proper, unrevoked certificate and user status is NEW (SUCCESS)
 * 
 * @throws Exception on some errors
 */
@Test
public void test18CrmfReqClientModeEESignature() throws Exception {
    this.cmpConfiguration.setAuthenticationModule(ALIAS, CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE);
    this.cmpConfiguration.setAuthenticationParameters(ALIAS, "-");
    this.cmpConfiguration.setRAMode(ALIAS, false);
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

    final X500Name testUserDN = new X500Name("CN=cmptestuser16,C=SE");
    final String testUsername = "cmptestuser16";
    final String otherUserDN = "CN=cmptestotheruser16,C=SE";
    final String otherUsername = "cmptestotheruser16";
    String fingerprint = null;
    String fingerprint2 = null;
    String fingerprint3 = null;
    try {
        KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
        KeyPair fakeKeys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
        createUser(testUsername, testUserDN.toString(), "foo123", true, this.caid,
                SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
        // A real certificate that can be used to sign the message
        Certificate cert = this.signSession.createCertificate(ADMIN, testUsername, "foo123",
                new PublicKeyWrapper(keys.getPublic()));
        fingerprint = CertTools.getFingerprintAsString(cert);
        // A fake certificate that should not be valid
        Certificate fakeCert = CertTools.genSelfCert(testUserDN.toString(), 30, null, fakeKeys.getPrivate(),
                fakeKeys.getPublic(), AlgorithmConstants.SIGALG_SHA1_WITH_RSA, false);

        // Step 1 sign with fake certificate, should not be valid as end entity authentication
        {
            AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
            PKIMessage msg = genCertReq(issuerDN, testUserDN, keys, this.cacert, this.nonce, this.transid,
                    false, null, null, null, null, pAlg, null);
            assertNotNull("Generating CrmfRequest failed.", msg);
            CMPCertificate[] extraCert = getCMPCert(fakeCert);
            msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, fakeKeys.getPrivate(),
                    pAlg.getAlgorithm().getId(), "BC");
            assertNotNull(msg);
            //******************************************''''''
            final Signature sig = Signature
                    .getInstance(msg.getHeader().getProtectionAlg().getAlgorithm().getId(), "BC");
            sig.initVerify(fakeCert.getPublicKey());
            sig.update(CmpMessageHelper.getProtectedBytes(msg));
            boolean verified = sig.verify(msg.getProtection().getBytes());
            assertTrue("Signing the message failed.", verified);
            //***************************************************

            final ByteArrayOutputStream bao = new ByteArrayOutputStream();
            final DEROutputStream out = new DEROutputStream(bao);
            out.writeObject(msg);
            final byte[] ba = bao.toByteArray();
            // Send request and receive response
            final byte[] resp = sendCmpHttp(ba, 200, ALIAS);
            // This should have failed
            checkCmpResponseGeneral(resp, issuerDN, testUserDN, this.cacert,
                    msg.getHeader().getSenderNonce().getOctets(),
                    msg.getHeader().getTransactionID().getOctets(), false, null,
                    PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
            ASN1InputStream inputStream = new ASN1InputStream(new ByteArrayInputStream(resp));
            PKIMessage respObject = PKIMessage.getInstance(inputStream.readObject());
            try {
                assertNotNull(respObject);
                PKIBody body = respObject.getBody();
                assertEquals(23, body.getType());
                ErrorMsgContent err = (ErrorMsgContent) body.getContent();
                String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
                String expectedErrMsg = "The certificate attached to the PKIMessage in the extraCert field could not be found in the database.";
                assertEquals(expectedErrMsg, errMsg);
            } finally {
                inputStream.close();
            }
        }
        // Step 2, sign the request with a certificate that does not belong to the user
        {
            KeyPair otherKeys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
            createUser(otherUsername, otherUserDN, "foo123", true, this.caid, SecConst.EMPTY_ENDENTITYPROFILE,
                    CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
            // A real certificate that can be used to sign the message
            Certificate othercert = this.signSession.createCertificate(ADMIN, otherUsername, "foo123",
                    new PublicKeyWrapper(otherKeys.getPublic()));
            fingerprint2 = CertTools.getFingerprintAsString(cert);
            AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
            PKIMessage msg = genCertReq(issuerDN, testUserDN, keys, this.cacert, this.nonce, this.transid,
                    false, null, null, null, null, pAlg, null);
            assertNotNull("Generating CrmfRequest failed.", msg);
            CMPCertificate[] extraCert = getCMPCert(othercert);
            msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, otherKeys.getPrivate(),
                    pAlg.getAlgorithm().getId(), "BC");
            assertNotNull(msg);
            //******************************************''''''
            final Signature sig = Signature
                    .getInstance(msg.getHeader().getProtectionAlg().getAlgorithm().getId(), "BC");
            sig.initVerify(othercert.getPublicKey());
            sig.update(CmpMessageHelper.getProtectedBytes(msg));
            boolean verified = sig.verify(msg.getProtection().getBytes());
            assertTrue("Signing the message failed.", verified);
            //***************************************************

            final ByteArrayOutputStream bao = new ByteArrayOutputStream();
            final DEROutputStream out = new DEROutputStream(bao);
            out.writeObject(msg);
            final byte[] ba = bao.toByteArray();
            // Send request and receive response
            final byte[] resp = sendCmpHttp(ba, 200, ALIAS);
            // This should have failed
            checkCmpResponseGeneral(resp, issuerDN, testUserDN, this.cacert,
                    msg.getHeader().getSenderNonce().getOctets(),
                    msg.getHeader().getTransactionID().getOctets(), false, null,
                    PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
            ASN1InputStream inputStream = new ASN1InputStream(new ByteArrayInputStream(resp));
            try {
                PKIMessage respObject = PKIMessage.getInstance(inputStream.readObject());
                assertNotNull(respObject);
                PKIBody body = respObject.getBody();
                assertEquals(23, body.getType());
                ErrorMsgContent err = (ErrorMsgContent) body.getContent();
                String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
                String expectedErrMsg = "The End Entity certificate attached to the PKIMessage in the extraCert field does not belong to user '"
                        + testUsername + "'";
                assertEquals(expectedErrMsg, errMsg);
            } finally {
                inputStream.close();
            }
        }

        // Step 3 sign with the real certificate, but user status is not NEW
        AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
        PKIMessage msg = genCertReq(issuerDN, testUserDN, keys, this.cacert, this.nonce, this.transid, false,
                null, null, null, null, pAlg, null);
        assertNotNull("Generating CrmfRequest failed.", msg);
        CMPCertificate[] extraCert = getCMPCert(cert);
        msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, keys.getPrivate(),
                pAlg.getAlgorithm().getId(), "BC");
        assertNotNull(msg);
        //******************************************''''''
        final Signature sig = Signature.getInstance(msg.getHeader().getProtectionAlg().getAlgorithm().getId(),
                "BC");
        sig.initVerify(cert.getPublicKey());
        sig.update(CmpMessageHelper.getProtectedBytes(msg));
        boolean verified = sig.verify(msg.getProtection().getBytes());
        assertTrue("Signing the message failed.", verified);
        //***************************************************

        final ByteArrayOutputStream bao = new ByteArrayOutputStream();
        final DEROutputStream out = new DEROutputStream(bao);
        out.writeObject(msg);
        final byte[] ba = bao.toByteArray();
        // Send request and receive response
        final byte[] resp = sendCmpHttp(ba, 200, ALIAS);
        checkCmpResponseGeneral(resp, issuerDN, testUserDN, this.cacert,
                msg.getHeader().getSenderNonce().getOctets(), msg.getHeader().getTransactionID().getOctets(),
                false, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        // This should have failed
        ASN1InputStream inputStream = new ASN1InputStream(new ByteArrayInputStream(resp));
        try {
            PKIMessage respObject = PKIMessage.getInstance(inputStream.readObject());
            assertNotNull(respObject);
            PKIBody body = respObject.getBody();
            assertEquals(23, body.getType());
            ErrorMsgContent err = (ErrorMsgContent) body.getContent();
            String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
            String expectedErrMsg = "Got request with status GENERATED (40), NEW, FAILED or INPROCESS required: cmptestuser16.";
            assertEquals(expectedErrMsg, errMsg);

            // Step 4 now set status to NEW, and a clear text password, then it should finally work
            createUser(testUsername, testUserDN.toString(), "randompasswordhere", true, this.caid,
                    SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
            // Send request and receive response
            final byte[] resp2 = sendCmpHttp(ba, 200, ALIAS);
            CertReqMessages ir = (CertReqMessages) msg.getBody().getContent();
            Certificate cert2 = checkCmpCertRepMessage(testUserDN, this.cacert, resp2,
                    ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue());
            assertNotNull("CrmfRequest did not return a certificate", cert2);
            fingerprint3 = CertTools.getFingerprintAsString(cert2);

            // Step 5, revoke the certificate and try again
            {
                this.certificateStoreSession.setRevokeStatus(ADMIN, cert,
                        RevokedCertInfo.REVOCATION_REASON_CESSATIONOFOPERATION, null);
                final byte[] resp3 = sendCmpHttp(ba, 200, ALIAS);
                // This should have failed
                checkCmpResponseGeneral(resp, issuerDN, testUserDN, this.cacert,
                        msg.getHeader().getSenderNonce().getOctets(),
                        msg.getHeader().getTransactionID().getOctets(), false, null,
                        PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
                ASN1InputStream inputStream3 = new ASN1InputStream(new ByteArrayInputStream(resp3));
                try {
                    PKIMessage respObject3 = PKIMessage.getInstance(inputStream3.readObject());
                    assertNotNull(respObject);
                    PKIBody body3 = respObject3.getBody();
                    assertEquals(23, body3.getType());
                    err = (ErrorMsgContent) body3.getContent();
                    String errMsg3 = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
                    String expectedErrMsg3 = "The certificate attached to the PKIMessage in the extraCert field is not active.";
                    assertEquals(expectedErrMsg3, errMsg3);
                } finally {
                    inputStream3.close();
                }
            }
        } finally {
            inputStream.close();
        }

    } finally {
        try {
            this.endEntityManagementSession.revokeAndDeleteUser(ADMIN, testUsername, ReasonFlags.unused);
        } catch (Exception e) {// do nothing
        }

        try {
            this.endEntityManagementSession.revokeAndDeleteUser(ADMIN, otherUsername, ReasonFlags.unused);
        } catch (Exception e) {// do nothing
        }

        this.internalCertStoreSession.removeCertificate(fingerprint);
        this.internalCertStoreSession.removeCertificate(fingerprint2);
        this.internalCertStoreSession.removeCertificate(fingerprint3);
    }
}

From source file:org.ejbca.core.ejb.ca.caadmin.CAAdminSessionBean.java

/**
 * Check if subject certificate is signed by issuer certificate. Used in
 * //from www . ja v a  2s. co  m
 * @see #upgradeFromOldCAKeyStore(Admin, String, byte[], char[], char[], String). This method does a lazy check: if signature verification failed
 *      for any reason that prevent verification, e.g. signature algorithm not supported, method returns false. Author: Marco Ferrante
 * 
 * @param subject Subject certificate
 * @param issuer Issuer certificate
 * @return true if subject certificate is signed by issuer certificate
 * @throws java.lang.Exception
 */
private boolean verifyIssuer(Certificate subject, Certificate issuer) {
    try {
        PublicKey issuerKey = issuer.getPublicKey();
        subject.verify(issuerKey);
        return true;
    } catch (java.security.GeneralSecurityException e) {
        return false;
    }
}

From source file:org.ejbca.core.protocol.cmp.AuthenticationModulesTest.java

@Test
public void test05EECrmfReq() throws NoSuchAlgorithmException, EjbcaException, IOException, Exception {
    this.cmpConfiguration.setAuthenticationModule(ALIAS, CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE);
    this.cmpConfiguration.setAuthenticationParameters(ALIAS, "TestCA");
    this.cmpConfiguration.setRAMode(ALIAS, true);
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

    final X500Name testUserDN = new X500Name("CN=cmptestuser5,C=SE");
    final String testUsername = "cmptestuser5";
    String fingerprint = null;/*w  w w.  j av a 2  s  .  c o m*/
    String fingerprint2 = null;
    AuthenticationToken admToken = null;
    Certificate admCert = null;
    try {
        KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);

        AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);
        PKIMessage msg = genCertReq(issuerDN, testUserDN, keys, this.cacert, this.nonce, this.transid, false,
                null, null, null, null, pAlg, new DEROctetString(this.nonce));
        assertNotNull("Generating CrmfRequest failed.", msg);

        KeyPair admkeys = KeyTools.genKeys("512", "RSA");
        admToken = createAdminToken(admkeys, testUsername, testUserDN.toString(), this.caid,
                SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
        admCert = getCertFromCredentials(admToken);
        fingerprint = CertTools.getFingerprintAsString(admCert);

        CMPCertificate[] extraCert = getCMPCert(admCert);
        msg = CmpMessageHelper.buildCertBasedPKIProtection(msg, extraCert, admkeys.getPrivate(),
                pAlg.getAlgorithm().getId(), "BC");
        assertNotNull(msg);
        //******************************************''''''
        final Signature sig = Signature.getInstance(msg.getHeader().getProtectionAlg().getAlgorithm().getId(),
                "BC");
        sig.initVerify(admCert.getPublicKey());
        sig.update(CmpMessageHelper.getProtectedBytes(msg));
        boolean verified = sig.verify(msg.getProtection().getBytes());
        assertTrue("Signing the message failed.", verified);
        //***************************************************

        final ByteArrayOutputStream bao = new ByteArrayOutputStream();
        final DEROutputStream out = new DEROutputStream(bao);
        out.writeObject(msg);
        final byte[] ba = bao.toByteArray();
        // Send request and receive response
        final byte[] resp = sendCmpHttp(ba, 200, ALIAS);
        checkCmpResponseGeneral(resp, issuerDN, testUserDN, this.cacert,
                msg.getHeader().getSenderNonce().getOctets(), msg.getHeader().getTransactionID().getOctets(),
                true, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        CertReqMessages ir = (CertReqMessages) msg.getBody().getContent();
        Certificate cert2 = checkCmpCertRepMessage(testUserDN, this.cacert, resp,
                ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue());
        assertNotNull("CrmfRequest did not return a certificate", cert2);
        fingerprint2 = CertTools.getFingerprintAsString(cert2);
    } finally {
        removeAuthenticationToken(admToken, admCert, testUsername); // also removes testUsername
        this.internalCertStoreSession.removeCertificate(fingerprint);
        this.internalCertStoreSession.removeCertificate(fingerprint2);
    }
}

From source file:org.ejbca.core.ejb.ca.caadmin.CAAdminSessionBean.java

@Override
public void importCAFromKeyStore(AuthenticationToken admin, String caname, byte[] p12file, String keystorepass,
        String privkeypass, String privateSignatureKeyAlias, String privateEncryptionKeyAlias) {
    try {// ww  w. j  a v a 2  s . co m
        // check authorization
        if (!accessSession.isAuthorizedNoLogging(admin, StandardRules.ROLE_ROOT.resource())) {
            String msg = intres.getLocalizedMessage("caadmin.notauthorizedtocreateca", caname);
            Map<String, Object> details = new LinkedHashMap<String, Object>();
            details.put("msg", msg);
            auditSession.log(EventTypes.ACCESS_CONTROL, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE,
                    admin.toString(), null, null, null, details);
        }
        // load keystore
        java.security.KeyStore keystore = KeyStore.getInstance("PKCS12", "BC");
        keystore.load(new java.io.ByteArrayInputStream(p12file), keystorepass.toCharArray());
        // Extract signature keys
        if (privateSignatureKeyAlias == null || !keystore.isKeyEntry(privateSignatureKeyAlias)) {
            throw new Exception("Alias \"" + privateSignatureKeyAlias + "\" not found.");
        }
        Certificate[] signatureCertChain = KeyTools.getCertChain(keystore, privateSignatureKeyAlias);
        if (signatureCertChain.length < 1) {
            String msg = "Cannot load certificate chain with alias " + privateSignatureKeyAlias;
            log.error(msg);
            throw new Exception(msg);
        }
        Certificate caSignatureCertificate = (Certificate) signatureCertChain[0];
        PublicKey p12PublicSignatureKey = caSignatureCertificate.getPublicKey();
        PrivateKey p12PrivateSignatureKey = null;
        p12PrivateSignatureKey = (PrivateKey) keystore.getKey(privateSignatureKeyAlias,
                privkeypass.toCharArray());
        log.debug("ImportSignatureKeyAlgorithm=" + p12PrivateSignatureKey.getAlgorithm());

        // Extract encryption keys
        PrivateKey p12PrivateEncryptionKey = null;
        PublicKey p12PublicEncryptionKey = null;
        Certificate caEncryptionCertificate = null;
        if (privateEncryptionKeyAlias != null) {
            if (!keystore.isKeyEntry(privateEncryptionKeyAlias)) {
                throw new Exception("Alias \"" + privateEncryptionKeyAlias + "\" not found.");
            }
            Certificate[] encryptionCertChain = KeyTools.getCertChain(keystore, privateEncryptionKeyAlias);
            if (encryptionCertChain.length < 1) {
                String msg = "Cannot load certificate chain with alias " + privateEncryptionKeyAlias;
                log.error(msg);
                throw new Exception(msg);
            }
            caEncryptionCertificate = (Certificate) encryptionCertChain[0];
            p12PrivateEncryptionKey = (PrivateKey) keystore.getKey(privateEncryptionKeyAlias,
                    privkeypass.toCharArray());
            p12PublicEncryptionKey = caEncryptionCertificate.getPublicKey();
        }
        importCAFromKeys(admin, caname, keystorepass, signatureCertChain, p12PublicSignatureKey,
                p12PrivateSignatureKey, p12PrivateEncryptionKey, p12PublicEncryptionKey);
    } catch (Exception e) {
        String detailsMsg = intres.getLocalizedMessage("caadmin.errorimportca", caname, "PKCS12",
                e.getMessage());
        auditSession.log(EjbcaEventTypes.CA_IMPORT, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE,
                admin.toString(), null, null, null, detailsMsg);
        throw new EJBException(e);
    }
}

From source file:org.ejbca.core.ejb.ca.caadmin.CAAdminSessionBean.java

@Override
public void restoreCAKeyStore(AuthenticationToken authenticationToken, String caname, byte[] p12file,
        String keystorepass, String privkeypass, String privateSignatureKeyAlias,
        String privateEncryptionKeyAlias) {
    if (log.isTraceEnabled()) {
        log.trace(">restoreCAKeyStore");
    }/*from  w w  w .  ja  va2 s .com*/
    try {
        // check authorization
        if (!accessSession.isAuthorizedNoLogging(authenticationToken, StandardRules.ROLE_ROOT.resource())) {
            final String detailsMsg = intres.getLocalizedMessage("caadmin.notauthorizedtorestorecatoken",
                    caname);
            auditSession.log(EventTypes.ACCESS_CONTROL, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE,
                    authenticationToken.toString(), null, null, null, detailsMsg);
        }
        CA thisCa = caSession.getCAForEdit(authenticationToken, caname);
        final CAToken thisCAToken = thisCa.getCAToken();
        CryptoToken cryptoToken = cryptoTokenSession.getCryptoToken(thisCAToken.getCryptoTokenId());
        if (cryptoToken != null) {
            throw new Exception("CA already has an existing CryptoToken reference: " + cryptoToken.getId());
        }
        // load keystore from input
        KeyStore keystore = KeyStore.getInstance("PKCS12", "BC");
        keystore.load(new ByteArrayInputStream(p12file), keystorepass.toCharArray());
        // Extract signature keys
        if (privateSignatureKeyAlias == null || !keystore.isKeyEntry(privateSignatureKeyAlias)) {
            throw new Exception("Alias \"" + privateSignatureKeyAlias + "\" not found.");
        }
        Certificate[] signatureCertChain = KeyTools.getCertChain(keystore, privateSignatureKeyAlias);
        if (signatureCertChain.length < 1) {
            String msg = "Cannot load certificate chain with alias " + privateSignatureKeyAlias;
            log.error(msg);
            throw new Exception(msg);
        }
        Certificate caSignatureCertificate = (Certificate) signatureCertChain[0];
        PublicKey p12PublicSignatureKey = caSignatureCertificate.getPublicKey();
        PrivateKey p12PrivateSignatureKey = null;
        p12PrivateSignatureKey = (PrivateKey) keystore.getKey(privateSignatureKeyAlias,
                privkeypass.toCharArray());

        // Extract encryption keys
        PrivateKey p12PrivateEncryptionKey = null;
        PublicKey p12PublicEncryptionKey = null;
        Certificate caEncryptionCertificate = null;
        if (privateEncryptionKeyAlias != null) {
            if (!keystore.isKeyEntry(privateEncryptionKeyAlias)) {
                throw new Exception("Alias \"" + privateEncryptionKeyAlias + "\" not found.");
            }
            Certificate[] encryptionCertChain = KeyTools.getCertChain(keystore, privateEncryptionKeyAlias);
            if (encryptionCertChain.length < 1) {
                String msg = "Cannot load certificate chain with alias " + privateEncryptionKeyAlias;
                log.error(msg);
                throw new Exception(msg);
            }
            caEncryptionCertificate = (Certificate) encryptionCertChain[0];
            p12PrivateEncryptionKey = (PrivateKey) keystore.getKey(privateEncryptionKeyAlias,
                    privkeypass.toCharArray());
            p12PublicEncryptionKey = caEncryptionCertificate.getPublicKey();
        } else {
            throw new Exception("Missing encryption key");
        }

        // Sign something to see that we are restoring the right private signature key
        String testSigAlg = (String) AlgorithmTools
                .getSignatureAlgorithms(thisCa.getCACertificate().getPublicKey()).iterator().next();
        if (testSigAlg == null) {
            testSigAlg = "SHA1WithRSA";
        }
        // Sign with imported private key
        byte[] input = "Test data...".getBytes();
        Signature signature = Signature.getInstance(testSigAlg, "BC");
        signature.initSign(p12PrivateSignatureKey);
        signature.update(input);
        byte[] signed = signature.sign();
        // Verify with public key from CA certificate
        signature = Signature.getInstance(testSigAlg, "BC");
        signature.initVerify(thisCa.getCACertificate().getPublicKey());
        signature.update(input);
        if (!signature.verify(signed)) {
            throw new Exception("Could not use private key for verification. Wrong p12-file for this CA?");
        }
        // Import the keys and save to database
        CAToken catoken = importKeysToCAToken(authenticationToken, keystorepass, thisCAToken.getProperties(),
                p12PrivateSignatureKey, p12PublicSignatureKey, p12PrivateEncryptionKey, p12PublicEncryptionKey,
                signatureCertChain, thisCa.getCAId());
        thisCa.setCAToken(catoken);
        // Finally save the CA
        caSession.editCA(authenticationToken, thisCa, true);
        // Log
        final String detailsMsg = intres.getLocalizedMessage("caadmin.restoredcakeystore",
                Integer.valueOf(thisCa.getCAId()));
        auditSession.log(EjbcaEventTypes.CA_RESTORETOKEN, EventStatus.SUCCESS, ModuleTypes.CA,
                ServiceTypes.CORE, authenticationToken.toString(), String.valueOf(thisCa.getCAId()), null, null,
                detailsMsg);
    } catch (Exception e) {
        final String detailsMsg = intres.getLocalizedMessage("caadmin.errorrestorecakeystore", caname, "PKCS12",
                e.getMessage());
        auditSession.log(EjbcaEventTypes.CA_RESTORETOKEN, EventStatus.FAILURE, ModuleTypes.CA,
                ServiceTypes.CORE, authenticationToken.toString(), null, null, null, detailsMsg);
        throw new EJBException(e);
    }
    if (log.isTraceEnabled()) {
        log.trace("<restoreCAKeyStore");
    }
}

From source file:org.ejbca.core.ejb.ca.caadmin.CAAdminSessionBean.java

@Override
public void importCAFromHSM(AuthenticationToken authenticationToken, String caname,
        Certificate[] signatureCertChain, String catokenpassword, String catokenclasspath,
        String catokenproperties) throws CryptoTokenOfflineException, CryptoTokenAuthenticationFailedException,
        IllegalCryptoTokenException, AuthorizationDeniedException, CAExistsException, CAOfflineException,
        NoSuchSlotException {//w  w  w  .j a  v a 2  s .c  o  m
    Certificate cacert = signatureCertChain[0];
    int caId = StringTools.strip(CertTools.getSubjectDN(cacert)).hashCode();
    Properties caTokenProperties = CAToken.getPropertiesFromString(catokenproperties);
    // Create the CryptoToken
    int cryptoTokenId = createCryptoTokenWithUniqueName(authenticationToken, "ImportedCryptoToken" + caId,
            PKCS11CryptoToken.class.getName(), caTokenProperties, null, catokenpassword.toCharArray());
    final CAToken catoken = new CAToken(cryptoTokenId, caTokenProperties);
    // Set a lot of properties on the crypto token

    // If this is a CVC CA we need to find out the sequence
    String signatureAlgorithm = AlgorithmTools.getSignatureAlgorithm(cacert);
    String sequence = CAToken.DEFAULT_KEYSEQUENCE;
    if (cacert instanceof CardVerifiableCertificate) {
        CardVerifiableCertificate cvccacert = (CardVerifiableCertificate) cacert;
        log.debug("Getting sequence from holderRef in CV certificate.");
        try {
            sequence = cvccacert.getCVCertificate().getCertificateBody().getHolderReference().getSequence();
        } catch (NoSuchFieldException e) {
            log.error("Can not get sequence from holderRef in CV certificate, using default sequence.");
        }
    }
    log.debug("Setting sequence " + sequence);
    catoken.setKeySequence(sequence);
    log.debug("Setting default sequence format " + StringTools.KEY_SEQUENCE_FORMAT_NUMERIC);
    catoken.setKeySequenceFormat(StringTools.KEY_SEQUENCE_FORMAT_NUMERIC);
    catoken.setSignatureAlgorithm(signatureAlgorithm);
    // Encryption keys must be RSA still
    String encryptionAlgorithm = AlgorithmTools.getEncSigAlgFromSigAlg(signatureAlgorithm);
    catoken.setEncryptionAlgorithm(encryptionAlgorithm);
    // Identify the key algorithms for extended CA services, OCSP, XKMS, CMS
    String keyAlgorithm = AlgorithmTools.getKeyAlgorithm(cacert.getPublicKey());
    String keySpecification = AlgorithmTools.getKeySpecification(cacert.getPublicKey());
    if (keyAlgorithm == null || keyAlgorithm == AlgorithmConstants.KEYALGORITHM_RSA) {
        keyAlgorithm = AlgorithmConstants.KEYALGORITHM_RSA;
        keySpecification = "2048";
    }
    // Do the general import
    importCA(authenticationToken, caname, catokenpassword, signatureCertChain, catoken, keyAlgorithm,
            keySpecification);
}

From source file:org.ejbca.core.ejb.ca.caadmin.CAAdminSessionBean.java

@Override
public void receiveResponse(AuthenticationToken authenticationToken, int caid, ResponseMessage responsemessage,
        Collection<?> cachain, String nextKeyAlias)
        throws AuthorizationDeniedException, CertPathValidatorException, EjbcaException, CesecoreException {
    if (log.isTraceEnabled()) {
        log.trace(">receiveResponse: " + caid);
    }//from   w  w  w . j  a  va  2 s  .  co  m
    if (!accessSession.isAuthorizedNoLogging(authenticationToken, AccessRulesConstants.REGULAR_RENEWCA)) {
        final String detailsMsg = intres.getLocalizedMessage("caadmin.notauthorizedtocertresp",
                Integer.valueOf(caid));
        auditSession.log(EventTypes.ACCESS_CONTROL, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE,
                authenticationToken.toString(), String.valueOf(caid), null, null, detailsMsg);
    }
    try {
        final CA ca = caSession.getCAForEdit(authenticationToken, caid);
        if (!(responsemessage instanceof X509ResponseMessage)) {
            String msg = intres.getLocalizedMessage("caadmin.errorcertrespillegalmsg",
                    responsemessage != null ? responsemessage.getClass().getName() : "null");
            log.info(msg);
            throw new EjbcaException(msg);
        }
        final Certificate cacert = ((X509ResponseMessage) responsemessage).getCertificate();
        // Receiving a certificate for an internal CA will transform it into an externally signed CA
        if (ca.getSignedBy() != CAInfo.SIGNEDBYEXTERNALCA) {
            ca.setSignedBy(CAInfo.SIGNEDBYEXTERNALCA);
        }
        // Check that CA DN is equal to the certificate response.
        if (!CertTools.getSubjectDN(cacert).equals(CertTools.stringToBCDNString(ca.getSubjectDN()))) {
            String msg = intres.getLocalizedMessage("caadmin.errorcertrespwrongdn",
                    CertTools.getSubjectDN(cacert), ca.getSubjectDN());
            log.info(msg);
            throw new EjbcaException(msg);
        }
        List<Certificate> tmpchain = new ArrayList<Certificate>();
        tmpchain.add(cacert);

        Collection<Certificate> reqchain = null;
        if (cachain != null && cachain.size() > 0) {
            //  1. If we have a chain given as parameter, we will use that.
            reqchain = CertTools.createCertChain(cachain);
            log.debug("Using CA certificate chain from parameter of size: " + reqchain.size());
        } else {
            // 2. If no parameter is given we assume that the request chain was stored when the request was created.
            reqchain = ca.getRequestCertificateChain();
            if (reqchain == null) {
                // 3. Lastly, if that failed we'll check if the certificate chain in it's entirety already exists in the database. 
                reqchain = new ArrayList<Certificate>();
                Certificate issuer = certificateStoreSession
                        .findLatestX509CertificateBySubject(CertTools.getIssuerDN(cacert));
                if (issuer != null) {
                    reqchain.add(issuer);
                    while (!CertTools.isSelfSigned(issuer)) {
                        issuer = certificateStoreSession
                                .findLatestX509CertificateBySubject(CertTools.getIssuerDN(issuer));
                        if (issuer != null) {
                            reqchain.add(issuer);
                        } else {
                            String msg = intres.getLocalizedMessage("caadmin.errorincompleterequestchain", caid,
                                    ca.getSubjectDN());
                            log.info(msg);
                            throw new CertPathValidatorException(msg);
                        }
                    }
                }
                if (reqchain.size() == 0) {
                    String msg = intres.getLocalizedMessage("caadmin.errornorequestchain", caid,
                            ca.getSubjectDN());
                    log.info(msg);
                    throw new CertPathValidatorException(msg);
                }

            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Using pre-stored CA certificate chain.");
                }
            }
        }
        log.debug("Picked up request certificate chain of size: " + reqchain.size());
        tmpchain.addAll(reqchain);
        final List<Certificate> chain = CertTools.createCertChain(tmpchain);
        log.debug("Storing certificate chain of size: " + chain.size());
        // Before importing the certificate we want to make sure that the public key matches the CAs private key
        PublicKey caCertPublicKey = cacert.getPublicKey();
        // If it is a DV certificate signed by a CVCA, enrich the public key for EC parameters from the CVCA's certificate
        if (StringUtils.equals(cacert.getType(), "CVC")) {
            if (caCertPublicKey.getAlgorithm().equals("ECDSA")) {
                CardVerifiableCertificate cvccert = (CardVerifiableCertificate) cacert;
                try {
                    if (cvccert.getCVCertificate().getCertificateBody().getAuthorizationTemplate()
                            .getAuthorizationField().getAuthRole().isDV()) {
                        log.debug("Enriching DV public key with EC parameters from CVCA");
                        Certificate cvcacert = (Certificate) reqchain.iterator().next();
                        caCertPublicKey = KeyTools.getECPublicKeyWithParams(caCertPublicKey,
                                cvcacert.getPublicKey());
                    }
                } catch (InvalidKeySpecException e) {
                    log.debug("Strange CVCA certificate that we can't get the key from, continuing anyway...",
                            e);
                } catch (NoSuchFieldException e) {
                    log.debug("Strange DV certificate with no AutheorizationRole, continuing anyway...", e);
                }
            } else {
                log.debug("Key is not ECDSA, don't try to enrich with EC parameters.");
            }
        } else {
            log.debug("Cert is not CVC, no need to enrich with EC parameters.");
        }

        final CAToken catoken = ca.getCAToken();
        final CryptoToken cryptoToken = cryptoTokenSession.getCryptoToken(catoken.getCryptoTokenId());
        boolean activatedNextSignKey = false;
        if (nextKeyAlias != null) {
            try {
                if (log.isDebugEnabled()) {
                    log.debug("SubjectKeyId for CA cert public key: " + new String(
                            Hex.encode(KeyTools.createSubjectKeyId(caCertPublicKey).getKeyIdentifier())));
                    log.debug("SubjectKeyId for CA next public key: " + new String(Hex.encode(KeyTools
                            .createSubjectKeyId(cryptoToken.getPublicKey(nextKeyAlias)).getKeyIdentifier())));
                }
                KeyTools.testKey(cryptoToken.getPrivateKey(nextKeyAlias), caCertPublicKey,
                        cryptoToken.getSignProviderName());
            } catch (InvalidKeyException e) {
                throw new EjbcaException(ErrorCode.INVALID_KEY, e);
            }
            catoken.setNextCertSignKey(nextKeyAlias);
            catoken.activateNextSignKey();
            activatedNextSignKey = true;
        } else {
            // Since we don't specified the nextSignKey, we will just try the current or next CA sign key
            try {
                KeyTools.testKey(
                        cryptoToken.getPrivateKey(
                                catoken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN)),
                        caCertPublicKey, cryptoToken.getSignProviderName());
            } catch (Exception e1) {
                log.debug(
                        "The received certificate response does not match the CAs private signing key for purpose CAKEYPURPOSE_CERTSIGN, trying CAKEYPURPOSE_CERTSIGN_NEXT...");
                if (e1 instanceof InvalidKeyException) {
                    log.trace(e1);
                } else {
                    // If it's not invalid key, we want to see more of the error
                    log.debug("Error: ", e1);
                }
                try {
                    KeyTools.testKey(
                            cryptoToken.getPrivateKey(
                                    catoken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN_NEXT)),
                            caCertPublicKey, cryptoToken.getSignProviderName());
                    // This was OK, so we must also activate the next signing key when importing this certificate
                    catoken.activateNextSignKey();
                    activatedNextSignKey = true;
                } catch (Exception e2) {
                    log.debug(
                            "The received certificate response does not match the CAs private signing key for purpose CAKEYPURPOSE_CERTSIGN_NEXT either, giving up.");
                    if ((e2 instanceof InvalidKeyException) || (e2 instanceof IllegalArgumentException)) {
                        log.trace(e2);
                    } else {
                        // If it's not invalid key or missing authentication code, we want to see more of the error
                        log.debug("Error: ", e2);
                    }
                    throw new EjbcaException(ErrorCode.INVALID_KEY, e2);
                }
            }
        }
        if (activatedNextSignKey) {
            // Activated the next signing key(s) so generate audit log
            final Map<String, Object> details = new LinkedHashMap<String, Object>();
            details.put("msg", intres.getLocalizedMessage("catoken.activatednextkey", caid));
            details.put("certSignKey", catoken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN));
            details.put("crlSignKey", catoken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CRLSIGN));
            details.put("sequence", catoken.getKeySequence());
            auditSession.log(EventTypes.CA_KEYACTIVATE, EventStatus.SUCCESS, ModuleTypes.CA, ServiceTypes.CORE,
                    authenticationToken.toString(), String.valueOf(caid), null, null, details);
        }
        ca.setCAToken(catoken);
        ca.setCertificateChain(chain);

        // Set status to active, so we can sign certificates for the external services below.
        ca.setStatus(CAConstants.CA_ACTIVE);

        // activate External CA Services
        for (int type : ca.getExternalCAServiceTypes()) {
            try {
                ca.initExtendedService(cryptoToken, type, ca);
                final ExtendedCAServiceInfo info = ca.getExtendedCAServiceInfo(type);
                if (info instanceof BaseSigningCAServiceInfo) {
                    // Publish the extended service certificate, but only for active services
                    if (info.getStatus() == ExtendedCAServiceInfo.STATUS_ACTIVE) {
                        final List<Certificate> extcacertificate = new ArrayList<Certificate>();
                        extcacertificate.add(((BaseSigningCAServiceInfo) info).getCertificatePath().get(0));
                        publishCACertificate(authenticationToken, extcacertificate, ca.getCRLPublishers(),
                                ca.getSubjectDN());
                    }
                }
            } catch (Exception fe) {
                final String detailsMsg = intres.getLocalizedMessage("caadmin.errorcreatecaservice",
                        Integer.valueOf(caid));
                auditSession.log(EventTypes.CA_EDITING, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE,
                        authenticationToken.toString(), String.valueOf(caid), null, null, detailsMsg);
                throw new EJBException(fe);
            }
        }
        // Set expire time
        ca.setExpireTime(CertTools.getNotAfter(cacert));
        // Save CA
        caSession.editCA(authenticationToken, ca, true);
        // Publish CA Certificate
        publishCACertificate(authenticationToken, chain, ca.getCRLPublishers(), ca.getSubjectDN());
        // Create initial CRL
        publishingCrlSession.forceCRL(authenticationToken, caid);
        publishingCrlSession.forceDeltaCRL(authenticationToken, caid);
        // All OK
        String detailsMsg = intres.getLocalizedMessage("caadmin.certrespreceived", Integer.valueOf(caid));
        auditSession.log(EventTypes.CA_EDITING, EventStatus.SUCCESS, ModuleTypes.CA, ServiceTypes.CORE,
                authenticationToken.toString(), String.valueOf(caid), null, null, detailsMsg);
    } catch (CryptoTokenOfflineException e) {
        String msg = intres.getLocalizedMessage("caadmin.errorcertresp", Integer.valueOf(caid));
        log.info(msg);
        sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically
        throw e;
    } catch (CADoesntExistsException e) {
        String msg = intres.getLocalizedMessage("caadmin.errorcertresp", Integer.valueOf(caid));
        log.info(msg);
        sessionContext.setRollbackOnly(); // This is an application exception so it wont trigger a roll-back automatically
        throw e;
    } catch (CertificateEncodingException e) {
        String msg = intres.getLocalizedMessage("caadmin.errorcertresp", Integer.valueOf(caid));
        log.info(msg);
        throw new EjbcaException(e.getMessage());
    } catch (CertificateException e) {
        String msg = intres.getLocalizedMessage("caadmin.errorcertresp", Integer.valueOf(caid));
        log.info(msg);
        throw new EjbcaException(e.getMessage());
    } catch (InvalidAlgorithmParameterException e) {
        String msg = intres.getLocalizedMessage("caadmin.errorcertresp", Integer.valueOf(caid));
        log.info(msg);
        throw new EjbcaException(e.getMessage());
    } catch (NoSuchAlgorithmException e) {
        String msg = intres.getLocalizedMessage("caadmin.errorcertresp", Integer.valueOf(caid));
        log.info(msg);
        throw new EjbcaException(e.getMessage());
    } catch (NoSuchProviderException e) {
        String msg = intres.getLocalizedMessage("caadmin.errorcertresp", Integer.valueOf(caid));
        log.info(msg);
        throw new EjbcaException(e.getMessage());
    }
    if (log.isTraceEnabled()) {
        log.trace("<receiveResponse: " + caid);
    }
}