Example usage for org.bouncycastle.pkcs PKCS10CertificationRequest toASN1Structure

List of usage examples for org.bouncycastle.pkcs PKCS10CertificationRequest toASN1Structure

Introduction

In this page you can find the example usage for org.bouncycastle.pkcs PKCS10CertificationRequest toASN1Structure.

Prototype

public CertificationRequest toASN1Structure() 

Source Link

Document

Return the underlying ASN.1 structure for this request.

Usage

From source file:org.ejbca.core.ejb.ca.sign.SignSessionWithMfg1Test.java

License:Open Source License

/**
 * tests bouncy PKCS10/*from ww  w. j a v a 2 s .  c  o m*/
 * 
 */
@Test
public void testBCPKCS10RSAWithRSASha256WithMGF1CA() throws Exception {
    log.trace(">test19TestBCPKCS10RSAWithRSASha256WithMGF1CA()");
    endEntityManagementSession.setUserStatus(internalAdmin, RSA_MFG1_ENTITY_NAME,
            EndEntityConstants.STATUS_NEW);
    log.debug("Reset status of 'foorsamgf1ca' to NEW");
    // Create certificate request
    PKCS10CertificationRequest req = CertTools.genPKCS10CertificationRequest(
            AlgorithmConstants.SIGALG_SHA256_WITH_RSA_AND_MGF1,
            CertTools.stringToBcX500Name("C=SE, O=AnaTom, CN=" + RSA_MFG1_ENTITY_NAME), rsakeys.getPublic(),
            new DERSet(), rsakeys.getPrivate(), null);
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    DEROutputStream dOut = new DEROutputStream(bOut);
    dOut.writeObject(req.toASN1Structure());
    dOut.close();
    PKCS10CertificationRequest req2 = new PKCS10CertificationRequest(bOut.toByteArray());
    ContentVerifierProvider verifier = CertTools.genContentVerifierProvider(rsakeys.getPublic());
    boolean verify = req2.isSignatureValid(verifier);
    log.debug("Verify returned " + verify);
    assertTrue(verify);
    log.debug("CertificationRequest generated successfully.");
    byte[] bcp10 = bOut.toByteArray();
    PKCS10RequestMessage p10 = new PKCS10RequestMessage(bcp10);
    p10.setUsername("foorsamgf1ca");
    p10.setPassword("foo123");
    ResponseMessage resp = signSession.createCertificate(internalAdmin, p10, X509ResponseMessage.class, null);
    X509Certificate cert = (X509Certificate) CertTools.getCertfromByteArray(resp.getResponseMessage());
    assertNotNull("Failed to create certificate", cert);
    log.debug("Cert=" + cert.toString());
    PublicKey pk = cert.getPublicKey();
    if (pk instanceof RSAPublicKey) {
        RSAPublicKey rsapk = (RSAPublicKey) pk;
        assertEquals(rsapk.getAlgorithm(), "RSA");
    } else {
        assertTrue("Public key is not RSA", false);
    }
    X509Certificate rsamgf1cacacert = (X509Certificate) caSession
            .getCAInfo(internalAdmin, TEST_SHA256_WITH_MFG1_CA_NAME).getCertificateChain().toArray()[0];
    try {
        cert.verify(rsamgf1cacacert.getPublicKey());
    } catch (Exception e) {
        assertTrue("Verify failed: " + e.getMessage(), false);
    }
    // 1.2.840.113549.1.1.10 is SHA256WithRSAAndMGF1
    assertEquals("1.2.840.113549.1.1.10", cert.getSigAlgOID());
    assertEquals("1.2.840.113549.1.1.10", cert.getSigAlgName());
    assertEquals("1.2.840.113549.1.1.10", rsamgf1cacacert.getSigAlgOID());
    assertEquals("1.2.840.113549.1.1.10", rsamgf1cacacert.getSigAlgName());
    log.trace("<test19TestBCPKCS10RSAWithRSASha256WithMGF1CA()");
}

From source file:org.ejbca.core.ejb.ca.sign.SignSessionWithRsaTest.java

License:Open Source License

/**
 * tests bouncy PKCS10//w  w w  .j  a v  a 2  s. co  m
 * 
 */
