Example usage for org.bouncycastle.pkcs.jcajce JcaPKCS10CertificationRequest getSubject

List of usage examples for org.bouncycastle.pkcs.jcajce JcaPKCS10CertificationRequest getSubject

Introduction

In this page you can find the example usage for org.bouncycastle.pkcs.jcajce JcaPKCS10CertificationRequest getSubject.

Prototype

public X500Name getSubject() 

Source Link

Document

Return the subject on this request.

Usage

From source file:org.apache.nifi.toolkit.tls.service.client.TlsCertificateSigningRequestPerformerTest.java

License:Apache License

@Before
public void setup() throws GeneralSecurityException, OperatorCreationException, IOException {
    objectMapper = new ObjectMapper();
    keyPair = TlsHelper.generateKeyPair(TlsConfig.DEFAULT_KEY_PAIR_ALGORITHM, TlsConfig.DEFAULT_KEY_SIZE);

    testToken = "testToken";
    testCaHostname = "testCaHostname";
    testPort = 8993;/*w  w w  .  j  a v  a2 s  . c  o m*/
    certificates = new ArrayList<>();

    when(tlsClientConfig.getToken()).thenReturn(testToken);
    when(tlsClientConfig.getCaHostname()).thenReturn(testCaHostname);
    when(tlsClientConfig.getDn()).thenReturn(new TlsConfig().calcDefaultDn(testCaHostname));
    when(tlsClientConfig.getPort()).thenReturn(testPort);
    when(tlsClientConfig.createCertificateSigningRequestPerformer())
            .thenReturn(tlsCertificateSigningRequestPerformer);
    when(tlsClientConfig.getSigningAlgorithm()).thenReturn(TlsConfig.DEFAULT_SIGNING_ALGORITHM);
    JcaPKCS10CertificationRequest jcaPKCS10CertificationRequest = TlsHelper.generateCertificationRequest(
            tlsClientConfig.getDn(), null, keyPair, TlsConfig.DEFAULT_SIGNING_ALGORITHM);
    String testCsrPem = TlsHelper.pemEncodeJcaObject(jcaPKCS10CertificationRequest);
    when(httpClientBuilderSupplier.get()).thenReturn(httpClientBuilder);
    when(httpClientBuilder.build()).thenAnswer(invocation -> {
        Field sslSocketFactory = HttpClientBuilder.class.getDeclaredField("sslSocketFactory");
        sslSocketFactory.setAccessible(true);
        Object o = sslSocketFactory.get(httpClientBuilder);
        Field field = TlsCertificateAuthorityClientSocketFactory.class.getDeclaredField("certificates");
        field.setAccessible(true);
        ((List<X509Certificate>) field.get(o)).addAll(certificates);
        return closeableHttpClient;
    });
    StatusLine statusLine = mock(StatusLine.class);
    when(statusLine.getStatusCode()).thenAnswer(i -> statusCode);
    when(closeableHttpClient.execute(eq(new HttpHost(testCaHostname, testPort, "https")), any(HttpPost.class)))
            .thenAnswer(invocation -> {
                HttpPost httpPost = (HttpPost) invocation.getArguments()[1];
                TlsCertificateAuthorityRequest tlsCertificateAuthorityRequest = objectMapper
                        .readValue(httpPost.getEntity().getContent(), TlsCertificateAuthorityRequest.class);
                assertEquals(tlsCertificateAuthorityRequest.getCsr(), testCsrPem);
                CloseableHttpResponse closeableHttpResponse = mock(CloseableHttpResponse.class);
                when(closeableHttpResponse.getEntity()).thenAnswer(i -> {
                    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                    objectMapper.writeValue(byteArrayOutputStream, tlsCertificateAuthorityResponse);
                    return new ByteArrayEntity(byteArrayOutputStream.toByteArray());
                });
                when(closeableHttpResponse.getStatusLine()).thenReturn(statusLine);
                return closeableHttpResponse;
            });
    KeyPair caKeyPair = TlsHelper.generateKeyPair(TlsConfig.DEFAULT_KEY_PAIR_ALGORITHM,
            TlsConfig.DEFAULT_KEY_SIZE);
    caCertificate = CertificateUtils.generateSelfSignedX509Certificate(caKeyPair, "CN=fakeCa",
            TlsConfig.DEFAULT_SIGNING_ALGORITHM, TlsConfig.DEFAULT_DAYS);
    testHmac = TlsHelper.calculateHMac(testToken, caCertificate.getPublicKey());
    signedCsr = CertificateUtils.generateIssuedCertificate(
            jcaPKCS10CertificationRequest.getSubject().toString(), jcaPKCS10CertificationRequest.getPublicKey(),
            caCertificate, caKeyPair, TlsConfig.DEFAULT_SIGNING_ALGORITHM, TlsConfig.DEFAULT_DAYS);
    testSignedCsr = TlsHelper.pemEncodeJcaObject(signedCsr);

    tlsCertificateSigningRequestPerformer = new TlsCertificateSigningRequestPerformer(httpClientBuilderSupplier,
            tlsClientConfig);
}

