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.CrmfRAPbeMultipleKeyIdRequestTest.java

License:Open Source License

@Test
public void test06CrmfTcpOkUserKeyId3() throws Exception {

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

    PKIMessage one = genCertReq(this.issuerDN2, userDN2, this.keys, this.cacert2, nonce, transid, true, null,
            null, null, null, null, null);
    PKIMessage req = protectPKIMessage(one, false, PBEPASSWORD, "KeyId3", 567);

    CertReqMessages ir = (CertReqMessages) req.getBody().getContent();
    int reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();
    assertNotNull(req);/*from   www  .  j  a  va 2 s  . com*/
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(req);
    byte[] ba = bao.toByteArray();
    // Send request and receive response
    byte[] resp = sendCmpTcp(ba, 5);
    checkCmpResponseGeneral(resp, this.issuerDN2, userDN2, this.cacert2, nonce, transid, false, PBEPASSWORD,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    X509Certificate cert = checkCmpCertRepMessage(userDN2, this.cacert2, resp, reqId);
    // FileOutputStream fos = new FileOutputStream("/home/tomas/foo.crt");
    // fos.write(cert.getEncoded());
    // fos.close();
    String altNames = CertTools.getSubjectAlternativeName(cert);
    assertTrue(altNames.indexOf("upn=fooupn@bar.com") != -1);
    assertTrue(altNames.indexOf("rfc822name=fooemail@bar.com") != -1);

    // Check key usage that it is digitalSignature, keyEncipherment and
    // nonRepudiation for KeyId3
    // Because keyUsage for keyId3 should be taken from the request (see
    // genCertReq)
    boolean[] ku = cert.getKeyUsage();
    assertTrue(ku[0]);
    assertTrue(ku[1]);
    assertTrue(ku[2]);
    assertFalse(ku[3]);
    assertFalse(ku[4]);
    assertFalse(ku[5]);
    assertFalse(ku[6]);
    assertFalse(ku[7]);
    assertFalse(ku[8]);
    // Check DN that must be SE for KeyId1 and NO for KeyId2
    assertEquals("NO", CertTools.getPartFromDN(cert.getSubjectDN().getName(), "C"));

    // Send a confirm message to the CA
    String hash = "foo123";
    PKIMessage confirm = genCertConfirm(userDN2, this.cacert2, nonce, transid, hash, reqId);
    assertNotNull(confirm);
    PKIMessage req1 = protectPKIMessage(confirm, false, PBEPASSWORD, 567);
    bao = new ByteArrayOutputStream();
    out = new DEROutputStream(bao);
    out.writeObject(req1);
    ba = bao.toByteArray();
    // Send request and receive response
    resp = sendCmpTcp(ba, 5);
    checkCmpResponseGeneral(resp, this.issuerDN2, userDN2, this.cacert2, nonce, transid, false, PBEPASSWORD,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    checkCmpPKIConfirmMessage(userDN2, this.cacert2, resp);
}

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

License:Open Source License

@Test
public void test07ExtensionOverride() throws Exception {

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

    // Create some crazy extensions to see that we get them when using
    // extension override.
    // We should not get our values when not using extension override
    ExtensionsGenerator extgen = new ExtensionsGenerator();
    // SubjectAltName
    GeneralNames san = CertTools.getGeneralNamesFromAltName("dnsName=foo.bar.com");
    extgen.addExtension(Extension.subjectAlternativeName, false, san);
    // KeyUsage/*w ww .j a v a 2  s  .co  m*/
    int bcku = 0;
    bcku = X509KeyUsage.decipherOnly;
    X509KeyUsage ku = new X509KeyUsage(bcku);
    extgen.addExtension(Extension.keyUsage, false, ku);
    // Extended Key Usage
    List<KeyPurposeId> usage = new ArrayList<KeyPurposeId>();
    usage.add(KeyPurposeId.id_kp_codeSigning);
    ExtendedKeyUsage eku = ExtendedKeyUsage.getInstance(usage);
    extgen.addExtension(Extension.extendedKeyUsage, false, eku);
    // OcspNoCheck
    extgen.addExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck, false, DERNull.INSTANCE);
    // Netscape cert type
    extgen.addExtension(new ASN1ObjectIdentifier("2.16.840.1.113730.1.1"), false,
            new NetscapeCertType(NetscapeCertType.objectSigningCA));
    // My completely own
    extgen.addExtension(new ASN1ObjectIdentifier("1.1.1.1.1"), false, new DERIA5String("PrimeKey"));

    // Make the complete extension package
    Extensions exts = extgen.generate();

    // First test without extension override
    PKIMessage one = genCertReq(this.issuerDN2, userDN2, this.keys, this.cacert2, nonce, transid, true, exts,
            null, null, null, null, null);
    PKIMessage req = protectPKIMessage(one, false, PBEPASSWORD, "KeyId2", 567);

    CertReqMessages ir = (CertReqMessages) req.getBody().getContent();
    int reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();
    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 = sendCmpTcp(ba, 5);
    checkCmpResponseGeneral(resp, this.issuerDN2, userDN2, this.cacert2, nonce, transid, false, PBEPASSWORD,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    X509Certificate cert = checkCmpCertRepMessage(userDN2, this.cacert2, resp, reqId);
    String altNames = CertTools.getSubjectAlternativeName(cert);
    assertTrue(altNames.indexOf("dNSName=foo.bar.com") != -1);

    // Check key usage that it is nonRepudiation for KeyId2
    boolean[] kubits = cert.getKeyUsage();
    assertFalse(kubits[0]);
    assertTrue(kubits[1]);
    assertFalse(kubits[2]);
    assertFalse(kubits[3]);
    assertFalse(kubits[4]);
    assertFalse(kubits[5]);
    assertFalse(kubits[6]);
    assertFalse(kubits[7]);
    assertFalse(kubits[8]);
    // Our own ext should not be here
    assertNull(cert.getExtensionValue("1.1.1.1.1"));
    assertNull(cert.getExtensionValue("2.16.840.1.113730.1.1"));
    assertNull(cert.getExtensionValue(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck.getId()));

    // Skip confirmation message, we have tested that several times already

    //
    // Do the same with keyId4, that has full extension override
    one = genCertReq(this.issuerDN2, userDN2, this.keys, this.cacert2, nonce, transid, true, exts, null, null,
            null, null, null);
    req = protectPKIMessage(one, false, PBEPASSWORD, "KeyId4", 567);

    ir = (CertReqMessages) req.getBody().getContent();
    reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();
    assertNotNull(req);
    bao = new ByteArrayOutputStream();
    out = new DEROutputStream(bao);
    out.writeObject(req);
    ba = bao.toByteArray();
    // Send request and receive response
    resp = sendCmpTcp(ba, 5);
    checkCmpResponseGeneral(resp, this.issuerDN2, userDN2, this.cacert2, nonce, transid, false, PBEPASSWORD,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    cert = checkCmpCertRepMessage(userDN2, this.cacert2, resp, reqId);
    altNames = CertTools.getSubjectAlternativeName(cert);
    assertTrue(altNames.indexOf("dNSName=foo.bar.com") != -1);

    // Check key usage that it is decipherOnly for KeyId4
    kubits = cert.getKeyUsage();
    assertFalse(kubits[0]);
    assertFalse(kubits[1]);
    assertFalse(kubits[2]);
    assertFalse(kubits[3]);
    assertFalse(kubits[4]);
    assertFalse(kubits[5]);
    assertFalse(kubits[6]);
    assertFalse(kubits[7]);
    assertTrue(kubits[8]);
    // Our own ext should not be here
    assertNotNull(cert.getExtensionValue("1.1.1.1.1"));
    assertNotNull(cert.getExtensionValue("2.16.840.1.113730.1.1"));
    assertNotNull(cert.getExtensionValue(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck.getId()));
    List<String> l = cert.getExtendedKeyUsage();
    assertEquals(1, l.size());
    String s = l.get(0);
    assertEquals(KeyPurposeId.id_kp_codeSigning.getId(), s);

    // Skip confirmation message, we have tested that several times already
}

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

License:Open Source License

@Test
public void test01CrmfHttpOkUser() throws Exception {
    try {/* w ww. j  av a 2 s  .  c  o m*/
        byte[] nonce = CmpMessageHelper.createSenderNonce();
        byte[] transid = CmpMessageHelper.createSenderNonce();

        // We should be able to back date the start time when allow validity
        // override is enabled in the certificate profile
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_WEEK, -1);
        cal.set(Calendar.MILLISECOND, 0); // Certificates don't use milliseconds
        // in validity
        Date notBefore = cal.getTime();
        cal.add(Calendar.DAY_OF_WEEK, 3);
        cal.set(Calendar.MILLISECOND, 0); // Certificates don't use milliseconds
        // in validity
        Date notAfter = cal.getTime();

        // In this we also test validity override using notBefore and notAfter
        // from above
        // In this test userDN contains special, escaped characters to verify
        // that that works with CMP RA as well
        PKIMessage one = genCertReq(issuerDN, userDN, this.keys, this.cacert, nonce, transid, true, null,
                notBefore, notAfter, null, null, null);
        PKIMessage req = protectPKIMessage(one, false, PBEPASSWORD, 567);
        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, false, PBEPASSWORD,
                PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        X509Certificate cert = checkCmpCertRepMessage(userDN, this.cacert, resp, reqId);
        // Check that validity override works
        assertTrue(cert.getNotBefore().equals(notBefore));
        assertTrue(cert.getNotAfter().equals(notAfter));
        String altNames = CertTools.getSubjectAlternativeName(cert);
        assertTrue(altNames.indexOf("upn=fooupn@bar.com") != -1);
        assertTrue(altNames.indexOf("rfc822name=fooemail@bar.com") != -1);

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

        // Now revoke the bastard using the CMPv1 reason code!
        PKIMessage rev = genRevReq(issuerDN, userDN, cert.getSerialNumber(), this.cacert, nonce, transid, false,
                null, null);
        PKIMessage revReq = protectPKIMessage(rev, false, PBEPASSWORD, 567);
        assertNotNull(revReq);
        bao = new ByteArrayOutputStream();
        out = new DEROutputStream(bao);
        out.writeObject(revReq);
        ba = bao.toByteArray();
        // Send request and receive response
        resp = sendCmpHttp(ba, 200, ALIAS);
        checkCmpResponseGeneral(resp, issuerDN, userDN, this.cacert, nonce, transid, false, PBEPASSWORD,
                PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        checkCmpRevokeConfirmMessage(issuerDN, userDN, cert.getSerialNumber(), this.cacert, resp, true);
        int reason = checkRevokeStatus(issuerDN, cert.getSerialNumber());
        assertEquals(reason, RevokedCertInfo.REVOCATION_REASON_KEYCOMPROMISE);

        // Create a revocation request for a non existing cert, should fail!
        rev = genRevReq(issuerDN, userDN, new BigInteger("1"), this.cacert, 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();
        // Send request and receive response
        resp = sendCmpHttp(ba, 200, ALIAS);
        checkCmpResponseGeneral(resp, issuerDN, userDN, this.cacert, nonce, transid, false, PBEPASSWORD,
                PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        checkCmpRevokeConfirmMessage(issuerDN, userDN, cert.getSerialNumber(), this.cacert, resp, false);
    } finally {
        try {
            this.endEntityManagementSession.deleteUser(ADMIN, "cmptest");
        } catch (NotFoundException e) {
            // NOPMD: ignore
        }
    }
}

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

License:Open Source License

/** Tests the cmp configuration settings:
 * cmp.ra.certificateprofile=KeyId//from   w w w. ja v a  2s.  co  m
 * cmp.ra.certificateprofile=ProfileDefault
 * 
 * KeyId means that the certificate profile used to issue the certificate is the same as the KeyId sent in the request.
 * ProfileDefault means that the certificate profile used is taken from the default certificate profile in the end entity profile.
 */
@Test
public void test02KeyIdProfiles() throws Exception {
    final String keyId = "CmpTestKeyIdProfileName";
    final String keyIdDefault = "CmpTestKeyIdProfileNameDefault";

    this.cmpConfiguration.setRACertProfile(ALIAS, "KeyId");
    this.cmpConfiguration.setRAEEProfile(ALIAS, "KeyId");
    this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

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

        // Create one EE profile and 2 certificate profiles, one of the certificate profiles
        // (that does not have the same name as KeyId) will be the default in the EE profile.
        // First we will use "KeyId" for both profiles, and then we will use ProfileDefault for the cert profile
        CertificateProfile cp1 = new CertificateProfile(CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
        cp1.setUseSubjectAlternativeName(true);
        cp1.setAllowDNOverride(true);
        // Add a weird CDP, so we are sure this is the profile used
        final String cdp1 = "http://keyidtest/crl.crl";
        cp1.setCRLDistributionPointURI(cdp1);
        cp1.setUseCRLDistributionPoint(true);
        CertificateProfile cp2 = new CertificateProfile(CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
        cp2.setUseSubjectAlternativeName(false);
        cp2.setAllowDNOverride(true);
        final String cdp2 = "http://keyidtestDefault/crl.crl";
        cp2.setCRLDistributionPointURI(cdp2);
        cp2.setUseCRLDistributionPoint(true);
        try {
            this.certProfileSession.addCertificateProfile(ADMIN, keyId, cp1);
        } catch (CertificateProfileExistsException e) {
            log.error("Error adding certificate profile: ", e);
        }
        try {
            this.certProfileSession.addCertificateProfile(ADMIN, keyIdDefault, cp2);
        } catch (CertificateProfileExistsException e) {
            log.error("Error adding certificate profile: ", e);
        }

        int cpId1 = this.certProfileSession.getCertificateProfileId(keyId);
        int cpId2 = this.certProfileSession.getCertificateProfileId(keyIdDefault);
        // Configure an EndEntity profile with allow CN, O, C in DN
        // and rfc822Name (uncheck 'Use entity e-mail field' and check
        // 'Modifyable'), MS UPN in altNames in the end entity profile.
        EndEntityProfile eep = new EndEntityProfile(true);
        eep.setValue(EndEntityProfile.DEFAULTCERTPROFILE, 0, "" + cpId2);
        eep.setValue(EndEntityProfile.AVAILCERTPROFILES, 0, "" + cpId1 + ";" + cpId2);
        eep.setModifyable(DnComponents.RFC822NAME, 0, true);
        eep.setUse(DnComponents.RFC822NAME, 0, false); // Don't use field
        // from "email" data
        try {
            this.endEntityProfileSession.addEndEntityProfile(ADMIN, keyId, eep);
        } catch (EndEntityProfileExistsException e) {
            log.error("Could not create end entity profile.", e);
        }

        // In this test userDN contains special, escaped characters to verify
        // that that works with CMP RA as well
        PKIMessage one = genCertReq(issuerDN, userDN, this.keys, this.cacert, nonce, transid, true, null, null,
                null, null, null, null);
        PKIMessage req = protectPKIMessage(one, false, PBEPASSWORD, keyId, 567);
        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, false, PBEPASSWORD,
                PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        X509Certificate cert = checkCmpCertRepMessage(userDN, this.cacert, resp, reqId);
        String altNames = CertTools.getSubjectAlternativeName(cert);
        assertTrue(altNames.indexOf("upn=fooupn@bar.com") != -1);
        assertTrue(altNames.indexOf("rfc822name=fooemail@bar.com") != -1);
        final URL cdpfromcert1 = CertTools.getCrlDistributionPoint(cert);
        assertEquals(
                "CDP is not correct, it probably means it was not the correct 'KeyId' certificate profile that was used",
                cdp1, cdpfromcert1.toString());

        // Update property on server so that we use ProfileDefault as certificate profile, should give a little different result
        this.cmpConfiguration.setRACertProfile(ALIAS, "ProfileDefault");
        this.globalConfigurationSession.saveConfiguration(ADMIN, this.cmpConfiguration);

        // Make new request, the certificate should now be produced with the other certificate profile
        PKIMessage two = genCertReq(issuerDN, userDN, this.keys, this.cacert, nonce, transid, true, null, null,
                null, null, null, null);
        PKIMessage req2 = protectPKIMessage(two, false, PBEPASSWORD, keyId, 567);
        assertNotNull(req2);

        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, ALIAS);
        checkCmpResponseGeneral(resp, issuerDN, userDN, this.cacert, nonce, transid, false, PBEPASSWORD,
                PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        cert = checkCmpCertRepMessage(userDN, this.cacert, resp, reqId);
        altNames = CertTools.getSubjectAlternativeName(cert);
        assertNull(altNames);
        final URL cdpfromcert2 = CertTools.getCrlDistributionPoint(cert);
        assertEquals(
                "CDP is not correct, it probably means it was not the correct 'KeyId' certificate profile that was used",
                cdp2, cdpfromcert2.toString());
    } finally {
        try {
            this.endEntityManagementSession.deleteUser(ADMIN, "cmptest");
        } catch (NotFoundException e) {
            // NOPMD: ignore
        }
        this.endEntityProfileSession.removeEndEntityProfile(ADMIN, keyId);
        this.certProfileSession.removeCertificateProfile(ADMIN, keyId);
        this.certProfileSession.removeCertificateProfile(ADMIN, keyIdDefault);
    }
}

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 a  v a 2 s. co 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.CrmfRAPbeTcpRequestTest.java

License:Open Source License

@Test
public void test02CrmfTcpOkUser() throws Exception {

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

    PKIMessage one = genCertReq(issuerDN, userDN, this.keys, this.cacert, nonce, transid, true, null, null,
            null, null, null, null);/*from  ww  w  .j ava  2s.c o  m*/
    PKIMessage req = protectPKIMessage(one, false, PBEPASSWORD, 567);
    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 = sendCmpTcp(ba, 5);
    checkCmpResponseGeneral(resp, issuerDN, userDN, this.cacert, nonce, transid, false, PBEPASSWORD,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    X509Certificate cert = checkCmpCertRepMessage(userDN, this.cacert, resp, reqId);
    assertNotNull(cert);

    // Send a confirm message to the CA
    String hash = "foo123";
    PKIMessage confirm = genCertConfirm(userDN, this.cacert, nonce, transid, hash, reqId);
    assertNotNull(confirm);
    PKIMessage req1 = protectPKIMessage(confirm, false, PBEPASSWORD, 567);
    bao = new ByteArrayOutputStream();
    out = new DEROutputStream(bao);
    out.writeObject(req1);
    ba = bao.toByteArray();
    // Send request and receive response
    resp = sendCmpTcp(ba, 5);
    checkCmpResponseGeneral(resp, issuerDN, userDN, this.cacert, nonce, transid, false, PBEPASSWORD,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    checkCmpPKIConfirmMessage(userDN, this.cacert, resp);

    // Now revoke the bastard using the CMPv2 CRL entry extension!
    PKIMessage rev = genRevReq(issuerDN, userDN, cert.getSerialNumber(), this.cacert, nonce, transid, true,
            null, null);
    PKIMessage revReq = protectPKIMessage(rev, false, PBEPASSWORD, 567);
    assertNotNull(revReq);
    bao = new ByteArrayOutputStream();
    out = new DEROutputStream(bao);
    out.writeObject(revReq);
    ba = bao.toByteArray();
    // Send request and receive response
    resp = sendCmpTcp(ba, 5);
    checkCmpResponseGeneral(resp, issuerDN, userDN, this.cacert, nonce, transid, false, PBEPASSWORD,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    checkCmpRevokeConfirmMessage(issuerDN, userDN, cert.getSerialNumber(), this.cacert, resp, true);
    int reason = checkRevokeStatus(issuerDN, cert.getSerialNumber());
    assertEquals(reason, RevokedCertInfo.REVOCATION_REASON_CESSATIONOFOPERATION);

}

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

License:Open Source License

/**
 * @param userDN/*from   ww  w  .  j a  v  a  2s  . c om*/
 *            for new certificate.
 * @param keys
 *            key of the new certificate.
 * @param sFailMessage
 *            if !=null then EJBCA is expected to fail. The failure response
 *            message string is checked against this parameter.
 * @return If it is a certificate request that results in a successful certificate issuance, this certificate is returned
 * @throws Exception
 */
private X509Certificate crmfHttpUserTest(X500Name userDN, KeyPair keys, String sFailMessage,
        BigInteger customCertSerno) throws Exception {

    X509Certificate ret = null;
    final byte[] nonce = CmpMessageHelper.createSenderNonce();
    final byte[] transid = CmpMessageHelper.createSenderNonce();
    final int reqId;
    {
        final PKIMessage one = genCertReq(this.issuerDN, userDN, keys, this.cacert, nonce, transid, true, null,
                null, null, customCertSerno, null, null);
        final PKIMessage req = protectPKIMessage(one, false, PBEPASSWORD, 567);

        CertReqMessages ir = (CertReqMessages) req.getBody().getContent();
        reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();
        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, this.issuerDN, userDN, this.cacert, nonce, transid, sFailMessage == null,
                null, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        if (sFailMessage == null) {
            ret = checkCmpCertRepMessage(userDN, this.cacert, resp, reqId);
            // verify if custom cert serial number was used
            if (customCertSerno != null) {
                assertTrue(ret.getSerialNumber().toString(16) + " is not same as expected "
                        + customCertSerno.toString(16), ret.getSerialNumber().equals(customCertSerno));
            }
        } else {
            checkCmpFailMessage(resp, sFailMessage, CmpPKIBodyConstants.ERRORMESSAGE, reqId,
                    PKIFailureInfo.badRequest, PKIFailureInfo.incorrectData);
        }
    }
    {
        // Send a confirm message to the CA
        final String hash = "foo123";
        final PKIMessage con = genCertConfirm(userDN, this.cacert, nonce, transid, hash, reqId);
        assertNotNull(con);
        PKIMessage confirm = protectPKIMessage(con, false, PBEPASSWORD, 567);
        final ByteArrayOutputStream bao = new ByteArrayOutputStream();
        final DEROutputStream out = new DEROutputStream(bao);
        out.writeObject(confirm);
        final byte[] ba = bao.toByteArray();
        // Send request and receive response
        final byte[] resp = sendCmpHttp(ba, 200, cmpAlias);
        checkCmpResponseGeneral(resp, this.issuerDN, userDN, this.cacert, nonce, transid, false, null,
                PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        checkCmpPKIConfirmMessage(userDN, this.cacert, resp);
    }
    return ret;
}

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

License:Open Source License

/**
 * @param userDN for new certificate./* w  ww .j  a  v  a2 s  . com*/
 * @param keys key of the new certificate.
 * @param sFailMessage if !=null then EJBCA is expected to fail. The failure response message string is checked against this parameter.
 * @return X509Certificate the cert produced if test was successful, null for a test that resulted in failure (can be expected if sFailMessage != null)
 * @throws Exception
 */
private X509Certificate crmfHttpUserTest(X500Name userDN, KeyPair keys, String sFailMessage,
        BigInteger customCertSerno, String sigAlg, X509Certificate caCert, String issuerDN) throws Exception {

    // Create a new good user

    X509Certificate cert = null;
    final byte[] nonce = CmpMessageHelper.createSenderNonce();
    final byte[] transid = CmpMessageHelper.createSenderNonce();
    final int reqId;
    {
        final PKIMessage one = genCertReq(issuerDN, userDN, keys, caCert, nonce, transid, true, null, null,
                null, customCertSerno, null, null);
        final PKIMessage req = protectPKIMessage(one, false, PBEPASSWORD, 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, issuerDN, userDN, caCert, nonce, transid, sFailMessage == null, null,
                sigAlg);
        if (sFailMessage == null) {
            cert = checkCmpCertRepMessage(userDN, caCert, resp, reqId);
            // verify if custom cert serial number was used
            if (customCertSerno != null) {
                Assert.assertTrue(cert.getSerialNumber().toString(16) + " is not same as expected "
                        + customCertSerno.toString(16), cert.getSerialNumber().equals(customCertSerno));
            }
        } else {
            checkCmpFailMessage(resp, sFailMessage, CmpPKIBodyConstants.ERRORMESSAGE, reqId,
                    PKIFailureInfo.badRequest, PKIFailureInfo.incorrectData);
        }
    }
    {
        // Send a confirm message to the CA
        final String hash = "foo123";
        final PKIMessage con = genCertConfirm(userDN, caCert, nonce, transid, hash, reqId);
        Assert.assertNotNull(con);
        PKIMessage confirm = protectPKIMessage(con, false, PBEPASSWORD, 567);
        final ByteArrayOutputStream bao = new ByteArrayOutputStream();
        final DEROutputStream out = new DEROutputStream(bao);
        out.writeObject(confirm);
        final byte[] ba = bao.toByteArray();
        // Send request and receive response
        final byte[] resp = sendCmpHttp(ba, 200, cmpAlias);
        checkCmpResponseGeneral(resp, issuerDN, userDN, caCert, nonce, transid, false, null,
                PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        checkCmpPKIConfirmMessage(userDN, caCert, resp);
    }
    return cert;
}

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 w w.ja  v a  2  s  . co  m*/
    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 av a  2 s  .c  o m
        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
        }
    }

}