@Test
public void testBCPKCS10() throws Exception {
    log.trace(">test03TestBCPKCS10()");
    endEntityManagementSession.setUserStatus(internalAdmin, RSA_USERNAME, EndEntityConstants.STATUS_NEW);
    log.debug("Reset status of 'foo' to NEW");
    // Create certificate request
    PKCS10CertificationRequest req = CertTools.genPKCS10CertificationRequest("SHA256WithRSA",
            CertTools.stringToBcX500Name("C=SE, O=AnaTom, CN=foo"), rsakeys.getPublic(), new DERSet(),
            rsakeys.getPrivate(), null);
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    DEROutputStream dOut = new DEROutputStream(bOut);
    dOut.writeObject(req.toASN1Structure());
    dOut.close();
    PKCS10CertificationRequest req2 = new PKCS10CertificationRequest(bOut.toByteArray());
    ContentVerifierProvider verifier = CertTools.genContentVerifierProvider(rsakeys.getPublic());
    boolean verify = req2.isSignatureValid(verifier);
    log.debug("Verify returned " + verify);
    assertTrue(verify);
    log.debug("CertificationRequest generated successfully.");
    byte[] bcp10 = bOut.toByteArray();
    PKCS10RequestMessage p10 = new PKCS10RequestMessage(bcp10);
    p10.setUsername(RSA_USERNAME);
    p10.setPassword("foo123");
    ResponseMessage resp = signSession.createCertificate(internalAdmin, p10, X509ResponseMessage.class, null);
    Certificate cert = CertTools.getCertfromByteArray(resp.getResponseMessage());
    assertNotNull("Failed to create certificate", cert);
    log.debug("Cert=" + cert.toString());
    // Verify error handling
    EndEntityInformation badUserData = new EndEntityInformation();
    int rsacaid = caSession.getCAInfo(internalAdmin, getTestCAName()).getCAId();
    badUserData.setCAId(rsacaid);
    p10 = new PKCS10RequestMessage(bcp10);
    try {
        signSession.createCertificate(internalAdmin, p10, X509ResponseMessage.class, badUserData);
        assertFalse("Was able to create certificate when it should have failed.", true);
    } catch (SignRequestException e) {
        log.info("Expected exception caught (no password supplied): " + e.getMessage());
    }
    log.trace("<test03TestBCPKCS10()");
}

From source file:org.ejbca.core.ejb.ca.sign.SignSessionWithRsaTest.java

License:Open Source License

