Example usage for org.bouncycastle.asn1.pkcs PKCSObjectIdentifiers sha1WithRSAEncryption

List of usage examples for org.bouncycastle.asn1.pkcs PKCSObjectIdentifiers sha1WithRSAEncryption

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.pkcs PKCSObjectIdentifiers sha1WithRSAEncryption.

Prototype

ASN1ObjectIdentifier sha1WithRSAEncryption

To view the source code for org.bouncycastle.asn1.pkcs PKCSObjectIdentifiers sha1WithRSAEncryption.

Click Source Link

Document

PKCS#1: 1.2.840.113549.1.1.5

Usage

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

License:Open Source License

/**
 * Test the error message returned when CMP request missing a signature in RA mode (operationmode=ra) and EndEntityCertificate authentication is configured. 
 * //from w w  w .  jav a 2  s . c  o  m
 * @throws Exception on some errors
 */
@Test
public void test20NoEECAuthentication() throws Exception {
    this.cmpConfiguration.setAuthenticationModule(ALIAS, CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE);
    this.cmpConfiguration.setAuthenticationParameters(ALIAS, "TestCA");
    this.cmpConfiguration.setRAMode(ALIAS, false);
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

    KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);

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

    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, USER_DN, 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 = "PKI Message is not athenticated properly. No PKI protection is found.";
        assertEquals(expectedErrMsg, errMsg);
    } finally {
        inputStream.close();
    }
}

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

License:Open Source License

/**
 * Tests that EndEntityAuthentication module can be successfully used in client mode when the end entity's password is not stored in clear text.
 * /*from   w  w w  .  j  ava  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

License:Open Source License

/**
 * Tests the possibility to use different signature algorithms in CMP requests and responses.
 * /*from  ww w  .ja  v  a 2s  . com*/
 * A CRMF request, signed using ECDSA with SHA1, is sent to a CA that uses RSA with SHA256 as signature algorithm.
 * The expected response is signed by RSA with SHA1.
 * 
 * @throws Exception
 */