From source file:org.apache.nifi.toolkit.tls.service.server.TlsCertificateAuthorityServiceHandler.java

License:Apache License

@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    try {/* www  . j a  v  a 2  s.  co  m*/
        TlsCertificateAuthorityRequest tlsCertificateAuthorityRequest = objectMapper.readValue(
                new BoundedReader(request.getReader(), 1024 * 1024), TlsCertificateAuthorityRequest.class);

        if (!tlsCertificateAuthorityRequest.hasHmac()) {
            writeResponse(objectMapper, request, response,
                    new TlsCertificateAuthorityResponse(HMAC_FIELD_MUST_BE_SET), Response.SC_BAD_REQUEST);
            return;
        }

        if (!tlsCertificateAuthorityRequest.hasCsr()) {
            writeResponse(objectMapper, request, response,
                    new TlsCertificateAuthorityResponse(CSR_FIELD_MUST_BE_SET), Response.SC_BAD_REQUEST);
            return;
        }

        JcaPKCS10CertificationRequest jcaPKCS10CertificationRequest = TlsHelper
                .parseCsr(tlsCertificateAuthorityRequest.getCsr());
        byte[] expectedHmac = TlsHelper.calculateHMac(token, jcaPKCS10CertificationRequest.getPublicKey());

        if (MessageDigest.isEqual(expectedHmac, tlsCertificateAuthorityRequest.getHmac())) {
            String dn = jcaPKCS10CertificationRequest.getSubject().toString();
            if (logger.isInfoEnabled()) {
                logger.info("Received CSR with DN " + dn);
            }
            X509Certificate x509Certificate = CertificateUtils.generateIssuedCertificate(dn,
                    jcaPKCS10CertificationRequest.getPublicKey(),
                    CertificateUtils.getExtensionsFromCSR(jcaPKCS10CertificationRequest), caCert, keyPair,
                    signingAlgorithm, days);
            writeResponse(objectMapper, request, response,
                    new TlsCertificateAuthorityResponse(TlsHelper.calculateHMac(token, caCert.getPublicKey()),
                            TlsHelper.pemEncodeJcaObject(x509Certificate)),
                    Response.SC_OK);
            return;
        } else {
            writeResponse(objectMapper, request, response, new TlsCertificateAuthorityResponse(FORBIDDEN),
                    Response.SC_FORBIDDEN);
            return;
        }
    } catch (Exception e) {
        throw new ServletException("Server error");
    } finally {
        baseRequest.setHandled(true);
    }
}

From source file:org.apache.nifi.toolkit.tls.util.TlsHelperTest.java

License:Apache License

@Test
public void testShouldIncludeSANFromCSR() throws Exception {
    // Arrange//from w  w  w.  ja v a2  s .c o m
    final List<String> SAN_ENTRIES = Arrays.asList("127.0.0.1", "nifi.nifi.apache.org");
    final String SAN = StringUtils.join(SAN_ENTRIES, ",");
    final int SAN_COUNT = SAN_ENTRIES.size();
    final String DN = "CN=localhost";
    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    logger.info("Generating CSR with DN: " + DN);

    // Act
    JcaPKCS10CertificationRequest csrWithSan = TlsHelper.generateCertificationRequest(DN, SAN, keyPair,
            TlsConfig.DEFAULT_SIGNING_ALGORITHM);
    logger.info("Created CSR with SAN: " + SAN);
    String testCsrPem = TlsHelper.pemEncodeJcaObject(csrWithSan);
    logger.info("Encoded CSR as PEM: " + testCsrPem);

    // Assert
    String subjectName = csrWithSan.getSubject().toString();
    logger.info("CSR Subject Name: " + subjectName);
    assert subjectName.equals(DN);

    List<String> extractedSans = extractSanFromCsr(csrWithSan);
    assert extractedSans.size() == SAN_COUNT + 1;
    List<String> formattedSans = SAN_ENTRIES.stream().map(s -> "DNS: " + s).collect(Collectors.toList());
    assert extractedSans.containsAll(formattedSans);

    // We check that the SANs also contain the CN
    assert extractedSans.contains("DNS: localhost");
}

