Example usage for org.bouncycastle.asn1.x500 X500Name X500Name

List of usage examples for org.bouncycastle.asn1.x500 X500Name X500Name

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x500 X500Name X500Name.

Prototype

public X500Name(String dirName) 

Source Link

Usage

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

License:Open Source License

protected static void checkCmpResponseGeneral(byte[] retMsg, String issuerDN, X500Name userDN,
        Certificate cacert, byte[] senderNonce, byte[] transId, boolean signed, String pbeSecret,
        String expectedSignAlg)//from   w  w  w .  j ava 2 s . co m
        throws IOException, InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException {
    assertNotNull("No response from server.", retMsg);
    assertTrue("Response was of 0 length.", retMsg.length > 0);
    boolean pbe = (pbeSecret != null);
    //
    // Parse response message
    //
    ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(retMsg));
    PKIMessage respObject = null;
    try {
        respObject = PKIMessage.getInstance(asn1InputStream.readObject());
    } finally {
        asn1InputStream.close();
    }
    assertNotNull(respObject);

    // The signer, i.e. the CA, check it's the right CA
    PKIHeader header = respObject.getHeader();

    // Check that the message is signed with the correct digest alg
    if (StringUtils.isEmpty(expectedSignAlg)) {
        expectedSignAlg = PKCSObjectIdentifiers.sha1WithRSAEncryption.getId();
    }
    // if cacert is ECDSA we should expect an ECDSA signature alg
    //if (AlgorithmTools.getSignatureAlgorithm(cacert).contains("ECDSA")) {
    //    expectedSignAlg = X9ObjectIdentifiers.ecdsa_with_SHA1.getId();
    //} else if(AlgorithmTools.getSignatureAlgorithm(cacert).contains("ECGOST3410")) {
    //    expectedSignAlg = CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001.getId();
    //} else if(AlgorithmTools.getSignatureAlgorithm(cacert).contains("DSTU4145")) {
    //    expectedSignAlg = (new ASN1ObjectIdentifier(CesecoreConfiguration.getOidDstu4145())).getId();
    //}
    if (signed) {
        AlgorithmIdentifier algId = header.getProtectionAlg();
        assertNotNull(
                "Protection algorithm was null when expecting a signed response, this was propably an unprotected error message: "
                        + header.getFreeText(),
                algId);
        assertEquals(expectedSignAlg, algId.getAlgorithm().getId());
    }
    if (pbe) {
        AlgorithmIdentifier algId = header.getProtectionAlg();
        assertNotNull(
                "Protection algorithm was null when expecting a pbe protected response, this was propably an unprotected error message: "
                        + header.getFreeText(),
                algId);
        assertEquals("Protection algorithm id: " + algId.getAlgorithm().getId(),
                CMPObjectIdentifiers.passwordBasedMac.getId(), algId.getAlgorithm().getId()); // 1.2.840.113549.1.1.5 - SHA-1 with RSA Encryption
    }

    // Check that the signer is the expected CA    
    assertEquals(header.getSender().getTagNo(), 4);

    X500Name expissuer = new X500Name(issuerDN);
    X500Name actissuer = new X500Name(header.getSender().getName().toString());
    assertEquals(expissuer, actissuer);
    if (signed) {
        // Verify the signature
        byte[] protBytes = CmpMessageHelper.getProtectedBytes(respObject);
        DERBitString bs = respObject.getProtection();
        Signature sig;
        try {
            sig = Signature.getInstance(expectedSignAlg, "BC");
            sig.initVerify(cacert);
            sig.update(protBytes);
            boolean ret = sig.verify(bs.getBytes());
            assertTrue(ret);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            assertTrue(false);
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
            assertTrue(false);
        } catch (InvalidKeyException e) {
            e.printStackTrace();
            assertTrue(false);
        } catch (SignatureException e) {
            e.printStackTrace();
            assertTrue(false);
        }
    }
    if (pbe) {
        ASN1OctetString os = header.getSenderKID();
        assertNotNull(os);
        String keyId = CmpMessageHelper.getStringFromOctets(os);
        log.debug("Found a sender keyId: " + keyId);
        // Verify the PasswordBased protection of the message
        byte[] protectedBytes = CmpMessageHelper.getProtectedBytes(respObject);
        DERBitString protection = respObject.getProtection();
        AlgorithmIdentifier pAlg = header.getProtectionAlg();
        log.debug("Protection type is: " + pAlg.getAlgorithm().getId());
        PBMParameter pp = PBMParameter.getInstance(pAlg.getParameters());
        int iterationCount = pp.getIterationCount().getPositiveValue().intValue();
        log.debug("Iteration count is: " + iterationCount);
        AlgorithmIdentifier owfAlg = pp.getOwf();
        // Normal OWF alg is 1.3.14.3.2.26 - SHA1
        log.debug("Owf type is: " + owfAlg.getAlgorithm().getId());
        AlgorithmIdentifier macAlg = pp.getMac();
        // Normal mac alg is 1.3.6.1.5.5.8.1.2 - HMAC/SHA1
        log.debug("Mac type is: " + macAlg.getAlgorithm().getId());
        byte[] salt = pp.getSalt().getOctets();
        // log.info("Salt is: "+new String(salt));
        byte[] raSecret = pbeSecret != null ? pbeSecret.getBytes() : new byte[0];
        byte[] basekey = new byte[raSecret.length + salt.length];
        System.arraycopy(raSecret, 0, basekey, 0, raSecret.length);
        for (int i = 0; i < salt.length; i++) {
            basekey[raSecret.length + i] = salt[i];
        }
        // Construct the base key according to rfc4210, section 5.1.3.1
        MessageDigest dig = MessageDigest.getInstance(owfAlg.getAlgorithm().getId(),
                BouncyCastleProvider.PROVIDER_NAME);
        for (int i = 0; i < iterationCount; i++) {
            basekey = dig.digest(basekey);
            dig.reset();
        }
        // HMAC/SHA1 os normal 1.3.6.1.5.5.8.1.2 or 1.2.840.113549.2.7
        String macOid = macAlg.getAlgorithm().getId();
        Mac mac = Mac.getInstance(macOid, BouncyCastleProvider.PROVIDER_NAME);
        SecretKey key = new SecretKeySpec(basekey, macOid);
        mac.init(key);
        mac.reset();
        mac.update(protectedBytes, 0, protectedBytes.length);
        byte[] out = mac.doFinal();
        // My out should now be the same as the protection bits
        byte[] pb = protection.getBytes();
        boolean ret = Arrays.equals(out, pb);
        assertTrue(ret);
    }

    // --SenderNonce
    // SenderNonce is something the server came up with, but it should be 16
    // chars
    byte[] nonce = header.getSenderNonce().getOctets();
    assertEquals(nonce.length, 16);

    // --Recipient Nonce
    // recipient nonce should be the same as we sent away as sender nonce
    nonce = header.getRecipNonce().getOctets();
    assertEquals(new String(nonce), new String(senderNonce));

    // --Transaction ID
    // transid should be the same as the one we sent
    nonce = header.getTransactionID().getOctets();
    assertEquals(new String(nonce), new String(transId));

}

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