@Test
public void test23EECAuthWithRSAandECDSA() throws Exception {
    log.trace(">test23EECAuthWithRSAandECDSA()");

    //-------------- Set the necessary configurations

    this.cmpConfiguration.setRAMode(ALIAS, true);
    this.cmpConfiguration.setRANameGenScheme(ALIAS, "DN");
    this.cmpConfiguration.setRANameGenParams(ALIAS, "CN");
    this.cmpConfiguration.setAuthenticationModule(ALIAS, CmpConfiguration.AUTHMODULE_ENDENTITY_CERTIFICATE);
    this.cmpConfiguration.setAuthenticationParameters(ALIAS, "TestCA");
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

    //---------------- Send a CMP initialization request
    AuthenticationToken admToken = null;
    final String testAdminDN = "CN=cmptestadmin,C=SE";
    final String testAdminName = "cmptestadmin";
    X509Certificate admCert = null;
    String fp = null, fp2 = null;
    try {
        KeyPair keys = KeyTools.genKeys("prime192v1", AlgorithmConstants.KEYALGORITHM_ECDSA);

        final X500Name userDN = new X500Name("CN=cmpmixuser");
        final byte[] _nonce = CmpMessageHelper.createSenderNonce();
        final byte[] _transid = CmpMessageHelper.createSenderNonce();
        final AlgorithmIdentifier pAlg = new AlgorithmIdentifier(X9ObjectIdentifiers.ecdsa_with_SHA1);
        PKIMessage req = genCertReq(issuerDN, userDN, keys, this.cacert, _nonce, _transid, false, null, null,
                null, null, pAlg, null);

        createUser(testAdminName, testAdminDN, "foo123", true, this.caid, SecConst.EMPTY_ENDENTITYPROFILE,
                CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
        KeyPair admkeys = KeyTools.genKeys("prime192v1", AlgorithmConstants.KEYALGORITHM_ECDSA);
        admToken = createAdminToken(admkeys, testAdminName, testAdminDN, this.caid,
                SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
        admCert = getCertFromCredentials(admToken);
        fp = CertTools.getFingerprintAsString(admCert);

        CMPCertificate[] extraCert = getCMPCert(admCert);
        req = CmpMessageHelper.buildCertBasedPKIProtection(req, extraCert, admkeys.getPrivate(),
                CMSSignedGenerator.DIGEST_SHA1, "BC");
        assertNotNull(req);

        CertReqMessages ir = (CertReqMessages) req.getBody().getContent();
        int reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();
        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, ALIAS);
        checkCmpResponseGeneral(resp, issuerDN, userDN, this.cacert, _nonce, _transid, true, null,
                PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        X509Certificate cert = checkCmpCertRepMessage(userDN, this.cacert, resp, reqId);
        fp2 = CertTools.getFingerprintAsString(cert);

    } finally {
        removeAuthenticationToken(admToken, admCert, testAdminName);
        this.endEntityManagementSession.revokeAndDeleteUser(ADMIN, "cmpmixuser", ReasonFlags.unused);
        this.internalCertStoreSession.removeCertificate(fp);
        this.internalCertStoreSession.removeCertificate(fp2);
    }
    log.trace("<test23EECAuthWithRSAandECDSA()");
}

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

License:Open Source License

/**
 * Sending a Crmf Request in RA mode. The request is authenticated using HMAC and is expected to contain the EndEntityProfile 'EMPTY' in the KeyId field.
 * The request should fail because specifying 'EMPTY' or 'ENDUSER' as the KeyId is not allowed in combination with RA mode and HMAC authentication module 
 * //from  ww  w.j  av  a2 s .  c  o m
 * The test is only done for HMAC and not EndEntityCertificate because in the later, the use of profiles can be restricted through Administrator privileges.
 * Other authentication modules are not used in RA mode
 * 
 * @throws Exception
 */
@Test
public void test24HMACUnacceptedKeyId() throws Exception {

    this.cmpConfiguration.setRAMode(ALIAS, true);
    this.cmpConfiguration.setAuthenticationModule(ALIAS, CmpConfiguration.AUTHMODULE_HMAC);
    this.cmpConfiguration.setAuthenticationParameters(ALIAS, "foo123hmac");
    this.cmpConfiguration.setRAEEProfile(ALIAS, "KeyId");
    this.cmpConfiguration.setRACertProfile(ALIAS, "ProfileDefault");
    this.cmpConfiguration.setRACAName(ALIAS, "TestCA");
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

    KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);

    PKIMessage msg = genCertReq(issuerDN, USER_DN, keys, this.cacert, this.nonce, this.transid, false, null,
            null, null, null, null, null);
    assertNotNull("Generating CrmfRequest failed.", msg);
    PKIMessage req = protectPKIMessage(msg, false, "foo123hmac", "EMPTY", 567);
    assertNotNull("Protecting PKIMessage with HMACPbe failed.", req);

    final ByteArrayOutputStream bao = new ByteArrayOutputStream();
    final DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(req);
    final byte[] ba = bao.toByteArray();
    // Send request and receive response
    final byte[] resp = sendCmpHttp(ba, 200, ALIAS);
    checkCmpResponseGeneral(resp, issuerDN, USER_DN, this.cacert, req.getHeader().getSenderNonce().getOctets(),
            req.getHeader().getTransactionID().getOctets(), false, null,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());

    ASN1InputStream inputStream = new ASN1InputStream(new ByteArrayInputStream(resp));
    try {
        PKIMessage respObject = PKIMessage.getInstance(inputStream.readObject());
        assertNotNull(respObject);

        final PKIBody body = respObject.getBody();
        assertEquals(23, body.getType());
        ErrorMsgContent err = (ErrorMsgContent) body.getContent();
        final String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
        final String expectedErrMsg = "Unaccepted KeyId 'EMPTY' in CMP request";
        assertEquals(expectedErrMsg, errMsg);
    } finally {
        inputStream.close();
    }
}

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

License:Open Source License

/**
 * This test sends a CmpConfirmMessage and expects a successful CmpConfirmResponse message
 * signed using the CA specified as recipient in the request.
 * @throws Exception/*from w  w w .  j  av  a 2 s  . co  m*/
 */
@Test
public void test01ConfRespSignedByRecepient() throws Exception {
    log.trace(">test01ConfRespSignedByRecepient");

    this.cmpConfiguration.setResponseProtection(cmpAlias, "signature");
    this.cmpConfiguration.setCMPDefaultCA(cmpAlias, "");
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

    byte[] nonce = CmpMessageHelper.createSenderNonce();
    byte[] transid = CmpMessageHelper.createSenderNonce();

    // Send a confirm message to the CA
    String hash = "foo123";
    PKIMessage confirm = genCertConfirm(userDN, this.cacert, nonce, transid, hash, 0);
    assertNotNull(confirm);
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(confirm);
    byte[] ba = bao.toByteArray();
    // Send request and receive response
    byte[] resp = sendCmpHttp(ba, 200, cmpAlias);
    checkCmpResponseGeneral(resp, this.testx509ca.getSubjectDN(), userDN, this.cacert, nonce, transid, true,
            null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    checkCmpPKIConfirmMessage(userDN, this.cacert, resp);

    log.trace("<test01ConfRespSignedByRecepient");
}

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

License:Open Source License

/**
 * This test sends a CmpConfirmMessage and expects a successful CmpConfirmResponse message
 * signed using the CA set in cmp.defaultca
 * @throws Exception// w  w  w.j av  a 2 s . c  om
 */
@Test
public void test02ConfRespSignedByDefaultCA() throws Exception {
    log.trace(">test02ConfRespSignedByDefaultCA");

    this.cmpConfiguration.setResponseProtection(cmpAlias, "signature");
    this.cmpConfiguration.setCMPDefaultCA(cmpAlias, this.testx509ca.getSubjectDN());
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

    byte[] nonce = CmpMessageHelper.createSenderNonce();
    byte[] transid = CmpMessageHelper.createSenderNonce();

    // Send a confirm message to the CA
    String hash = "foo123";
    // the parameter 'null' is to  generate a confirm request for a recipient that does not exist
    PKIMessage confirm = genCertConfirm(userDN, null, nonce, transid, hash, 0);
    assertNotNull(confirm);
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(confirm);
    byte[] ba = bao.toByteArray();
    // Send request and receive response
    byte[] resp = sendCmpHttp(ba, 200, cmpAlias);
    checkCmpResponseGeneral(resp, this.testx509ca.getSubjectDN(), userDN, this.cacert, nonce, transid, true,
            null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    checkCmpPKIConfirmMessage(userDN, this.cacert, resp);

    log.trace("<test02ConfRespSignedByDefaultCA");
}

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

License:Open Source License

/**
 * This test sends a CmpConfirmMessage and expects a successful CmpConfirmResponse message
 * protected with PBE using the global shared secret set as authentication module parameter 
 * in cmp.authenticationparameter.//from   ww  w. j  a  va 2 s. co  m
 * @throws Exception
 */
@Test
public void test03ConfRespPbeProtectedByGlobalSharedSecret() throws Exception {
    log.trace(">test03ConfRespPbeProtected");

    this.cmpConfiguration.setRAMode(cmpAlias, true);
    this.cmpConfiguration.setResponseProtection(cmpAlias, "pbe");
    this.cmpConfiguration.setCMPDefaultCA(cmpAlias, "");
    this.cmpConfiguration.setAuthenticationModule(cmpAlias, CmpConfiguration.AUTHMODULE_HMAC);
    this.cmpConfiguration.setAuthenticationParameters(cmpAlias, "password");
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

    byte[] nonce = CmpMessageHelper.createSenderNonce();
    byte[] transid = CmpMessageHelper.createSenderNonce();

    // Send a confirm message to the CA
    String hash = "foo123";
    PKIMessage confirm = genCertConfirm(userDN, this.cacert, nonce, transid, hash, 0);
    confirm = protectPKIMessage(confirm, false, "password", 567);
    assertNotNull(confirm);
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(confirm);
    byte[] ba = bao.toByteArray();
    // Send request and receive response
    byte[] resp = sendCmpHttp(ba, 200, cmpAlias);
    checkCmpResponseGeneral(resp, this.testx509ca.getSubjectDN(), userDN, this.cacert, nonce, transid, false,
            "password", PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    checkCmpPKIConfirmMessage(userDN, this.cacert, resp);

    log.trace("<test03ConfRespPbeProtected");
}

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

License:Open Source License

/**
 * This test sends a CmpConfirmMessage and expects a successful CmpConfirmResponse message
 * protected with PBE using the global shared secret set as authentication module parameter 
 * in cmp.authenticationparameter./*from  w  w w.  j a va 2  s  .  co m*/
 * @throws Exception
 */
@Test
public void test04ConfRespPbeProtectedByCACmpSecret() throws Exception {
    log.trace(">test03ConfRespPbeProtected");

    this.cmpConfiguration.setRAMode(cmpAlias, true);
    this.cmpConfiguration.setResponseProtection(cmpAlias, "pbe");
    this.cmpConfiguration.setCMPDefaultCA(cmpAlias, this.testx509ca.getSubjectDN());
    this.cmpConfiguration.setAuthenticationModule(cmpAlias, CmpConfiguration.AUTHMODULE_HMAC);
    this.cmpConfiguration.setAuthenticationParameters(cmpAlias, "-");
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

    byte[] nonce = CmpMessageHelper.createSenderNonce();
    byte[] transid = CmpMessageHelper.createSenderNonce();

    // Send a confirm message to the CA
    String hash = "foo123";
    PKIMessage confirm = genCertConfirm(userDN, this.cacert, nonce, transid, hash, 0);
    confirm = protectPKIMessage(confirm, false, "foo123", 567);
    assertNotNull(confirm);
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(confirm);
    byte[] ba = bao.toByteArray();
    // Send request and receive response
    byte[] resp = sendCmpHttp(ba, 200, cmpAlias);
    checkCmpResponseGeneral(resp, this.testx509ca.getSubjectDN(), userDN, this.cacert, nonce, transid, false,
            "foo123", PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    checkCmpPKIConfirmMessage(userDN, this.cacert, resp);

    log.trace("<test03ConfRespPbeProtected");
}

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

License:Open Source License

/**
 * Sends a certificate request message and verifies result. Sends a confirm message and verifies result. Sends a revocation message and verifies
 * result./*  www  .ja  v a  2s . co m*/
 */
private void testIssueConfirmRevoke(X509Certificate caCertificate, String pbeSecret, String keyId,
        boolean reverseIssuerDN) throws Exception {
    LOG.trace(">testIssueConfirmRevoke");

    this.cmpConfiguration.setAuthenticationModule(this.configAlias, CmpConfiguration.AUTHMODULE_HMAC);
    this.cmpConfiguration.setAuthenticationParameters(this.configAlias, pbeSecret);
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

    String issuerDN = CertTools.getSubjectDN(caCertificate);
    if (reverseIssuerDN) {
        issuerDN = CertTools.reverseDN(issuerDN);
    }

    // Generate and send certificate request
    byte[] nonce = CmpMessageHelper.createSenderNonce();
    byte[] transid = CmpMessageHelper.createSenderNonce();
    Date notBefore = new Date();
    Date notAfter = new Date(new Date().getTime() + 24 * 3600 * 1000);
    KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
    final X500Name subjectDN = new X500Name("CN=" + USERNAME);
    try {
        PKIMessage one = genCertReq(issuerDN, subjectDN, keys, caCertificate, nonce, transid, true, null,
                notBefore, notAfter, null, null, null);
        PKIMessage req = protectPKIMessage(one, false, pbeSecret, keyId, 567);
        assertNotNull("Request was not created properly.", req);
        CertReqMessages ir = (CertReqMessages) req.getBody().getContent();
        int reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        new DEROutputStream(bao).writeObject(req);
        byte[] ba = bao.toByteArray();
        byte[] resp = sendCmpHttp(ba, 200, this.configAlias);
        checkCmpResponseGeneral(resp, CertTools.getSubjectDN(caCertificate), subjectDN, caCertificate, nonce,
                transid, false, pbeSecret, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        X509Certificate cert = checkCmpCertRepMessage(subjectDN, caCertificate, resp, reqId);

        assertTrue("Failed to create user " + USERNAME, this.endEntityManagementSession.existsUser(USERNAME));

        // Send a confirm message to the CA
        String hash = "foo123";
        PKIMessage confirm = genCertConfirm(subjectDN, caCertificate, nonce, transid, hash, reqId);
        assertNotNull("Could not create confirmation message.", confirm);
        PKIMessage req1 = protectPKIMessage(confirm, false, pbeSecret, keyId, 567);
        bao = new ByteArrayOutputStream();
        new DEROutputStream(bao).writeObject(req1);
        ba = bao.toByteArray();
        resp = sendCmpHttp(ba, 200, this.configAlias);
        checkCmpResponseGeneral(resp, caCertificate.getSubjectX500Principal().getName(), subjectDN,
                caCertificate, nonce, transid, false, pbeSecret,
                PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        checkCmpPKIConfirmMessage(subjectDN, caCertificate, resp);

        // Now revoke the bastard using the CMPv1 reason code!
        PKIMessage rev = genRevReq(issuerDN, subjectDN, cert.getSerialNumber(), caCertificate, nonce, transid,
                false, null, null);
        PKIMessage revReq = protectPKIMessage(rev, false, pbeSecret, keyId, 567);
        assertNotNull("Could not create revocation message.", revReq);
        bao = new ByteArrayOutputStream();
        new DEROutputStream(bao).writeObject(revReq);
        ba = bao.toByteArray();
        resp = sendCmpHttp(ba, 200, this.configAlias);
        checkCmpResponseGeneral(resp, caCertificate.getSubjectX500Principal().getName(), subjectDN,
                caCertificate, nonce, transid, false, pbeSecret,
                PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        checkCmpRevokeConfirmMessage(caCertificate.getSubjectX500Principal().getName(), subjectDN,
                cert.getSerialNumber(), caCertificate, resp, true);
        int reason = this.certificateStoreSession.getStatus(CertTools.getSubjectDN(caCertificate),
                cert.getSerialNumber()).revocationReason;
        assertEquals("Certificate was not revoked with the right reason.",
                RevokedCertInfo.REVOCATION_REASON_KEYCOMPROMISE, reason);
        LOG.trace("<testIssueConfirmRevoke");
    } finally {
        this.endEntityManagementSession.deleteUser(ADMIN, USERNAME);
    }
}

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

License:Open Source License

/**
 * Sends a certificate request message and verifies result. Sends a confirm message and verifies result. Sends a revocation message and verifies
 * result. (If we save certificate data!)
 *//*w w w  .j a  va 2s .  c  o m*/
private void testIssueConfirmRevoke(boolean useCertReqHistory, boolean useUserStorage,
        boolean useCertificateStorage) throws Exception {
    LOG.trace(">testIssueConfirmRevoke");
    LOG.info("useCertReqHistory=" + useCertReqHistory + " useUserStorage=" + useUserStorage
            + " useCertificateStorage=" + useCertificateStorage);
    // Generate and send certificate request
    byte[] nonce = CmpMessageHelper.createSenderNonce();
    byte[] transid = CmpMessageHelper.createSenderNonce();
    Date notBefore = new Date();
    Date notAfter = new Date(new Date().getTime() + 24 * 3600 * 1000);
    KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
    String username = "cmpRaThrowAwayTestUser" + RND.nextLong(); // This is what we expect from the CMP configuration
    final X500Name subjectDN = new X500Name("CN=" + username);
    PKIMessage one = genCertReq(CertTools.getSubjectDN(this.caCertificate), subjectDN, keys, this.caCertificate,
            nonce, transid, true, null, notBefore, notAfter, null, null, null);
    PKIMessage req = protectPKIMessage(one, false, PBE_SECRET, "unusedKeyId", 567);
    assertNotNull("Request was not created properly.", req);
    CertReqMessages ir = (CertReqMessages) req.getBody().getContent();
    int reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    new DEROutputStream(bao).writeObject(req);
    byte[] resp = sendCmpHttp(bao.toByteArray(), 200, configAlias);
    checkCmpResponseGeneral(resp, CertTools.getSubjectDN(this.caCertificate), subjectDN, this.caCertificate,
            nonce, transid, false, PBE_SECRET, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    X509Certificate cert = checkCmpCertRepMessage(subjectDN, this.caCertificate, resp, reqId);
    assertTrue("Certificate history data was or wasn't stored: ", useCertReqHistory == (this.csrHistorySession
            .retrieveCertReqHistory(CertTools.getSerialNumber(cert), CertTools.getIssuerDN(cert)) != null));
    assertTrue("User data was or wasn't stored: ",
            useUserStorage == this.endEntityManagementSession.existsUser(username));
    assertTrue("Certificate data was or wasn't stored: ", useCertificateStorage == (this.certificateStoreSession
            .findCertificateByFingerprint(CertTools.getFingerprintAsString(cert)) != null));

    // Send a confirm message to the CA
    String hash = "foo123";
    PKIMessage confirm = genCertConfirm(subjectDN, this.caCertificate, nonce, transid, hash, reqId);
    assertNotNull("Could not create confirmation message.", confirm);
    PKIMessage req1 = protectPKIMessage(confirm, false, PBE_SECRET, "unusedKeyId", 567);
    bao = new ByteArrayOutputStream();
    new DEROutputStream(bao).writeObject(req1);
    resp = sendCmpHttp(bao.toByteArray(), 200, configAlias);
    checkCmpResponseGeneral(resp, CertTools.getSubjectDN(this.caCertificate), subjectDN, this.caCertificate,
            nonce, transid, false, PBE_SECRET, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    checkCmpPKIConfirmMessage(subjectDN, this.caCertificate, resp);

    // We only expect revocation to work if we store certificate data and user data
    // TODO: ECA-1916 should remove dependency on useUserStorage
    if (useCertificateStorage && useUserStorage) {
        // Now revoke the bastard using the CMPv1 reason code!
        PKIMessage rev = genRevReq(CertTools.getSubjectDN(this.caCertificate), subjectDN,
                cert.getSerialNumber(), this.caCertificate, nonce, transid, false, null, null);
        PKIMessage revReq = protectPKIMessage(rev, false, PBE_SECRET, "unusedKeyId", 567);
        assertNotNull("Could not create revocation message.", revReq);
        bao = new ByteArrayOutputStream();
        new DEROutputStream(bao).writeObject(revReq);
        resp = sendCmpHttp(bao.toByteArray(), 200, configAlias);
        checkCmpResponseGeneral(resp, CertTools.getSubjectDN(this.caCertificate), subjectDN, this.caCertificate,
                nonce, transid, false, PBE_SECRET, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        checkCmpRevokeConfirmMessage(CertTools.getSubjectDN(this.caCertificate), subjectDN,
                cert.getSerialNumber(), this.caCertificate, resp, true);
        int reason = this.certificateStoreSession.getStatus(CertTools.getSubjectDN(this.caCertificate),
                cert.getSerialNumber()).revocationReason;
        assertEquals("Certificate was not revoked with the right reason.",
                RevokedCertInfo.REVOCATION_REASON_KEYCOMPROMISE, reason);
    }
    // Clean up what we can
    if (useUserStorage) {
        this.endEntityManagementSession.deleteUser(ADMIN, username);
    }
    if (useCertReqHistory) {
        this.csrHistorySession.removeCertReqHistoryData(CertTools.getFingerprintAsString(cert));
    }
    LOG.trace("<testIssueConfirmRevoke");
}