From source file:org.cesecore.keybind.InternalKeyBindingMgmtTest.java

License:Open Source License

@Test
public void workflowIssueCertFromCsrUpdateAndRenew() throws Exception {
    final String TEST_METHOD_NAME = Thread.currentThread().getStackTrace()[1].getMethodName();
    final String KEY_BINDING_NAME = TEST_METHOD_NAME;
    final String KEY_PAIR_ALIAS = TEST_METHOD_NAME;
    final String endEntityId = TESTCLASSNAME + "_" + TEST_METHOD_NAME;
    // Clean up old key binding
    removeInternalKeyBindingByName(alwaysAllowToken, TEST_METHOD_NAME);
    int internalKeyBindingId = 0;
    String certFpToDelete = null;
    try {/*from  w  w w  . j  a v  a2  s.c om*/
        // First create a new CryptoToken
        cryptoTokenManagementSession.createKeyPair(alwaysAllowToken, cryptoTokenId, KEY_PAIR_ALIAS, "RSA2048");
        // Create a new InternalKeyBinding with a implementation specific property and bind it to the previously generated key
        final Map<String, Serializable> dataMap = new LinkedHashMap<String, Serializable>();
        dataMap.put(PROPERTY_ALIAS, Boolean.FALSE);
        internalKeyBindingId = internalKeyBindingMgmtSession.createInternalKeyBinding(alwaysAllowToken,
                KEYBINDING_TYPE_ALIAS, KEY_BINDING_NAME, InternalKeyBindingStatus.ACTIVE, null, cryptoTokenId,
                KEY_PAIR_ALIAS, AlgorithmConstants.SIGALG_SHA1_WITH_RSA, dataMap, null);
        // Add a user to EJBCA for the renewal later on
        final EndEntityInformation endEntityInformation = new EndEntityInformation(endEntityId,
                "CN=" + TESTCLASSNAME + "_" + TEST_METHOD_NAME, x509ca.getCAId(), null, null,
                EndEntityTypes.ENDUSER.toEndEntityType(), 1,
                CertificateProfileConstants.CERTPROFILE_FIXED_OCSPSIGNER, EndEntityConstants.TOKEN_USERGEN, 0,
                null);
        endEntityInformation.setPassword("foo123");
        // Request a CSR for the key pair
        // First make a couple of requests with different DN to see that that part works
        final X500Name x500name = CertTools.stringToBcX500Name("CN=name,O=org,C=SE", false);
        final byte[] csr = internalKeyBindingMgmtSession.generateCsrForNextKey(alwaysAllowToken,
                internalKeyBindingId, x500name.getEncoded());
        final JcaPKCS10CertificationRequest jcareq = new JcaPKCS10CertificationRequest(csr);
        assertEquals("Wrong order of DN, should be X500 with C first", "C=SE,O=org,CN=name",
                jcareq.getSubject().toString());
        final X500Name x500name2 = CertTools.stringToBcX500Name("CN=name,O=org,C=SE", true);
        final byte[] csr2 = internalKeyBindingMgmtSession.generateCsrForNextKey(alwaysAllowToken,
                internalKeyBindingId, x500name2.getEncoded());
        final JcaPKCS10CertificationRequest jcareq2 = new JcaPKCS10CertificationRequest(csr2);
        assertEquals("Wrong order of DN, should be LDAP with CN first", "CN=name,O=org,C=SE",
                jcareq2.getSubject().toString());
        // Now make the request that we will actually use
        final byte[] csr3 = internalKeyBindingMgmtSession.generateCsrForNextKey(alwaysAllowToken,
                internalKeyBindingId, null);
        final RequestMessage req = new PKCS10RequestMessage(csr3);
        assertEquals("CN=" + KEY_BINDING_NAME, req.getRequestDN());
        X509Certificate keyBindingCertificate = (X509Certificate) (((X509ResponseMessage) certificateCreateSession
                .createCertificate(alwaysAllowToken, endEntityInformation, req, X509ResponseMessage.class,
                        signSession.fetchCertGenParams())).getCertificate());
        certFpToDelete = CertTools.getFingerprintAsString(keyBindingCertificate);
        // Ask the key binding to search the database for a new certificate matching its public key
        final String boundCertificateFingerprint = internalKeyBindingMgmtSession
                .updateCertificateForInternalKeyBinding(alwaysAllowToken, internalKeyBindingId);
        // Verify that it was the right certificate it found
        assertEquals("Wrong certificate was found for InternalKeyBinding",
                CertTools.getFingerprintAsString(keyBindingCertificate), boundCertificateFingerprint);
        // ...so now we have a mapping between a certificate in the database and a key pair in a CryptoToken
        // Since we no have a certificate issued by an internal CA, we should be able to renew it
        final String renewedCertificateFingerprint = internalKeyBindingMgmtSession
                .renewInternallyIssuedCertificate(alwaysAllowToken, internalKeyBindingId, endEntityInformation);
        assertNotNull("Renewal returned null which is an undefined state.", renewedCertificateFingerprint);
        assertFalse("After certificate renewal the same certificate was returned",
                boundCertificateFingerprint.equals(renewedCertificateFingerprint));
        final String actualCertificateFingerprint = internalKeyBindingMgmtSession
                .getInternalKeyBindingInfo(alwaysAllowToken, internalKeyBindingId).getCertificateId();
        assertFalse("After certificate renewal the same certificate still in use.",
                boundCertificateFingerprint.equals(actualCertificateFingerprint));
        // Check DN in generated CSR when we have a bound certificate, should be the DN of the old certificate
        final byte[] csr4 = internalKeyBindingMgmtSession.generateCsrForNextKey(alwaysAllowToken,
                internalKeyBindingId, null);
        final JcaPKCS10CertificationRequest jcareq4 = new JcaPKCS10CertificationRequest(csr4);
        assertEquals("Wrong DN, should be from the bound certificate",
                "CN=" + TESTCLASSNAME + "_" + TEST_METHOD_NAME, jcareq4.getSubject().toString());
    } finally {
        internalKeyBindingMgmtSession.deleteInternalKeyBinding(alwaysAllowToken, internalKeyBindingId);
        internalCertStoreSession.removeCertificate(certFpToDelete);
    }
}