License:Open Source License

/**
 * Sends a KeyUpdateRequest concerning a certificate that does not exist in the database. A CMP error message is expected and no certificate renewal.
 * // www.  j a  va2 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 'true'
 * - Generates a self-signed certificate, fakecert
 * - Generates a CMP KeyUpdate Request and tests that such request has been created.
 * - Signs the CMP request using fakecert and attaches fakecert to the CMP request. Tests that the CMP request is still not null
 * - Sends the request using HTTP and receives an response.
 * - Examines the response:
 *       - Checks that the response is not empty or null
 *       - Checks that the protection algorithm is sha1WithRSAEncryption
 *       - Checks 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
 *       - Parses the response and checks that the parsing did not result in a 'null'
 *       - Checks that the CMP response message tag number is '23', indicating a CMP error message
 *       - Checks that the CMP response message contain the expected error details text
 * 
 * @throws Exception
 */
@Test
public void test04UpdateKeyWithFakeCert() throws Exception {
    if (log.isTraceEnabled()) {
        log.trace(">test04UpdateKeyWithFakeCert");
    }

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

    //--------------- create the user and issue his first certificate -----------------
    final String fakeUsername = "fakeuser";
    final X500Name fakeUserDN = new X500Name("CN=" + fakeUsername + ",C=SE");
    createUser(fakeUsername, fakeUserDN.toString(), "foo123");

    KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
    Certificate fakeCert = CertTools.genSelfCert(fakeUserDN.toString(), 30, null, keys.getPrivate(),
            keys.getPublic(), AlgorithmConstants.SIGALG_SHA1_WITH_RSA, false);
    assertNotNull("Failed to create a test certificate", fakeCert);

    AlgorithmIdentifier pAlg = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption);

    // Sending a request with a certificate that neither it nor the issuer CA is in the database
    PKIMessage req = genRenewalReq(this.userDN, this.cacert, this.nonce, this.transid, keys, false, null, null,
            pAlg, new DEROctetString(this.nonce));
    assertNotNull("Failed to generate a CMP renewal request", req);

    CMPCertificate[] extraCert = getCMPCert(fakeCert);
    req = CmpMessageHelper.buildCertBasedPKIProtection(req, extraCert, keys.getPrivate(),
            pAlg.getAlgorithm().getId(), "BC");
    assertNotNull(req);

    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, false,
            null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());

    PKIMessage respObject = null;
    ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(resp));
    try {
        respObject = PKIMessage.getInstance(asn1InputStream.readObject());
    } finally {
        asn1InputStream.close();
    }
    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);

    // sending another renewal request with a certificate issued by an existing CA but the certificate itself is not in the database        
    // A certificate, not in the database, issued by TestCA
    byte[] fakecertBytes = Base64.decode(("MIIB6TCCAVKgAwIBAgIIIKF3bEBbbyQwDQYJKoZIhvcNAQELBQAwETEPMA0GA1UE"
            + "AwwGVGVzdENBMB4XDTEzMDMxMjExMTcyMVoXDTEzMDMyMjExMjcyMFowIDERMA8G"
            + "A1UEAwwIZmFrZXVzZXIxCzAJBgNVBAYTAlNFMFwwDQYJKoZIhvcNAQEBBQADSwAw"
            + "SAJBAKZlXrI3TwziiDK9/E1V4n6PCXhpRERSLWPEpRvRPWfpvazpq7R2UZZRq5i2"
            + "hrqKDbfLdAouh2J7AIlUZG3cdJECAwEAAaN/MH0wHQYDVR0OBBYEFCb2tsZTXOh7"
            + "FjjVXpSxkJ79P3tJMAwGA1UdEwEB/wQCMAAwHwYDVR0jBBgwFoAURmtK3gFt81Bp"
            + "3z+YZuzBm65Ja6IwDgYDVR0PAQH/BAQDAgXgMB0GA1UdJQQWMBQGCCsGAQUFBwMC"
            + "BggrBgEFBQcDBDANBgkqhkiG9w0BAQsFAAOBgQAmclw6cwuQkiPSN4bHOP5S7bdU"
            + "+UKXLIkk1L84q0WQfblNzYkcDXMsxwJ1dv2Yd/dxIjtVjrhVIUrRMA70jtWs31CH"
            + "t9ofdgncIdtzZo49mLRQDwhTCApoLf0BCNb2rWpzCPWQTa97y0u5T65m7DAkBTV/" + "JAkFQIZCLSAci++qPA==")
                    .getBytes());
    fakeCert = CertTools.getCertfromByteArray(fakecertBytes);

    req = genRenewalReq(fakeUserDN, this.cacert, this.nonce, this.transid, keys, false, null, null, pAlg,
            new DEROctetString(this.nonce));
    assertNotNull("Failed to generate a CMP renewal request", req);

    extraCert = getCMPCert(fakeCert);
    req = CmpMessageHelper.buildCertBasedPKIProtection(req, extraCert, keys.getPrivate(),
            pAlg.getAlgorithm().getId(), "BC");
    assertNotNull(req);

    bao = new ByteArrayOutputStream();
    out = new DEROutputStream(bao);
    out.writeObject(req);
    ba = bao.toByteArray();
    // Send request and receive response
    resp = sendCmpHttp(ba, 200, this.cmpAlias);
    checkCmpResponseGeneral(resp, this.issuerDN, this.userDN, this.cacert, this.nonce, this.transid, false,
            null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());

    respObject = null;
    asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(resp));
    try {
        respObject = PKIMessage.getInstance(asn1InputStream.readObject());
    } finally {
        asn1InputStream.close();
    }
    assertNotNull(respObject);

    body = respObject.getBody();
    assertEquals(23, body.getType());
    err = (ErrorMsgContent) body.getContent();
    errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
    expectedErrMsg = "The certificate attached to the PKIMessage in the extraCert field could not be found in the database.";
    assertEquals(expectedErrMsg, errMsg);

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

}

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