@Test
public void testProfileSignatureAlgorithm() throws Exception {
    // Create a good certificate profile (good enough), using QC statement
    final String testName = "TESTSIGALG";
    certificateProfileSession.removeCertificateProfile(internalAdmin, testName);
    final CertificateProfile certprof = new CertificateProfile(
            CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
    // Default profile uses "inherit from CA"
    certificateProfileSession.addCertificateProfile(internalAdmin, testName, certprof);
    int cprofile = certificateProfileSession.getCertificateProfileId(testName);
    // Create a good end entity profile (good enough)
    endEntityProfileSession.removeEndEntityProfile(internalAdmin, testName);
    EndEntityProfile profile = new EndEntityProfile();
    profile.addField(DnComponents.COUNTRY);
    profile.addField(DnComponents.COMMONNAME);
    profile.setValue(EndEntityProfile.AVAILCAS, 0, Integer.toString(SecConst.ALLCAS));
    profile.setValue(EndEntityProfile.AVAILCERTPROFILES, 0, Integer.toString(cprofile));
    endEntityProfileSession.addEndEntityProfile(internalAdmin, testName, profile);
    try {// www  . j ava  2  s.c o m
        int eeprofile = endEntityProfileSession.getEndEntityProfileId(testName);
        int rsacaid = caSession.getCAInfo(internalAdmin, getTestCAName()).getCAId();
        EndEntityInformation user = new EndEntityInformation(RSA_USERNAME, "C=SE,CN=testsigalg", rsacaid, null,
                "foo@anatom.nu", new EndEntityType(EndEntityTypes.ENDUSER), eeprofile, cprofile,
                SecConst.TOKEN_SOFT_PEM, 0, null);
        user.setPassword("foo123");
        user.setStatus(EndEntityConstants.STATUS_NEW);
        // Change a user that we know...
        endEntityManagementSession.changeUser(internalAdmin, user, false);
        // Create a P10
        // Create PKCS#10 certificate request
        PKCS10CertificationRequest req = CertTools.genPKCS10CertificationRequest("SHA256WithRSA",
                new X500Name("C=SE,CN=testsigalg"), rsakeys.getPublic(), null, rsakeys.getPrivate(), null);
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        DEROutputStream dOut = new DEROutputStream(bOut);
        dOut.writeObject(req.toASN1Structure());
        dOut.close();
        byte[] p10bytes = bOut.toByteArray();
        PKCS10RequestMessage p10 = new PKCS10RequestMessage(p10bytes);
        p10.setUsername(RSA_USERNAME);
        p10.setPassword("foo123");
        // See if the request message works...
        ResponseMessage resp = signSession.createCertificate(internalAdmin, p10, X509ResponseMessage.class,
                null);
        X509Certificate cert = (X509Certificate) CertTools.getCertfromByteArray(resp.getResponseMessage());
        assertNotNull("Failed to create certificate", cert);
        assertEquals("CN=testsigalg,C=SE", cert.getSubjectDN().getName());
        assertEquals(AlgorithmConstants.SIGALG_SHA1_WITH_RSA, AlgorithmTools.getSignatureAlgorithm(cert));
        // Change so that we can override signature algorithm
        CertificateProfile prof = certificateProfileSession.getCertificateProfile(cprofile);
        prof.setSignatureAlgorithm(AlgorithmConstants.SIGALG_SHA256_WITH_RSA);
        certificateProfileSession.changeCertificateProfile(internalAdmin, testName, prof);
        endEntityManagementSession.changeUser(internalAdmin, user, false);
        resp = signSession.createCertificate(internalAdmin, p10, X509ResponseMessage.class, null);
        cert = (X509Certificate) CertTools.getCertfromByteArray(resp.getResponseMessage());
        assertNotNull("Failed to create certificate", cert);
        assertEquals("CN=testsigalg,C=SE", cert.getSubjectDN().getName());
        assertEquals(AlgorithmConstants.SIGALG_SHA256_WITH_RSA, AlgorithmTools.getSignatureAlgorithm(cert));
    } finally {
        endEntityProfileSession.removeEndEntityProfile(internalAdmin, testName);
        certificateProfileSession.removeCertificateProfile(internalAdmin, testName);
    }
}

From source file:org.ejbca.core.ejb.ca.sign.SignSessionWithRsaTest.java

License:Open Source License

@Test
public void testExtensionOverride() throws Exception {
    final String altnames = "dNSName=foo1.bar.com,dNSName=foo2.bar.com,dNSName=foo3.bar.com,dNSName=foo4.bar.com,dNSName=foo5.bar.com,dNSName=foo6.bar.com,dNSName=foo7.bar.com,"
            + "dNSName=foo8.bar.com,dNSName=foo9.bar.com,dNSName=foo10.bar.com,dNSName=foo11.bar.com,dNSName=foo12.bar.com,dNSName=foo13.bar.com,dNSName=foo14.bar.com,"
            + "dNSName=foo15.bar.com,dNSName=foo16.bar.com,dNSName=foo17.bar.com,dNSName=foo18.bar.com,dNSName=foo19.bar.com,dNSName=foo20.bar.com,dNSName=foo21.bar.com";
    // Create a good certificate profile (good enough), using QC statement
    final String profileName = "TESTEXTENSIONOVERRIDE";
    certificateProfileSession.removeCertificateProfile(internalAdmin, profileName);
    final CertificateProfile certprof = new CertificateProfile(
            CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
    // Default profile does not allow Extension override
    certprof.setValidity(298);/*from   ww w .  j  a  v a2s  .c  o m*/
    certificateProfileSession.addCertificateProfile(internalAdmin, profileName, certprof);
    int cprofile = certificateProfileSession.getCertificateProfileId(profileName);
    // Create a good end entity profile (good enough), allowing multiple UPN
    // names
    endEntityProfileSession.removeEndEntityProfile(internalAdmin, profileName);
    EndEntityProfile profile = new EndEntityProfile();
    profile.addField(DnComponents.COUNTRY);
    profile.addField(DnComponents.COMMONNAME);
    profile.setValue(EndEntityProfile.AVAILCAS, 0, Integer.toString(SecConst.ALLCAS));
    profile.setValue(EndEntityProfile.AVAILCERTPROFILES, 0, Integer.toString(cprofile));
    endEntityProfileSession.addEndEntityProfile(internalAdmin, profileName, profile);
    try {
        int eeprofile = endEntityProfileSession.getEndEntityProfileId(profileName);
        int rsacaid = caSession.getCAInfo(internalAdmin, getTestCAName()).getCAId();
        EndEntityInformation user = new EndEntityInformation(RSA_USERNAME, "C=SE,CN=extoverride", rsacaid, null,
                "foo@anatom.nu", new EndEntityType(EndEntityTypes.ENDUSER), eeprofile, cprofile,
                SecConst.TOKEN_SOFT_PEM, 0, null);
        user.setPassword("foo123");
        user.setStatus(EndEntityConstants.STATUS_NEW);
        // Change a user that we know...
        endEntityManagementSession.changeUser(internalAdmin, user, false);
        // Create a P10 with extensions, in this case altNames with a lot of DNS
        // names
        ASN1EncodableVector extensionattr = new ASN1EncodableVector();
        extensionattr.add(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
        GeneralNames san = CertTools.getGeneralNamesFromAltName(altnames);
        ExtensionsGenerator extgen = new ExtensionsGenerator();
        extgen.addExtension(Extension.subjectAlternativeName, false, san);
        Extensions exts = extgen.generate();
        extensionattr.add(new DERSet(exts));
        // Complete the Attribute section of the request, the set (Attributes)
        // contains one sequence (Attribute)
        ASN1EncodableVector v = new ASN1EncodableVector();
        v.add(new DERSequence(extensionattr));
        DERSet attributes = new DERSet(v);
        // Create PKCS#10 certificate request
        PKCS10CertificationRequest req = CertTools.genPKCS10CertificationRequest("SHA256WithRSA",
                new X500Name("C=SE,CN=extoverride"), rsakeys.getPublic(), attributes, rsakeys.getPrivate(),
                null);
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        DEROutputStream dOut = new DEROutputStream(bOut);
        dOut.writeObject(req.toASN1Structure());
        dOut.close();
        byte[] p10bytes = bOut.toByteArray();
        PKCS10RequestMessage p10 = new PKCS10RequestMessage(p10bytes);
        p10.setUsername(RSA_USERNAME);
        p10.setPassword("foo123");
        // See if the request message works...
        Extensions p10exts = p10.getRequestExtensions();
        assertNotNull(p10exts);
        ResponseMessage resp = signSession.createCertificate(internalAdmin, p10, X509ResponseMessage.class,
                null);
        X509Certificate cert = (X509Certificate) CertTools.getCertfromByteArray(resp.getResponseMessage());
        assertNotNull("Failed to create certificate", cert);
        assertEquals("CN=extoverride,C=SE", cert.getSubjectDN().getName());
        // check altNames, should be none
        Collection<List<?>> c = cert.getSubjectAlternativeNames();
        assertNull(c);
        // Change so that we allow override of validity time
        CertificateProfile prof = certificateProfileSession.getCertificateProfile(cprofile);
        prof.setAllowExtensionOverride(true);
        certificateProfileSession.changeCertificateProfile(internalAdmin, profileName, prof);
        endEntityManagementSession.changeUser(internalAdmin, user, false);
        resp = signSession.createCertificate(internalAdmin, p10, X509ResponseMessage.class, null);
        cert = (X509Certificate) CertTools.getCertfromByteArray(resp.getResponseMessage());
        assertNotNull("Failed to create certificate", cert);
        assertEquals("CN=extoverride,C=SE", cert.getSubjectDN().getName());
        // check altNames, should be one altName
        c = cert.getSubjectAlternativeNames();
        assertNotNull(c);
        assertEquals(21, c.size());
        String retAltNames = CertTools.getSubjectAlternativeName(cert);
        List<String> originalNames = Arrays.asList(altnames.split(","));
        List<String> returnNames = Arrays.asList(retAltNames.split(", "));
        assertTrue(originalNames.containsAll(returnNames));
    } finally {
        certificateProfileSession.removeCertificateProfile(internalAdmin, profileName);
        endEntityProfileSession.removeEndEntityProfile(internalAdmin, profileName);
    }
}

From source file:org.ejbca.core.ejb.ca.sign.SignSessionWithRsaTest.java

License:Open Source License

@Test
public void testDNOverride() throws Exception {
    // Create a good certificate profile (good enough), using QC statement
    certificateProfileSession.removeCertificateProfile(internalAdmin, "TESTDNOVERRIDE");
    final CertificateProfile certprof = new CertificateProfile(
            CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
    // Default profile does not allow DN override
    certprof.setValidity(298);//w w  w .j a va  2  s .  c  o m
    certificateProfileSession.addCertificateProfile(internalAdmin, "TESTDNOVERRIDE", certprof);
    int cprofile = certificateProfileSession.getCertificateProfileId("TESTDNOVERRIDE");
    // Create a good end entity profile (good enough), allowing multiple UPN
    // names
    endEntityProfileSession.removeEndEntityProfile(internalAdmin, "TESTDNOVERRIDE");
    EndEntityProfile profile = new EndEntityProfile();
    profile.addField(DnComponents.COUNTRY);
    profile.addField(DnComponents.COMMONNAME);
    profile.setValue(EndEntityProfile.AVAILCAS, 0, Integer.toString(SecConst.ALLCAS));
    profile.setValue(EndEntityProfile.AVAILCERTPROFILES, 0, Integer.toString(cprofile));
    endEntityProfileSession.addEndEntityProfile(internalAdmin, "TESTDNOVERRIDE", profile);
    int eeprofile = endEntityProfileSession.getEndEntityProfileId("TESTDNOVERRIDE");
    int rsacaid = caSession.getCAInfo(internalAdmin, getTestCAName()).getCAId();
    final String dnOverrideEndEntityName = "DnOverride";
    createEndEntity(dnOverrideEndEntityName, eeprofile, cprofile, rsacaid);
    try {
        EndEntityInformation user = new EndEntityInformation(dnOverrideEndEntityName, "C=SE,CN=dnoverride",
                rsacaid, null, "foo@anatom.nu", new EndEntityType(EndEntityTypes.ENDUSER), eeprofile, cprofile,
                SecConst.TOKEN_SOFT_PEM, 0, null);
        user.setPassword("foo123");
        user.setStatus(EndEntityConstants.STATUS_NEW);
        // Change a user that we know...
        endEntityManagementSession.changeUser(internalAdmin, user, false);
        // Create a P10 with strange order DN
        PKCS10CertificationRequest req = CertTools.genPKCS10CertificationRequest("SHA256WithRSA",
                new X500Name("CN=foo,C=SE,NAME=AnaTom,O=My org"), rsakeys.getPublic(), new DERSet(),
                rsakeys.getPrivate(), null);
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        DEROutputStream dOut = new DEROutputStream(bOut);
        dOut.writeObject(req.toASN1Structure());
        dOut.close();
        PKCS10CertificationRequest req2 = new PKCS10CertificationRequest(bOut.toByteArray());
        ContentVerifierProvider verifier = CertTools.genContentVerifierProvider(rsakeys.getPublic());
        boolean verify = req2.isSignatureValid(verifier);
        log.debug("Verify returned " + verify);
        assertTrue(verify);
        log.debug("CertificationRequest generated successfully.");
        byte[] bcp10 = bOut.toByteArray();
        PKCS10RequestMessage p10 = new PKCS10RequestMessage(bcp10);
        p10.setUsername(dnOverrideEndEntityName);
        p10.setPassword("foo123");
        ResponseMessage resp = signSession.createCertificate(internalAdmin, p10, X509ResponseMessage.class,
                null);
        X509Certificate cert = (X509Certificate) CertTools.getCertfromByteArray(resp.getResponseMessage());
        assertNotNull("Failed to create certificate", cert);
        assertEquals("CN=dnoverride,C=SE", cert.getSubjectDN().getName());
        // Change so that we allow override of validity time
        CertificateProfile prof = certificateProfileSession.getCertificateProfile(cprofile);
        prof.setAllowDNOverride(true);
        certificateProfileSession.changeCertificateProfile(internalAdmin, "TESTDNOVERRIDE", prof);
        endEntityManagementSession.changeUser(internalAdmin, user, false);
        resp = signSession.createCertificate(internalAdmin, p10, X509ResponseMessage.class, null);
        cert = (X509Certificate) CertTools.getCertfromByteArray(resp.getResponseMessage());
        assertNotNull("Failed to create certificate", cert);
        assertEquals("CN=foo,C=SE,Name=AnaTom,O=My org", cert.getSubjectDN().getName());
    } finally {
        endEntityManagementSession.deleteUser(internalAdmin, dnOverrideEndEntityName);
    }
}

From source file:org.ejbca.core.ejb.ca.sign.SignSessionWithRsaTest.java

License:Open Source License

@Test
public void testBCPKCS10DSAWithRSACA() throws Exception {
    log.trace(">test24TestBCPKCS10DSAWithRSACA()");

    endEntityManagementSession.setUserStatus(internalAdmin, RSA_USERNAME, EndEntityConstants.STATUS_NEW);
    log.debug("Reset status of 'foo' to NEW");
    // Create certificate request
    KeyPair dsakeys = KeyTools.genKeys("1024", AlgorithmConstants.KEYALGORITHM_DSA);
    PKCS10CertificationRequest req = CertTools.genPKCS10CertificationRequest("SHA1WithDSA",
            CertTools.stringToBcX500Name("C=SE, O=AnaTom, CN=foo"), dsakeys.getPublic(), new DERSet(),
            dsakeys.getPrivate(), null);
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    DEROutputStream dOut = new DEROutputStream(bOut);
    dOut.writeObject(req.toASN1Structure());
    dOut.close();//from w  w  w.  j  a  v  a2s.c  om

    PKCS10CertificationRequest req2 = new PKCS10CertificationRequest(bOut.toByteArray());
    ContentVerifierProvider verifier = CertTools.genContentVerifierProvider(dsakeys.getPublic());
    boolean verify = req2.isSignatureValid(verifier);
    log.debug("Verify returned " + verify);
    assertTrue(verify);
    log.debug("CertificationRequest generated successfully.");
    byte[] bcp10 = bOut.toByteArray();
    PKCS10RequestMessage p10 = new PKCS10RequestMessage(bcp10);
    p10.setUsername(RSA_USERNAME);
    p10.setPassword("foo123");
    ResponseMessage resp = signSession.createCertificate(internalAdmin, p10, X509ResponseMessage.class, null);
    Certificate cert = CertTools.getCertfromByteArray(resp.getResponseMessage());
    assertNotNull("Failed to create certificate", cert);
    log.debug("Cert=" + cert.toString());
    PublicKey pk = cert.getPublicKey();
    if (pk instanceof DSAPublicKey) {
        DSAPublicKey dsapk = (DSAPublicKey) pk;
        assertEquals(dsapk.getAlgorithm(), "DSA");
    } else {
        fail("Public key is not DSA");
    }
    try {
        X509Certificate rsacacert = (X509Certificate) caSession.getCAInfo(internalAdmin, getTestCAName())
                .getCertificateChain().toArray()[0];
        cert.verify(rsacacert.getPublicKey());
    } catch (Exception e) {
        fail("Verify failed: " + e.getMessage());
    }
    log.trace("<test24TestBCPKCS10DSAWithRSACA()");
}

From source file:org.ejbca.core.protocol.ws.EjbcaWSTest.java

License:Open Source License

/**
 * Tests that the provided cardnumber is stored in the EndEntityInformation 
 * and that when querying for EndEntityInformation the cardnumber is 
 * returned./*from   w w  w .  j a va 2  s . c  o m*/
 * @throws Exception in case of error
 */
@Test
public void test48CertificateRequestWithCardNumber() throws Exception {
    String userName = "wsRequestCardNumber" + new SecureRandom().nextLong();

    // Generate a CSR
    KeyPair keys = KeyTools.genKeys("1024", AlgorithmConstants.KEYALGORITHM_RSA);
    PKCS10CertificationRequest pkcs10 = CertTools.genPKCS10CertificationRequest("SHA256WithRSA",
            CertTools.stringToBcX500Name("CN=NOUSED"), keys.getPublic(), new DERSet(), keys.getPrivate(), null);
    final String csr = new String(Base64.encode(pkcs10.toASN1Structure().getEncoded()));

    // Set some user data
    final UserDataVOWS userData = new UserDataVOWS();
    userData.setUsername(userName);
    userData.setPassword(PASSWORD);
    userData.setClearPwd(true);
    userData.setSubjectDN("CN=test" + secureRandom.nextLong() + ", UID=" + userName + ", O=Test, C=SE");
    userData.setCaName(getAdminCAName());
    userData.setEmail(null);
    userData.setSubjectAltName(null);
    userData.setStatus(UserDataVOWS.STATUS_NEW);
    userData.setTokenType(UserDataVOWS.TOKEN_TYPE_P12);
    userData.setEndEntityProfileName("EMPTY");
    userData.setCertificateProfileName("ENDUSER");

    // Set the card number
    userData.setCardNumber("1234fa");

    // Issue a certificate
    CertificateResponse response = ejbcaraws.certificateRequest(userData, csr,
            CertificateHelper.CERT_REQ_TYPE_PKCS10, null, CertificateHelper.RESPONSETYPE_CERTIFICATE);
    assertNotNull("null response", response);

    // Check that the cardnumber was stored in the EndEntityInformation
    EndEntityInformation endEntity = endEntityAccessSession.findUser(intAdmin, userName);
    assertEquals("stored cardnumber ejb", "1234fa", endEntity.getCardNumber());

    // Check that the cardnumber is also available when querying using WS
    UserMatch criteria = new UserMatch();
    criteria.setMatchtype(UserMatch.MATCH_TYPE_EQUALS);
    criteria.setMatchwith(UserMatch.MATCH_WITH_USERNAME);
    criteria.setMatchvalue(userName);
    UserDataVOWS user = ejbcaraws.findUser(criteria).get(0);
    assertEquals("stored cardnumber ws", "1234fa", user.getCardNumber());
}

From source file:org.ejbca.core.protocol.ws.EjbcaWSTest.java

License:Open Source License

private void testCertificateRequestWithEeiDnOverride(boolean allowDNOverrideByEndEntityInformation,
        boolean useCsr, String requestedSubjectDN, String expectedSubjectDN) throws Exception {
    if (certificateProfileSession.getCertificateProfileId(WS_TEST_CERTIFICATE_PROFILE_NAME) != 0) {
        certificateProfileSession.removeCertificateProfile(intAdmin, WS_TEST_CERTIFICATE_PROFILE_NAME);
    }//from w  w w . j  a v a  2s  . c o  m
    CertificateProfile profile = new CertificateProfile(CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
    profile.setAllowDNOverrideByEndEntityInformation(allowDNOverrideByEndEntityInformation);
    certificateProfileSession.addCertificateProfile(intAdmin, WS_TEST_CERTIFICATE_PROFILE_NAME, profile);
    //This test will fail if EEP limitations are enabled
    GlobalConfiguration originalConfiguration = (GlobalConfiguration) globalConfigurationSession
            .getCachedConfiguration(GlobalConfiguration.GLOBAL_CONFIGURATION_ID);
    GlobalConfiguration globalConfiguration = (GlobalConfiguration) globalConfigurationSession
            .getCachedConfiguration(GlobalConfiguration.GLOBAL_CONFIGURATION_ID);
    globalConfiguration.setEnableEndEntityProfileLimitations(false);
    globalConfigurationSession.saveConfiguration(intAdmin, globalConfiguration);
    try {
        String userName = "eeiDnOverride" + secureRandom.nextLong();
        final UserDataVOWS userData = new UserDataVOWS();
        userData.setUsername(userName);
        userData.setPassword(PASSWORD);
        userData.setClearPwd(true);
        userData.setSubjectDN(requestedSubjectDN);
        userData.setCaName(getAdminCAName());
        userData.setEmail(null);
        userData.setSubjectAltName(null);
        userData.setStatus(UserDataVOWS.STATUS_NEW);
        userData.setTokenType(UserDataVOWS.TOKEN_TYPE_P12);
        userData.setEndEntityProfileName("EMPTY");
        userData.setCertificateProfileName(WS_TEST_CERTIFICATE_PROFILE_NAME);
        final X509Certificate cert;
        if (useCsr) {
            KeyPair keys = KeyTools.genKeys("1024", AlgorithmConstants.KEYALGORITHM_RSA);
            PKCS10CertificationRequest pkcs10 = CertTools.genPKCS10CertificationRequest("SHA256WithRSA",
                    CertTools.stringToBcX500Name("CN=NOUSED"), keys.getPublic(), new DERSet(),
                    keys.getPrivate(), null);
            final String csr = new String(Base64.encode(pkcs10.toASN1Structure().getEncoded()));
            CertificateResponse response = ejbcaraws.certificateRequest(userData, csr,
                    CertificateHelper.CERT_REQ_TYPE_PKCS10, null, CertificateHelper.RESPONSETYPE_CERTIFICATE);
            cert = response.getCertificate();
        } else {
            KeyStore ksenv = ejbcaraws.softTokenRequest(userData, null, "1024",
                    AlgorithmConstants.KEYALGORITHM_RSA);
            java.security.KeyStore keyStore = KeyStoreHelper.getKeyStore(ksenv.getKeystoreData(), "PKCS12",
                    PASSWORD);
            assertNotNull(keyStore);
            Enumeration<String> en = keyStore.aliases();
            String alias = en.nextElement();
            if (!keyStore.isKeyEntry(alias)) {
                alias = en.nextElement();
            }
            cert = (X509Certificate) keyStore.getCertificate(alias);
        }
        final List<Certificate> certificates = Arrays.asList(new Certificate[] { cert });
        log.info(certificates.size() + " certs.\n"
                + new String(CertTools.getPemFromCertificateChain(certificates)));
        X500Name x500name = new JcaX509CertificateHolder(cert).getSubject();
        String resultingSubjectDN = CeSecoreNameStyle.INSTANCE.toString(x500name);
        log.debug("x500name:           " + resultingSubjectDN);
        assertEquals("Unexpected transformation.", expectedSubjectDN, resultingSubjectDN);
        try {
            endEntityManagementSession.deleteUser(intAdmin, userName);
        } catch (NotFoundException e) {
            // Ignore
        }
    } finally {
        if (certificateProfileSession.getCertificateProfileId(WS_TEST_CERTIFICATE_PROFILE_NAME) != 0) {
            certificateProfileSession.removeCertificateProfile(intAdmin, WS_TEST_CERTIFICATE_PROFILE_NAME);
        }
        globalConfigurationSession.saveConfiguration(intAdmin, originalConfiguration);
    }
}

From source file:org.ejbca.samples.HttpGetCert.java

License:Open Source License

/**
 * DOCUMENT ME!/*from   ww  w  . j  ava  2s.  c  om*/
 *
 * @param args DOCUMENT ME!
 *
 * @throws Exception DOCUMENT ME!
 */
public static void main(String[] args) throws Exception {
    //Configure Log4j
    BasicConfigurator.configure();

    // Install BouncyCastle provider
    CryptoProviderTools.installBCProvider();

    // Generate keys (512 bit for sample purposes)
    System.out.print("Generating 512 bit RSA keys.");

    KeyPair rsaKeys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
    System.out.println("Keys generated.");

    // Generate PKCS10 certificate request
    PKCS10CertificationRequest req = CertTools.genPKCS10CertificationRequest("SHA1WithRSA",
            CertTools.stringToBcX500Name("C=SE,O=AnaTom,CN=HttpTest"), rsaKeys.getPublic(), new DERSet(),
            rsaKeys.getPrivate(), null);
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    DEROutputStream dOut = new DEROutputStream(bOut);
    dOut.writeObject(req.toASN1Structure());
    dOut.close();

    ByteArrayOutputStream bos1 = new ByteArrayOutputStream();
    bos1.write("-----BEGIN CERTIFICATE REQUEST-----\n".getBytes());
    bos1.write(Base64.encode(bOut.toByteArray()));
    bos1.write("\n-----END CERTIFICATE REQUEST-----\n".getBytes());
    bos1.close();
    System.out.println("CertificationRequest generated:");
    System.out.println(new String(bos1.toByteArray()));

    // Now send the request
    System.out.println("Trying to send request...");

    HttpGetCert getter = new HttpGetCert();
    getter.sendHttpReq("http://127.0.0.1:8080/apply/certreq", new String(bos1.toByteArray()), "foo", "foo123");
}

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

License:Open Source License

protected void makeCertRequest(String dn, KeyPair rsaKeys, String reqfile)
        throws NoSuchAlgorithmException, IOException, NoSuchProviderException, InvalidKeyException,
        SignatureException, OperatorCreationException, PKCSException {
    log.trace(">makeCertRequest: dn='" + dn + "', reqfile='" + reqfile + "'.");

    PKCS10CertificationRequest req = CertTools.genPKCS10CertificationRequest("SHA1WithRSA",
            CertTools.stringToBcX500Name(dn), rsaKeys.getPublic(), new DERSet(), rsaKeys.getPrivate(), null);

    /*/*from   w w w.  j  a v  a  2  s.  c o  m*/
     * We don't use these unnecessary attributes DERConstructedSequence kName
     * = new DERConstructedSequence(); DERConstructedSet kSeq = new
     * DERConstructedSet();
     * kName.addObject(PKCSObjectIdentifiers.pkcs_9_at_emailAddress);
     * kSeq.addObject(new DERIA5String("foo@bar.se"));
     * kName.addObject(kSeq); req.setAttributes(kName);
     */
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    DEROutputStream dOut = new DEROutputStream(bOut);
    dOut.writeObject(req.toASN1Structure());
    dOut.close();

    PKCS10CertificationRequest req2 = new PKCS10CertificationRequest(bOut.toByteArray());
    ContentVerifierProvider contentVerifier = CertTools.genContentVerifierProvider(rsaKeys.getPublic());
    boolean verify = req2.isSignatureValid(contentVerifier); //req2.verify();
    log.info("Verify returned " + verify);

    if (verify == false) {
        log.info("Aborting!");
        return;
    }

    FileOutputStream os1 = new FileOutputStream(reqfile);
    os1.write("-----BEGIN CERTIFICATE REQUEST-----\n".getBytes());
    os1.write(Base64.encode(bOut.toByteArray()));
    os1.write("\n-----END CERTIFICATE REQUEST-----\n".getBytes());
    os1.close();
    log.info("CertificationRequest '" + reqfile + "' generated successfully.");
    log.trace("<makeCertRequest: dn='" + dn + "', reqfile='" + reqfile + "'.");
}