From source file:org.ejbca.ui.cli.keybind.InternalKeyBindingGenerateCsrCommandTest.java

License:Open Source License

@Test
public void testGenerateCsr() throws AuthorizationDeniedException, FileNotFoundException {
    String[] args = new String[] { TESTCLASS_NAME, "--genkeypair", csrFile.getAbsolutePath() };
    command.execute(args);/*ww w.ja va  2  s .  c o m*/
    try {
        PKCS10RequestMessage msg = RequestMessageUtils
                .genPKCS10RequestMessage(FileTools.readFiletoBuffer(csrFile.getAbsolutePath()));
        assertEquals("Wrong DN in generated request", "CN=InternalKeyBindingGenerateCsrCommandTest",
                msg.getRequestDN());
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        fail("A correct CSR was not generated.");
    }
    args = new String[] { TESTCLASS_NAME, "--genkeypair", csrFile.getAbsolutePath(), "--subjectdn",
            "C=SE,O=org,CN=name", "--x500dnorder" };
    command.execute(args);
    try {
        PKCS10RequestMessage msg = RequestMessageUtils
                .genPKCS10RequestMessage(FileTools.readFiletoBuffer(csrFile.getAbsolutePath()));
        JcaPKCS10CertificationRequest jcareq = new JcaPKCS10CertificationRequest(
                msg.getCertificationRequest().getEncoded());
        assertEquals("Wring order of DN, should be X500 with C first", "C=SE,O=org,CN=name",
                jcareq.getSubject().toString());
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        fail("A correct CSR was not generated.");
    }
    args = new String[] { TESTCLASS_NAME, "--genkeypair", csrFile.getAbsolutePath(), "--subjectdn",
            "C=SE,O=org,CN=name" };
    command.execute(args);
    try {
        PKCS10RequestMessage msg = RequestMessageUtils
                .genPKCS10RequestMessage(FileTools.readFiletoBuffer(csrFile.getAbsolutePath()));
        JcaPKCS10CertificationRequest jcareq = new JcaPKCS10CertificationRequest(
                msg.getCertificationRequest().getEncoded());
        assertEquals("Wring order of DN, should be LDAP with CN first", "CN=name,O=org,C=SE",
                jcareq.getSubject().toString());
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        fail("A correct CSR was not generated.");
    }
}

From source file:org.wso2.carbon.identity.certificateauthority.CAAdminService.java