License:Open Source License

private static X509Certificate checkKurCertRepMessage(X500Name eeDN, Certificate issuerCert, byte[] retMsg,
        int requestId) throws Exception {
    ////from  w  w  w.  j a  v  a 2  s  .  c  o m
    // Parse response message
    //

    PKIMessage respObject = null;
    ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(retMsg));
    try {
        respObject = PKIMessage.getInstance(asn1InputStream.readObject());
    } finally {
        asn1InputStream.close();
    }

    assertNotNull(respObject);

    // Verify body type
    PKIBody body = respObject.getBody();
    int tag = body.getType();
    assertEquals(8, tag);

    // Verify the response
    CertRepMessage c = (CertRepMessage) body.getContent();
    assertNotNull(c);
    CertResponse resp = c.getResponse()[0];
    assertNotNull(resp);
    assertEquals(resp.getCertReqId().getValue().intValue(), requestId);

    // Verify response status
    PKIStatusInfo info = resp.getStatus();
    assertNotNull(info);
    assertEquals(0, info.getStatus().intValue());

    // Verify response certificate
    CertifiedKeyPair kp = resp.getCertifiedKeyPair();
    assertNotNull(kp);
    CertOrEncCert cc = kp.getCertOrEncCert();
    assertNotNull(cc);
    final CMPCertificate cmpcert = cc.getCertificate();
    assertNotNull(cmpcert);
    X509Certificate cert = (X509Certificate) CertTools.getCertfromByteArray(cmpcert.getEncoded());
    final X500Name name = new X500Name(CertTools.getSubjectDN(cert));
    assertArrayEquals(eeDN.getEncoded(), name.getEncoded());
    assertEquals(CertTools.stringToBCDNString(CertTools.getIssuerDN(cert)), CertTools.getSubjectDN(issuerCert));

    // Verify the issuer of cert
    CMPCertificate respCmpCaCert = c.getCaPubs()[0];
    final X509Certificate respCaCert = (X509Certificate) CertTools
            .getCertfromByteArray(respCmpCaCert.getEncoded());
    assertEquals(CertTools.getFingerprintAsString(issuerCert), CertTools.getFingerprintAsString(respCaCert));

    Collection<Certificate> cacerts = new ArrayList<Certificate>();
    cacerts.add(issuerCert);
    assertTrue(CertTools.verify(cert, cacerts));
    cacerts = new ArrayList<Certificate>();
    cacerts.add(respCaCert);
    assertTrue(CertTools.verify(cert, cacerts));
    return cert;
}

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

License:Open Source License