License:Open Source License

protected X509Certificate signCSR(String serialNo, PKCS10CertificationRequest request, int validity,
        PrivateKey privateKey, X509Certificate caCert) throws CaException {
    try {//from   w  ww  . ja v a2  s  .c om

        Date issuedDate = new Date();
        Date expiryDate = new Date(System.currentTimeMillis() + validity * MILLIS_PER_DAY);
        JcaPKCS10CertificationRequest jcaRequest = new JcaPKCS10CertificationRequest(request);
        X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(caCert,
                new BigInteger(serialNo), issuedDate, expiryDate, jcaRequest.getSubject(),
                jcaRequest.getPublicKey());
        JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
        certificateBuilder
                .addExtension(Extension.authorityKeyIdentifier, false,
                        extUtils.createAuthorityKeyIdentifier(caCert))
                .addExtension(Extension.subjectKeyIdentifier, false,
                        extUtils.createSubjectKeyIdentifier(jcaRequest.getPublicKey()))
                .addExtension(Extension.basicConstraints, true, new BasicConstraints(0))
                .addExtension(Extension.keyUsage, true,
                        new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment))
                .addExtension(Extension.extendedKeyUsage, true,
                        new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));
        ContentSigner signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(privateKey);
        //todo add ocsp extension
        int tenantID = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
        DistributionPointName crlEp = new DistributionPointName(new GeneralNames(new GeneralName(
                GeneralName.uniformResourceIdentifier, CAUtils.getServerURL() + "/ca/crl/" + tenantID)));
        DistributionPoint disPoint = new DistributionPoint(crlEp, null, null);
        certificateBuilder.addExtension(Extension.cRLDistributionPoints, false,
                new CRLDistPoint(new DistributionPoint[] { disPoint }));
        AccessDescription ocsp = new AccessDescription(AccessDescription.id_ad_ocsp, new GeneralName(
                GeneralName.uniformResourceIdentifier, CAUtils.getServerURL() + "/ca/ocsp/" + tenantID));
        ASN1EncodableVector authInfoAccessASN = new ASN1EncodableVector();
        authInfoAccessASN.add(ocsp);
        certificateBuilder.addExtension(Extension.authorityInfoAccess, false,
                new DERSequence(authInfoAccessASN));
        return new JcaX509CertificateConverter().setProvider("BC")
                .getCertificate(certificateBuilder.build(signer));

        //            AccessDescription ocsp = new AccessDescription(ID_AD_OCSP,
        //                    new GeneralName(GeneralName.uniformResourceIdentifier,
        //                            new DERIA5String(CAUtils.getServerURL()+"/ca/ocsp/" + tenantID))
        //            );
        //
        //            ASN1EncodableVector authInfoAccessASN = new ASN1EncodableVector();
        //            authInfoAccessASN.add(ocsp);
        //
        //            certGen.addExtension(X509Extensions.AuthorityInfoAccess, false, new DERSequence(authInfoAccessASN));
        //
        //            DistributionPointName crlEP = new DistributionPointName(DNP_TYPE, new GeneralNames(
        //                    new GeneralName(GeneralName.uniformResourceIdentifier, CAUtils.getServerURL()+"/ca/crl/" + tenantID)));
        //
        //            DistributionPoint[] distPoints = new DistributionPoint[1];
        //            distPoints[0] = new DistributionPoint(crlEP, null, null);
        //
        //            certGen.addExtension(X509Extensions.CRLDistributionPoints, false, new CRLDistPoint(distPoints));
        //
        //            ASN1Set attributes = request.getCertificationRequestInfo().getAttributes();
        //            for (int i = 0; i != attributes.size(); i++) {
        //                Attribute attr = Attribute.getInstance(attributes.getObjectAt(i));
        //
        //                if (attr.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
        //                    X509Extensions extensions = X509Extensions.getInstance(attr.getAttrValues().getObjectAt(0));
        //
        //                    Enumeration e = extensions.oids();
        //                    while (e.hasMoreElements()) {
        //                        DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement();
        //                        X509Extension ext = extensions.getExtension(oid);
        //
        //                        certGen.addExtension(oid, ext.isCritical(), ext.getValue().getOctets());
        //                    }
        //                }
        //            }
        //            X509Certificate issuedCert = certGen.generateX509Certificate(privateKey);
        //            return issuedCert;
    } catch (Exception e) {
        throw new CaException("Error in signing the certificate", e);
    }
}