@Test
public void test04RevocationApprovals() throws Exception {
    // Generate random username and CA name
    String randomPostfix = Integer.toString((new Random(new Date().getTime() + 4711)).nextInt(999999));
    String caname = "cmpRevocationCA" + randomPostfix;
    String username = "cmpRevocationUser" + randomPostfix;
    X509CAInfo cainfo = null;/*from  w  ww.  j  av a  2 s.  c  o m*/
    int cryptoTokenId = 0;
    try {
        // Generate CA with approvals for revocation enabled
        cryptoTokenId = CryptoTokenTestUtils.createCryptoTokenForCA(ADMIN, caname, "1024");
        final CAToken catoken = CaTestUtils.createCaToken(cryptoTokenId,
                AlgorithmConstants.SIGALG_SHA1_WITH_RSA, AlgorithmConstants.SIGALG_SHA1_WITH_RSA);
        int caID = RevocationApprovalTest.createApprovalCA(ADMIN, caname, CAInfo.REQ_APPROVAL_REVOCATION,
                this.caAdminSession, this.caSession, catoken);
        // Get CA cert
        cainfo = (X509CAInfo) this.caSession.getCAInfo(ADMIN, caID);
        assertNotNull(cainfo);
        X509Certificate newCACert = (X509Certificate) cainfo.getCertificateChain().iterator().next();
        // Create a user and generate the cert
        EndEntityInformation userdata = new EndEntityInformation(username, "CN=" + username, cainfo.getCAId(),
                null, null, new EndEntityType(EndEntityTypes.ENDUSER), SecConst.EMPTY_ENDENTITYPROFILE,
                CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, SecConst.TOKEN_SOFT_P12, 0, null);
        userdata.setPassword("foo123");
        this.endEntityManagementSession.addUser(ADMIN, userdata, true);
        File tmpfile = File.createTempFile("ejbca", "p12");
        BatchCreateTool.createAllNew(ADMIN, tmpfile.getParent());
        Collection<java.security.cert.Certificate> userCerts = this.certificateStoreSession
                .findCertificatesByUsername(username);
        assertTrue(userCerts.size() == 1);
        X509Certificate cert = (X509Certificate) userCerts.iterator().next();
        // revoke via CMP and verify response
        byte[] nonce = CmpMessageHelper.createSenderNonce();
        byte[] transid = CmpMessageHelper.createSenderNonce();
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        DEROutputStream out = new DEROutputStream(bao);
        PKIMessage rev = genRevReq(cainfo.getSubjectDN(), new X500Name(userdata.getDN()),
                cert.getSerialNumber(), newCACert, nonce, transid, true, null, null);
        PKIMessage revReq = protectPKIMessage(rev, false, PBEPASSWORD, 567);
        assertNotNull(revReq);
        bao = new ByteArrayOutputStream();
        out = new DEROutputStream(bao);
        out.writeObject(revReq);
        byte[] ba = bao.toByteArray();
        byte[] resp = sendCmpHttp(ba, 200, ALIAS);
        checkCmpResponseGeneral(resp, cainfo.getSubjectDN(), new X500Name(userdata.getDN()), newCACert, nonce,
                transid, false, PBEPASSWORD, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        checkCmpRevokeConfirmMessage(cainfo.getSubjectDN(), new X500Name(userdata.getDN()),
                cert.getSerialNumber(), newCACert, resp, true);
        int reason = checkRevokeStatus(cainfo.getSubjectDN(), cert.getSerialNumber());
        assertEquals(reason, RevokedCertInfo.NOT_REVOKED);
        // try to revoke one more via CMP and verify error
        nonce = CmpMessageHelper.createSenderNonce();
        transid = CmpMessageHelper.createSenderNonce();
        bao = new ByteArrayOutputStream();
        out = new DEROutputStream(bao);
        rev = genRevReq(cainfo.getSubjectDN(), new X500Name(userdata.getDN()), cert.getSerialNumber(),
                newCACert, nonce, transid, true, null, null);
        revReq = protectPKIMessage(rev, false, PBEPASSWORD, 567);
        assertNotNull(revReq);
        bao = new ByteArrayOutputStream();
        out = new DEROutputStream(bao);
        out.writeObject(revReq);
        ba = bao.toByteArray();
        resp = sendCmpHttp(ba, 200, ALIAS);
        checkCmpResponseGeneral(resp, cainfo.getSubjectDN(), new X500Name(userdata.getDN()), newCACert, nonce,
                transid, false, PBEPASSWORD, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        checkCmpFailMessage(resp, "The request is already awaiting approval.",
                CmpPKIBodyConstants.REVOCATIONRESPONSE, 0, ResponseStatus.FAILURE.getValue(),
                PKIFailureInfo.incorrectData);
        reason = checkRevokeStatus(cainfo.getSubjectDN(), cert.getSerialNumber());
        assertEquals(reason, RevokedCertInfo.NOT_REVOKED);
        // Approve revocation and verify success

        approveRevocation(ADMIN, ADMIN, username, RevokedCertInfo.REVOCATION_REASON_CESSATIONOFOPERATION,
                ApprovalDataVO.APPROVALTYPE_REVOKECERTIFICATE, this.certificateStoreSession,
                this.approvalSession, this.approvalExecutionSession, cainfo.getCAId());
        // try to revoke the now revoked cert via CMP and verify error
        nonce = CmpMessageHelper.createSenderNonce();
        transid = CmpMessageHelper.createSenderNonce();
        bao = new ByteArrayOutputStream();
        out = new DEROutputStream(bao);
        rev = genRevReq(cainfo.getSubjectDN(), new X500Name(userdata.getDN()), cert.getSerialNumber(),
                newCACert, nonce, transid, true, null, null);
        revReq = protectPKIMessage(rev, false, PBEPASSWORD, 567);
        assertNotNull(revReq);
        bao = new ByteArrayOutputStream();
        out = new DEROutputStream(bao);
        out.writeObject(revReq);
        ba = bao.toByteArray();
        resp = sendCmpHttp(ba, 200, ALIAS);
        checkCmpResponseGeneral(resp, cainfo.getSubjectDN(), new X500Name(userdata.getDN()), newCACert, nonce,
                transid, false, PBEPASSWORD, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        checkCmpFailMessage(resp, "Already revoked.", CmpPKIBodyConstants.REVOCATIONRESPONSE, 0,
                ResponseStatus.FAILURE.getValue(), PKIFailureInfo.incorrectData);
    } finally {
        // Delete user
        this.endEntityManagementSession.deleteUser(ADMIN, username);
        if (cainfo != null) {
            // Nuke CA
            try {
                this.caAdminSession.revokeCA(ADMIN, cainfo.getCAId(),
                        RevokedCertInfo.REVOCATION_REASON_UNSPECIFIED);
            } finally {
                this.caSession.removeCA(ADMIN, cainfo.getCAId());
            }
        }
        CryptoTokenTestUtils.removeCryptoToken(ADMIN, cryptoTokenId);
    }
}

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

License:Open Source License

@Test
public void test01CustomCertificateSerialNumber() throws Exception {
    final KeyPair key1 = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
    final String userName1 = "cmptest1";
    final X500Name userDN1 = new X500Name("C=SE,O=PrimeKey,CN=" + userName1);
    try {/*w w  w.ja v a 2  s .  c  o  m*/
        // check that several certificates could be created for one user and one key.
        long serno = RandomUtils.nextLong();
        BigInteger bint = BigInteger.valueOf(serno);
        // First it should fail because the CMP RA does not even look for, or parse, requested custom certificate serial numbers
        // Actually it does not fail here, but returns good answer
        X509Certificate cert = crmfHttpUserTest(userDN1, key1, null, null);
        assertFalse("SerialNumbers should not be equal when custom serialnumbers are not allowed.",
                bint.equals(cert.getSerialNumber()));

        // Second it should fail when the certificate profile does not allow serial number override
        // crmfHttpUserTest checks the returned serno if bint parameter is not null
        this.cmpConfiguration.setAllowRACustomSerno(cmpAlias, true);
        this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);
        crmfHttpUserTest(userDN1, key1, "Used certificate profile ('" + this.cpDnOverrideId
                + "') is not allowing certificate serial number override.", bint);

        // Third it should succeed and we should get our custom requested serialnumber
        this.cmpConfiguration.setAllowRACustomSerno(cmpAlias, true);
        this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);
        CertificateProfile cp = this.certProfileSession.getCertificateProfile(this.cpDnOverrideId);
        cp.setAllowCertSerialNumberOverride(true);
        // Now when the profile allows serial number override it should work
        this.certProfileSession.changeCertificateProfile(ADMIN, CP_DN_OVERRIDE_NAME, cp);
        crmfHttpUserTest(userDN1, key1, null, bint);
    } finally {
        try {
            this.endEntityManagementSession.deleteUser(ADMIN, userName1);
        } catch (NotFoundException e) {
            /* do nothing */}
    }
}

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

License:Open Source License

@Test
public void test01CrmfHttpOkUser() throws Exception {
    final CAInfo caInfo = this.caSession.getCAInfo(ADMIN, "TestCA");
    // make sure same keys for different users is prevented
    caInfo.setDoEnforceUniquePublicKeys(true);
    // make sure same DN for different users is prevented
    caInfo.setDoEnforceUniqueDistinguishedName(true);
    caInfo.setUseUserStorage(true);/*from w ww .  j a v a2  s  .  c om*/
    this.caAdminSessionRemote.editCA(ADMIN, caInfo);

    final KeyPair key1 = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
    final KeyPair key2 = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
    final KeyPair key3 = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
    final KeyPair key4 = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
    final String userName1 = "cmptest1";
    final String userName2 = "cmptest2";
    final X500Name userDN1 = new X500Name("C=SE,O=PrimeKey,CN=" + userName1);
    final X500Name userDN2 = new X500Name("C=SE,O=PrimeKey,CN=" + userName2);
    try {

        // check that several certificates could be created for one user and one key.
        crmfHttpUserTest(userDN1, key1, null, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId(),
                this.cacert, ISSUER_DN);
        crmfHttpUserTest(userDN2, key2, null, null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId(),
                this.cacert, ISSUER_DN);
        // check that the request fails when asking for certificate for another user with same key.
        crmfHttpUserTest(userDN2, key1,
                "User 'cmptest2' is not allowed to use same key as another user is using.", null,
                PKCSObjectIdentifiers.sha1WithRSAEncryption.getId(), this.cacert, ISSUER_DN);
        crmfHttpUserTest(userDN1, key2,
                "User 'cmptest1' is not allowed to use same key as another user is using.", null,
                PKCSObjectIdentifiers.sha1WithRSAEncryption.getId(), this.cacert, ISSUER_DN);

        // check that you can not issue a certificate with same DN as another user.            
        EndEntityInformation user = new EndEntityInformation("samednuser1", "CN=SameDNUser,O=EJBCA Sample,C=SE",
                this.caid, null, "user1" + "@primekey.se", new EndEntityType(EndEntityTypes.ENDUSER),
                SecConst.EMPTY_ENDENTITYPROFILE, CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER,
                SecConst.TOKEN_SOFT_PEM, 0, null);
        user.setPassword("foo123");
        try {
            this.endEntityManagementSession.addUser(ADMIN, user, true);
            log.debug("created user: samednuser1, foo123, CN=SameDNUser,O=EJBCA Sample,C=SE");
        } catch (Exception e) {
            /* Do nothing. */}

        Certificate user1Cert = null;
        try {
            user1Cert = this.signSession.createCertificate(ADMIN, "samednuser1", "foo123",
                    new PublicKeyWrapper(key3.getPublic()));
        } catch (Exception e) {
            throw new CertificateCreationException("Error encountered when creating certificate", e);
        }
        assertNotNull("Failed to create a test certificate", user1Cert);
        assertEquals(ISSUER_DN, CertTools.getIssuerDN(user1Cert));

        crmfHttpUserTest(new X500Name("CN=SameDNUser,O=EJBCA Sample,C=SE"), key4,
                "User 'SameDNUser' is not allowed to use same subject DN as the user(s) 'samednuser1' is/are using (even if CN postfix is used). See setting for 'Enforce unique DN' in the section Certification Authorities.",
                null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId(), this.cacert, ISSUER_DN);

    } finally {
        try {
            this.endEntityManagementSession.deleteUser(ADMIN, userName1);
        } catch (NotFoundException e) {// Do nothing.
        }
        try {
            this.endEntityManagementSession.deleteUser(ADMIN, userName2);
        } catch (NotFoundException e) {// Do nothing.
        }
        try {
            this.endEntityManagementSession.revokeAndDeleteUser(ADMIN, "SameDNUser", ReasonFlags.unused);
        } catch (NotFoundException e) {// Do nothing.
        }
        try {
            this.endEntityManagementSession.revokeAndDeleteUser(ADMIN, "samednuser1", ReasonFlags.unused);
        } catch (NotFoundException e) {// Do nothing.
        }
    }
}

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

License:Open Source License

@Test
public void test02NullKeyID() throws Exception {

    // Create a new good user

    final X500Name userDN = new X500Name("CN=keyIDTestUser,C=SE");
    try {// w  w w  .  j  a v a2  s . c  om
        final KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
        final byte[] nonce = CmpMessageHelper.createSenderNonce();
        final byte[] transid = CmpMessageHelper.createSenderNonce();
        final int reqId;

        final PKIMessage one = genCertReq(ISSUER_DN, userDN, keys, this.cacert, nonce, transid, true, null,
                null, null, null, null, null);
        final PKIMessage req = protectPKIMessage(one, false, PBEPASSWORD, null, 567);
        Assert.assertNotNull(req);
        CertReqMessages ir = (CertReqMessages) req.getBody().getContent();
        reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();

        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, cmpAlias);
        // do not check signing if we expect a failure (sFailMessage==null)
        checkCmpResponseGeneral(resp, ISSUER_DN, userDN, this.cacert, nonce, transid, true, null,
                PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        X509Certificate cert = checkCmpCertRepMessage(userDN, this.cacert, resp, reqId);
        BigInteger serialnumber = cert.getSerialNumber();

        // Revoke the created certificate
        final PKIMessage con = genRevReq(ISSUER_DN, userDN, serialnumber, this.cacert, nonce, transid, false,
                null, null);
        Assert.assertNotNull(con);
        PKIMessage revmsg = protectPKIMessage(con, false, PBEPASSWORD, null, 567);
        final ByteArrayOutputStream baorev = new ByteArrayOutputStream();
        final DEROutputStream outrev = new DEROutputStream(baorev);
        outrev.writeObject(revmsg);
        final byte[] barev = baorev.toByteArray();
        // Send request and receive response
        final byte[] resprev = sendCmpHttp(barev, 200, cmpAlias);
        checkCmpResponseGeneral(resprev, ISSUER_DN, userDN, this.cacert, nonce, transid, false, null,
                PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        int revstatus = checkRevokeStatus(ISSUER_DN, serialnumber);
        Assert.assertEquals("Certificate revocation failed.", RevokedCertInfo.REVOCATION_REASON_KEYCOMPROMISE,
                revstatus);
    } finally {
        try {
            this.endEntityManagementSession.deleteUser(ADMIN, "keyIDTestUser");
        } catch (NotFoundException e) {
            // NOPMD
        }
    }

}

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

License:Open Source License

@Test
public void test03UseKeyID() throws Exception {

    GlobalConfiguration gc = (GlobalConfiguration) this.globalConfSession
            .getCachedConfiguration(GlobalConfiguration.GLOBAL_CONFIGURATION_ID);
    gc.setEnableEndEntityProfileLimitations(true);
    this.globalConfSession.saveConfiguration(ADMIN, gc);

    this.cmpConfiguration.setRAEEProfile(cmpAlias, "KeyId");
    this.cmpConfiguration.setRACertProfile(cmpAlias, "KeyId");
    this.globalConfSession.saveConfiguration(ADMIN, this.cmpConfiguration);

    try {/*from w w w  . jav  a 2 s.co  m*/
        this.certProfileSession.removeCertificateProfile(ADMIN, "CMPKEYIDTESTPROFILE");
        this.endEntityProfileSession.removeEndEntityProfile(ADMIN, "CMPKEYIDTESTPROFILE");
    } catch (Exception e) {
        /*Do nothing.*/}

    // Configure CMP for this test, we allow custom certificate serial numbers
    CertificateProfile profile = new CertificateProfile(CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
    try {
        this.certProfileSession.addCertificateProfile(ADMIN, "CMPKEYIDTESTPROFILE", profile);
    } catch (CertificateProfileExistsException e) {
        log.error("Could not create certificate profile.", e);
    }

    int cpId = this.certProfileSession.getCertificateProfileId("CMPKEYIDTESTPROFILE");

    EndEntityProfile eep = new EndEntityProfile();
    eep.setValue(EndEntityProfile.DEFAULTCERTPROFILE, 0, "" + cpId);
    eep.setValue(EndEntityProfile.AVAILCERTPROFILES, 0, "" + cpId);
    eep.setValue(EndEntityProfile.DEFAULTCA, 0, "" + this.caid);
    eep.setValue(EndEntityProfile.AVAILCAS, 0, "" + this.caid);
    eep.addField(DnComponents.ORGANIZATION);
    eep.setRequired(DnComponents.ORGANIZATION, 0, true);
    eep.addField(DnComponents.RFC822NAME);
    eep.addField(DnComponents.UPN);
    eep.setModifyable(DnComponents.RFC822NAME, 0, true);
    eep.setUse(DnComponents.RFC822NAME, 0, false); // Don't use field from "email" data

    try {
        this.endEntityProfileSession.addEndEntityProfile(ADMIN, "CMPKEYIDTESTPROFILE", eep);
    } catch (EndEntityProfileExistsException e) {
        log.error("Could not create end entity profile.", e);
    }

    // Create a new user that does not fulfill the end entity profile

    X500Name userDN = new X500Name("CN=keyIDTestUser,C=SE");
    final KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
    final byte[] nonce = CmpMessageHelper.createSenderNonce();
    final byte[] transid = CmpMessageHelper.createSenderNonce();
    final int reqId;

    try {
        this.endEntityManagementSession.deleteUser(ADMIN, "keyIDTestUser");
    } catch (NotFoundException e) {
        // NOPMD
    }
    try {
        this.endEntityManagementSession.deleteUser(ADMIN, "keyidtest2");
    } catch (NotFoundException e) {
        // NOPMD
    }

    try {
        final PKIMessage one = genCertReq(ISSUER_DN, userDN, keys, this.cacert, nonce, transid, true, null,
                null, null, null, null, null);
        final PKIMessage req = protectPKIMessage(one, false, PBEPASSWORD, "CMPKEYIDTESTPROFILE", 567);

        CertReqMessages ir = (CertReqMessages) req.getBody().getContent();
        reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();
        Assert.assertNotNull(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, cmpAlias);
        // do not check signing if we expect a failure (sFailMessage==null)
        checkCmpResponseGeneral(resp, ISSUER_DN, userDN, this.cacert, nonce, transid, false, null,
                PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        checkCmpFailMessage(resp, "Subject DN field 'ORGANIZATION' must exist.",
                CmpPKIBodyConstants.INITIALIZATIONRESPONSE, reqId, PKIFailureInfo.badRequest,
                PKIFailureInfo.incorrectData);

        // Create a new user that fulfills the end entity profile

        userDN = new X500Name("CN=keyidtest2,O=org");
        final KeyPair keys2 = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
        final byte[] nonce2 = CmpMessageHelper.createSenderNonce();
        final byte[] transid2 = CmpMessageHelper.createSenderNonce();
        final int reqId2;

        final PKIMessage one2 = genCertReq(ISSUER_DN, userDN, keys2, this.cacert, nonce2, transid2, true, null,
                null, null, null, null, null);
        final PKIMessage req2 = protectPKIMessage(one2, false, PBEPASSWORD, "CMPKEYIDTESTPROFILE", 567);

        ir = (CertReqMessages) req2.getBody().getContent();
        reqId2 = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();
        Assert.assertNotNull(req2);
        final ByteArrayOutputStream bao2 = new ByteArrayOutputStream();
        final DEROutputStream out2 = new DEROutputStream(bao2);
        out2.writeObject(req2);
        final byte[] ba2 = bao2.toByteArray();
        // Send request and receive response
        final byte[] resp2 = sendCmpHttp(ba2, 200, cmpAlias);
        // do not check signing if we expect a failure (sFailMessage==null)
        checkCmpResponseGeneral(resp2, ISSUER_DN, userDN, this.cacert, nonce2, transid2, true, null,
                PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        X509Certificate cert = checkCmpCertRepMessage(userDN, this.cacert, resp2, reqId2);
        BigInteger serialnumber = cert.getSerialNumber();

        EndEntityInformation ee = this.eeAccessSession.findUser(ADMIN, "keyidtest2");
        Assert.assertEquals("Wrong certificate profile", cpId, ee.getCertificateProfileId());

        // Revoke the created certificate and use keyid
        final PKIMessage con = genRevReq(ISSUER_DN, userDN, serialnumber, this.cacert, nonce2, transid2, false,
                null, null);
        Assert.assertNotNull(con);
        PKIMessage revmsg = protectPKIMessage(con, false, PBEPASSWORD, "CMPKEYIDTESTPROFILE", 567);
        final ByteArrayOutputStream baorev = new ByteArrayOutputStream();
        final DEROutputStream outrev = new DEROutputStream(baorev);
        outrev.writeObject(revmsg);
        final byte[] barev = baorev.toByteArray();
        // Send request and receive response
        final byte[] resprev = sendCmpHttp(barev, 200, cmpAlias);
        checkCmpResponseGeneral(resprev, ISSUER_DN, userDN, this.cacert, nonce2, transid2, true, null,
                PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        int revstatus = checkRevokeStatus(ISSUER_DN, serialnumber);
        Assert.assertEquals("Certificate revocation failed.", RevokedCertInfo.REVOCATION_REASON_KEYCOMPROMISE,
                revstatus);
    } finally {
        try {
            this.endEntityManagementSession.deleteUser(ADMIN, "keyIDTestUser");
        } catch (NotFoundException e) {
            // NOPMD
        }
        try {
            this.endEntityManagementSession.deleteUser(ADMIN, "keyidtest2");
        } catch (NotFoundException e) {
            // NOPMD
        }
    }
}

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

License:Open Source License

/**
 * Send a CMP request with SubjectAltName containing OIDs that are not defined by Ejbca.
 * Expected to pass and a certificate containing the unsupported OIDs is returned.
 * /*from   w w  w .ja  v  a2  s. com*/
 * @throws Exception
 */
@Test
public void test04UsingOtherNameInSubjectAltName() throws Exception {

    ASN1EncodableVector vec = new ASN1EncodableVector();
    ASN1EncodableVector v = new ASN1EncodableVector();

    v.add(new ASN1ObjectIdentifier(CertTools.UPN_OBJECTID));
    v.add(new DERTaggedObject(true, 0, new DERUTF8String("boo@bar")));
    GeneralName gn = GeneralName.getInstance(new DERTaggedObject(false, 0, new DERSequence(v)));
    vec.add(gn);

    v = new ASN1EncodableVector();
    v.add(new ASN1ObjectIdentifier("2.5.5.6"));
    v.add(new DERTaggedObject(true, 0,
            new DERIA5String("2.16.528.1.1007.99.8-1-993000027-N-99300011-00.000-00000000")));
    gn = GeneralName.getInstance(new DERTaggedObject(false, 0, new DERSequence(v)));
    vec.add(gn);

    GeneralNames san = GeneralNames.getInstance(new DERSequence(vec));

    ExtensionsGenerator gen = new ExtensionsGenerator();
    gen.addExtension(Extension.subjectAlternativeName, false, san);
    Extensions exts = gen.generate();

    final X500Name userDN = new X500Name("CN=TestAltNameUser");
    final KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
    final byte[] nonce = CmpMessageHelper.createSenderNonce();
    final byte[] transid = CmpMessageHelper.createSenderNonce();
    final int reqId;
    String fingerprint = null;

    try {
        final PKIMessage one = genCertReq(ISSUER_DN, userDN, keys, this.cacert, nonce, transid, true, exts,
                null, null, null, null, null);
        final PKIMessage req = protectPKIMessage(one, false, PBEPASSWORD, "CMPKEYIDTESTPROFILE", 567);

        CertReqMessages ir = (CertReqMessages) req.getBody().getContent();
        reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();
        Assert.assertNotNull(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, cmpAlias);
        // do not check signing if we expect a failure (sFailMessage==null)
        checkCmpResponseGeneral(resp, ISSUER_DN, userDN, this.cacert, nonce, transid, false, null,
                PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        X509Certificate cert = checkCmpCertRepMessage(userDN, this.cacert, resp, reqId);
        fingerprint = CertTools.getFingerprintAsString(cert);

    } finally {
        try {
            this.endEntityManagementSession.revokeAndDeleteUser(ADMIN, "TestAltNameUser",
                    RevokedCertInfo.REVOCATION_REASON_KEYCOMPROMISE);
        } catch (NotFoundException e) {
            /*Do nothing*/}

        try {
            this.internalCertStoreSession.removeCertificate(fingerprint);
        } catch (Exception e) {
            /*Do nothing*/}
    }

}

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

License:Open Source License

@Test
public void test05SubjectSerialNumber() throws Exception {

    // Set requirement of unique subjectDN serialnumber to be true
    CAInfo cainfo = this.caSession.getCAInfo(ADMIN, this.caid);
    boolean requiredUniqueSerialnumber = cainfo.isDoEnforceUniqueSubjectDNSerialnumber();
    // Set the CA to enforce unique serialnumber
    cainfo.setDoEnforceUniqueSubjectDNSerialnumber(true);
    CAAdminSessionRemote caAdminSession = EjbRemoteHelper.INSTANCE.getRemoteSession(CAAdminSessionRemote.class);
    caAdminSession.editCA(ADMIN, cainfo);

    // Create a new good user
    final String username = "subjectsnuser";
    X500Name userDN = new X500Name("CN=" + username + ",SN=1234567,C=SE");
    try {//from   ww  w.  j a  v a 2 s .co m
        KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
        final byte[] nonce = CmpMessageHelper.createSenderNonce();
        final byte[] transid = CmpMessageHelper.createSenderNonce();
        int reqId;

        PKIMessage one = genCertReq(ISSUER_DN, userDN, keys, this.cacert, nonce, transid, true, null, null,
                null, null, null, null);
        PKIMessage req = protectPKIMessage(one, false, PBEPASSWORD, null, 567);
        Assert.assertNotNull(req);
        CertReqMessages ir = (CertReqMessages) req.getBody().getContent();
        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, cmpAlias);
        // do not check signing if we expect a failure (sFailMessage==null)
        checkCmpResponseGeneral(resp, ISSUER_DN, userDN, this.cacert, nonce, transid, true, null,
                PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        X509Certificate cert = checkCmpCertRepMessage(userDN, this.cacert, resp, reqId);
        BigInteger serialnumber = cert.getSerialNumber();

        // create a second user with the same serialnumber, but spelled "SERIALNUMBER" instead of "SN"
        userDN = new X500Name("CN=subjectsnuser2,SERIALNUMBER=1234567,C=SE");
        keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);

        one = genCertReq(ISSUER_DN, userDN, keys, this.cacert, nonce, transid, true, null, null, null, null,
                null, null);
        req = protectPKIMessage(one, false, PBEPASSWORD, null, 567);
        Assert.assertNotNull(req);
        ir = (CertReqMessages) req.getBody().getContent();
        reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();

        bao = new ByteArrayOutputStream();
        out = new DEROutputStream(bao);
        out.writeObject(req);
        ba = bao.toByteArray();
        // Send request and receive response
        resp = sendCmpHttp(ba, 200, cmpAlias);
        // do not check signing if we expect a failure (sFailMessage==null)
        checkCmpResponseGeneral(resp, ISSUER_DN, userDN, this.cacert, nonce, transid, false, null,
                PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        checkCmpFailMessage(resp, "Error: SubjectDN Serialnumber already exists.",
                CmpPKIBodyConstants.ERRORMESSAGE, reqId, PKIFailureInfo.badRequest,
                PKIFailureInfo.incorrectData);

        // Revoke the created certificate
        final PKIMessage con = genRevReq(ISSUER_DN, userDN, serialnumber, this.cacert, nonce, transid, false,
                null, null);
        Assert.assertNotNull(con);
        PKIMessage revmsg = protectPKIMessage(con, false, PBEPASSWORD, null, 567);
        final ByteArrayOutputStream baorev = new ByteArrayOutputStream();
        final DEROutputStream outrev = new DEROutputStream(baorev);
        outrev.writeObject(revmsg);
        final byte[] barev = baorev.toByteArray();
        // Send request and receive response
        final byte[] resprev = sendCmpHttp(barev, 200, cmpAlias);
        checkCmpResponseGeneral(resprev, ISSUER_DN, userDN, this.cacert, nonce, transid, false, null,
                PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        int revstatus = checkRevokeStatus(ISSUER_DN, serialnumber);
        Assert.assertEquals("Certificate revocation failed.", RevokedCertInfo.REVOCATION_REASON_KEYCOMPROMISE,
                revstatus);

        cainfo.setDoEnforceUniqueSubjectDNSerialnumber(requiredUniqueSerialnumber);
        caAdminSession.editCA(ADMIN, cainfo);
    } finally {
        this.endEntityManagementSession.deleteUser(ADMIN, username);
    }
}