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

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

Introduction

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

Prototype

public PublicKey getPublicKey() throws InvalidKeyException, NoSuchAlgorithmException 

Source Link

Usage

From source file:cdm.api.windows.impl.EnrolmentServiceImpl.java

License:Open Source License

public Response enrollUser(Document request) {
    LOGGER.info("Received User Enrollment Request");

    XPath xPath = XPathFactory.newInstance().newXPath();
    xPath.setNamespaceContext(new MyNamespaceContext());
    String response = null;// ww  w . j a  va  2s  . c  o  m

    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();

    try {
        NodeList nl = (NodeList) xPath.evaluate(
                "/s:Envelope/s:Body/wst:RequestSecurityToken/wsse:BinarySecurityToken", request,
                XPathConstants.NODESET);
        Node node = nl.item(0);
        String certificateDataString = node.getTextContent();
        byte[] derByteArray = javax.xml.bind.DatatypeConverter.parseBase64Binary(certificateDataString);

        PKCS10CertificationRequest certificationRequest = new PKCS10CertificationRequest(derByteArray);
        JcaPKCS10CertificationRequest csrReq = new JcaPKCS10CertificationRequest(certificationRequest);

        LOGGER.info("Public Key of CSR : " + csrReq.getPublicKey());

        X509Certificate signedCert = CertificateSigningService.signCSR(csrReq, privateKey, rooCACertificate);

        LOGGER.info("Verifying Signed Certificate with CSR's public key : " + signedCert.getPublicKey());

        BASE64Encoder base64Encoder = new BASE64Encoder();
        String rootCertEncodedString = base64Encoder.encode(rooCACertificate.getEncoded());
        String signedCertEncoded = base64Encoder.encode(signedCert.getEncoded());

        DocumentBuilder builder = domFactory.newDocumentBuilder();
        org.w3c.dom.Document dDoc = builder.parse(wapProvisioningXmlFile);

        NodeList wapParm = dDoc.getElementsByTagName("parm");

        NamedNodeMap rootCertAttributes = wapParm.item(0).getAttributes();
        Node b64Encoded = rootCertAttributes.getNamedItem("value");
        b64Encoded.setTextContent(rootCertEncodedString);

        NamedNodeMap clientCertAttributes = wapParm.item(1).getAttributes();
        Node b64CliendEncoded = clientCertAttributes.getNamedItem("value");
        b64CliendEncoded.setTextContent(signedCertEncoded);

        String wapProvisioning = convertDocumentToString(dDoc);
        String encodedWap = base64Encoder.encode(wapProvisioning.getBytes());

        org.w3c.dom.Document responseXml = builder.parse(enrollmentResponseFile);
        NodeList token = responseXml.getElementsByTagName("BinarySecurityToken");

        Node firstToken = token.item(0);
        firstToken.setTextContent(encodedWap);

        response = convertDocumentToString(responseXml);
    } catch (Exception e) {
        LOGGER.error("An Unexpected Error has occurred while processing the request ", e);
    }

    LOGGER.info("Sending User Enrollment Response");
    return Response.ok().entity(response).build();
}

From source file:cdm.api.windows.util.CertificateSigningService.java

License:Open Source License

public static X509Certificate signCSR(JcaPKCS10CertificationRequest jcaRequest, PrivateKey privateKey,
        X509Certificate caCert) throws Exception {
    try {/*from  w  w  w. jav  a 2s . com*/

        X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(caCert,
                BigInteger.valueOf(new SecureRandom().nextInt(Integer.MAX_VALUE)),
                new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30),
                new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10)),
                new X500Name("CN=abimaran"), jcaRequest.getPublicKey());

        JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();

        ContentSigner signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(privateKey);

        X509Certificate theCert = new JcaX509CertificateConverter().setProvider("BC")
                .getCertificate(certificateBuilder.build(signer));

        LOGGER.info("Signed Certificate CN : " + theCert.getSubjectDN().getName());

        LOGGER.info("Signed CSR's public key : " + theCert.getPublicKey());

        return theCert;

    } catch (Exception e) {
        throw new Exception("Error in signing the certificate", e);
    }
}

From source file:com.yahoo.athenz.auth.util.Crypto.java

License:Apache License

public static X509Certificate generateX509Certificate(PKCS10CertificationRequest certReq,
        PrivateKey caPrivateKey, X500Name issuer, int validityTimeout, boolean basicConstraints) {

    // set validity for the given number of minutes from now

    Date notBefore = new Date();
    Calendar cal = Calendar.getInstance();
    cal.setTime(notBefore);/* w  w  w  . j  av a  2s . com*/
    cal.add(Calendar.MINUTE, validityTimeout);
    Date notAfter = cal.getTime();

    // Generate self-signed certificate

    X509Certificate cert = null;
    try {
        JcaPKCS10CertificationRequest jcaPKCS10CertificationRequest = new JcaPKCS10CertificationRequest(
                certReq);
        PublicKey publicKey = jcaPKCS10CertificationRequest.getPublicKey();

        X509v3CertificateBuilder caBuilder = new JcaX509v3CertificateBuilder(issuer,
                BigInteger.valueOf(System.currentTimeMillis()), notBefore, notAfter, certReq.getSubject(),
                publicKey)
                        .addExtension(Extension.basicConstraints, false, new BasicConstraints(basicConstraints))
                        .addExtension(Extension.keyUsage, true,
                                new X509KeyUsage(X509KeyUsage.digitalSignature | X509KeyUsage.keyEncipherment))
                        .addExtension(Extension.extendedKeyUsage, true,
                                new ExtendedKeyUsage(new KeyPurposeId[] { KeyPurposeId.id_kp_clientAuth,
                                        KeyPurposeId.id_kp_serverAuth }));

        // see if we have the dns/rfc822/ip address extensions specified in the csr

        ArrayList<GeneralName> altNames = new ArrayList<>();
        Attribute[] certAttributes = jcaPKCS10CertificationRequest
                .getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
        if (certAttributes != null && certAttributes.length > 0) {
            for (Attribute attribute : certAttributes) {
                Extensions extensions = Extensions.getInstance(attribute.getAttrValues().getObjectAt(0));
                GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName);
                if (gns == null) {
                    continue;
                }
                GeneralName[] names = gns.getNames();
                for (int i = 0; i < names.length; i++) {
                    switch (names[i].getTagNo()) {
                    case GeneralName.dNSName:
                    case GeneralName.iPAddress:
                    case GeneralName.rfc822Name:
                        altNames.add(names[i]);
                        break;
                    }
                }
            }
            if (!altNames.isEmpty()) {
                caBuilder.addExtension(Extension.subjectAlternativeName, false,
                        new GeneralNames(altNames.toArray(new GeneralName[altNames.size()])));
            }
        }

        String signatureAlgorithm = getSignatureAlgorithm(caPrivateKey.getAlgorithm(), SHA256);
        ContentSigner caSigner = new JcaContentSignerBuilder(signatureAlgorithm).setProvider(BC_PROVIDER)
                .build(caPrivateKey);

        JcaX509CertificateConverter converter = new JcaX509CertificateConverter().setProvider(BC_PROVIDER);
        cert = converter.getCertificate(caBuilder.build(caSigner));

    } catch (CertificateException ex) {
        LOG.error("generateX509Certificate: Caught CertificateException when generating certificate: "
                + ex.getMessage());
        throw new CryptoException(ex);
    } catch (OperatorCreationException ex) {
        LOG.error(
                "generateX509Certificate: Caught OperatorCreationException when creating JcaContentSignerBuilder: "
                        + ex.getMessage());
        throw new CryptoException(ex);
    } catch (InvalidKeyException ex) {
        LOG.error("generateX509Certificate: Caught InvalidKeySpecException, invalid key spec is being used: "
                + ex.getMessage());
        throw new CryptoException(ex);
    } catch (NoSuchAlgorithmException ex) {
        LOG.error(
                "generateX509Certificate: Caught NoSuchAlgorithmException, check to make sure the algorithm is supported by the provider: "
                        + ex.getMessage());
        throw new CryptoException(ex);
    } catch (Exception ex) {
        LOG.error("generateX509Certificate: unable to generate X509 Certificate: " + ex.getMessage());
        throw new CryptoException("Unable to generate X509 Certificate");
    }

    return cert;
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.security.TestingRMAppSecurityActions.java

License:Apache License

@Override
public X509SecurityHandler.CertificateBundle sign(PKCS10CertificationRequest csr)
        throws URISyntaxException, IOException, GeneralSecurityException {
    JcaPKCS10CertificationRequest jcaRequest = new JcaPKCS10CertificationRequest(csr);
    X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(caCert,
            BigInteger.valueOf(System.currentTimeMillis()), new Date(),
            new Date(System.currentTimeMillis() + 50000), csr.getSubject(), jcaRequest.getPublicKey());

    JcaX509ExtensionUtils extensionUtils = new JcaX509ExtensionUtils();
    certBuilder/*w  w w . j a va2 s .c o  m*/
            .addExtension(Extension.authorityKeyIdentifier, false,
                    extensionUtils.createAuthorityKeyIdentifier(caCert))
            .addExtension(Extension.subjectKeyIdentifier, false,
                    extensionUtils.createSubjectKeyIdentifier(jcaRequest.getPublicKey()))
            .addExtension(Extension.basicConstraints, true, new BasicConstraints(false))
            .addExtension(Extension.keyUsage, true,
                    new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
    X509Certificate certificate = new JcaX509CertificateConverter().setProvider("BC")
            .getCertificate(certBuilder.build(sigGen));
    return new X509SecurityHandler.CertificateBundle(certificate, caCert);
}

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

License:Apache License

/**
 * Submits a CSR to the Certificate authority, checks the resulting hmac, and returns the chain if everything succeeds
 *
 * @param keyPair the keypair to generate the csr for
 * @throws IOException if there is a problem during the process
 * @return the resulting certificate chain
 *//*from  w ww.ja v a 2  s. com*/
public X509Certificate[] perform(KeyPair keyPair) throws IOException {
    try {
        List<X509Certificate> certificates = new ArrayList<>();

        HttpClientBuilder httpClientBuilder = httpClientBuilderSupplier.get();
        SSLContextBuilder sslContextBuilder = SSLContextBuilder.create();
        sslContextBuilder.useProtocol("TLSv1.2");

        // We will be validating that we are talking to the correct host once we get the response's hmac of the token and public key of the ca
        sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        httpClientBuilder.setSSLSocketFactory(new TlsCertificateAuthorityClientSocketFactory(
                sslContextBuilder.build(), caHostname, certificates));

        String jsonResponseString;
        int responseCode;
        try (CloseableHttpClient client = httpClientBuilder.build()) {
            JcaPKCS10CertificationRequest request = TlsHelper.generateCertificationRequest(dn,
                    domainAlternativeNames, keyPair, signingAlgorithm);
            TlsCertificateAuthorityRequest tlsCertificateAuthorityRequest = new TlsCertificateAuthorityRequest(
                    TlsHelper.calculateHMac(token, request.getPublicKey()),
                    TlsHelper.pemEncodeJcaObject(request));

            HttpPost httpPost = new HttpPost();
            httpPost.setEntity(
                    new ByteArrayEntity(objectMapper.writeValueAsBytes(tlsCertificateAuthorityRequest)));

            if (logger.isInfoEnabled()) {
                logger.info("Requesting certificate with dn " + dn + " from " + caHostname + ":" + port);
            }
            try (CloseableHttpResponse response = client.execute(new HttpHost(caHostname, port, "https"),
                    httpPost)) {
                jsonResponseString = IOUtils.toString(
                        new BoundedInputStream(response.getEntity().getContent(), 1024 * 1024),
                        StandardCharsets.UTF_8);
                responseCode = response.getStatusLine().getStatusCode();
            }
        }

        if (responseCode != Response.SC_OK) {
            throw new IOException(
                    RECEIVED_RESPONSE_CODE + responseCode + " with payload " + jsonResponseString);
        }

        if (certificates.size() != 1) {
            throw new IOException(EXPECTED_ONE_CERTIFICATE);
        }

        TlsCertificateAuthorityResponse tlsCertificateAuthorityResponse = objectMapper
                .readValue(jsonResponseString, TlsCertificateAuthorityResponse.class);
        if (!tlsCertificateAuthorityResponse.hasHmac()) {
            throw new IOException(EXPECTED_RESPONSE_TO_CONTAIN_HMAC);
        }

        X509Certificate caCertificate = certificates.get(0);
        byte[] expectedHmac = TlsHelper.calculateHMac(token, caCertificate.getPublicKey());

        if (!MessageDigest.isEqual(expectedHmac, tlsCertificateAuthorityResponse.getHmac())) {
            throw new IOException(UNEXPECTED_HMAC_RECEIVED_POSSIBLE_MAN_IN_THE_MIDDLE);
        }

        if (!tlsCertificateAuthorityResponse.hasCertificate()) {
            throw new IOException(EXPECTED_RESPONSE_TO_CONTAIN_CERTIFICATE);
        }
        X509Certificate x509Certificate = TlsHelper
                .parseCertificate(new StringReader(tlsCertificateAuthorityResponse.getPemEncodedCertificate()));
        x509Certificate.verify(caCertificate.getPublicKey());
        if (logger.isInfoEnabled()) {
            logger.info("Got certificate with dn " + x509Certificate.getSubjectX500Principal());
        }
        return new X509Certificate[] { x509Certificate, caCertificate };
    } catch (IOException e) {
        throw e;
    } catch (Exception e) {
        throw new IOException(e);
    }
}

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;/*from www  .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  av a 2 s . c  om*/
        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.ejbca.ra.EnrollMakeNewRequestBean.java

License:Open Source License

public final void validateCsr(FacesContext context, UIComponent component, Object value)
        throws ValidatorException {
    algorithmFromCsr = null;//from   w ww.  j a  va 2s  .com
    PKCS10CertificationRequest pkcs10CertificateRequest = CertTools
            .getCertificateRequestFromPem(value.toString());
    if (pkcs10CertificateRequest == null) {
        throw new ValidatorException(
                new FacesMessage(raLocaleBean.getMessage("enroll_invalid_certificate_request")));
    }

    //Get public key algorithm from CSR and check if it's allowed in certificate profile
    final JcaPKCS10CertificationRequest jcaPKCS10CertificationRequest = new JcaPKCS10CertificationRequest(
            pkcs10CertificateRequest);
    try {
        final String keySpecification = AlgorithmTools
                .getKeySpecification(jcaPKCS10CertificationRequest.getPublicKey());
        final String keyAlgorithm = AlgorithmTools
                .getKeyAlgorithm(jcaPKCS10CertificationRequest.getPublicKey());
        final CertificateProfile certificateProfile = getCertificateProfile();
        final List<String> availableKeyAlgorithms = certificateProfile.getAvailableKeyAlgorithmsAsList();
        final List<Integer> availableBitLengths = certificateProfile.getAvailableBitLengthsAsList();
        if (!availableKeyAlgorithms.contains(keyAlgorithm)
                || !availableBitLengths.contains(Integer.parseInt(keySpecification))) {
            throw new ValidatorException(new FacesMessage(raLocaleBean.getMessage(
                    "enroll_key_algorithm_is_not_available", keyAlgorithm + "_" + keySpecification)));
        }
        algorithmFromCsr = keyAlgorithm + " " + keySpecification;// Save for later use
        // For yet unknown reasons, the setter is never when invoked during AJAX request
        certificateRequest = value.toString();
    } catch (InvalidKeyException | NoSuchAlgorithmException e) {
        throw new ValidatorException(new FacesMessage(raLocaleBean.getMessage("enroll_unknown_key_algorithm")));
    }
}

From source file:org.opendaylight.snbi.southplugin.SNBICAInterfaces.java

License:Open Source License

public X509Certificate generateX509Certificate(PKCS10CertificationRequest request, ContentSigner signer) {
    X509Certificate rootCert = CertificateMgmt.getSavedCertificate(CertManagerConstants.BC,
            CertManagerConstants.SELF_SIGNED_CERT_FILE);
    KeyPair rootPair = KeyPairMgmt.getKeyPairFromStore(CertManagerConstants.KEY_STORE_ALIAS,
            CertManagerConstants.KEY_STORE_CERT_ALIAS, CertManagerConstants.STORE_TYPE.JKS);

    // X500Name x500Name = request.getSubject();
    // RDN cn = x500Name.getRDNs(BCStyle.SN)[0];
    // AttributeTypeAndValue[] values = cn.getTypesAndValues();
    //BigInteger serial = BigInteger.valueOf(new Long(values[0].getValue().toString()).longValue());
    BigInteger serial = BigInteger.valueOf(System.currentTimeMillis());
    Calendar now = Calendar.getInstance();
    now.add(Calendar.YEAR, -1);//from  w  ww.  j a v a2  s  .  c om
    Date notBefore = now.getTime();
    now.add(Calendar.YEAR, 4);
    Date notAfter = now.getTime();
    org.bouncycastle.asn1.x500.X500Name issuername = JcaX500NameUtil.getSubject(rootCert);
    JcaPKCS10CertificationRequest jpkcsreq = new JcaPKCS10CertificationRequest(request);
    X509v3CertificateBuilder certGen;
    try {
        certGen = new JcaX509v3CertificateBuilder(issuername, serial, notBefore, notAfter, request.getSubject(),
                jpkcsreq.getPublicKey());
    } catch (InvalidKeyException | NoSuchAlgorithmException e1) {
        e1.printStackTrace();
        return null;
    }

    if (signer == null) {
        try {
            signer = new JcaContentSignerBuilder(CertManagerConstants.CERT_ALGORITHM.SHA1withRSA.toString())
                    .setProvider(CertManagerConstants.BC).build(rootPair.getPrivate());
        } catch (OperatorCreationException e) {
            e.printStackTrace();
            return null;
        }
    }
    try {
        X509Certificate issuedCert = new JcaX509CertificateConverter().setProvider(CertManagerConstants.BC)
                .getCertificate(certGen.build(signer));
        return issuedCert;
    } catch (CertificateException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:org.wso2.carbon.device.mgt.mobile.windows.api.services.enrollment.util.CertificateSigningService.java

License:Open Source License

/**
 * Implement certificate signing task using CSR received from the device and the MDM server key
 * store.//from ww  w  .j a va 2s. c o m
 * @param jcaRequest        - CSR from the device
 * @param privateKey        - Private key of CA certificate in MDM server
 * @param caCert            - CA certificate in MDM server
 * @param certParameterList - Parameter list for Signed certificate generation
 * @return - Signed certificate for CSR from device
 * @throws CertificateGenerationException
 * @throws WAPProvisioningException
 */
public static X509Certificate signCSR(JcaPKCS10CertificationRequest jcaRequest, PrivateKey privateKey,
        X509Certificate caCert, List certParameterList)
        throws CertificateGenerationException, WAPProvisioningException {

    String commonName = (String) certParameterList.get(PropertyIndex.COMMON_NAME_INDEX.getValue());
    int notBeforeDays = (Integer) certParameterList.get(PropertyIndex.NOT_BEFORE_DAYS_INDEX.getValue());
    int notAfterDays = (Integer) certParameterList.get(PropertyIndex.NOT_AFTER_DAYS_INDEX.getValue());
    X509v3CertificateBuilder certificateBuilder;
    X509Certificate signedCertificate;

    try {
        ContentSigner signer;
        BigInteger serialNumber = BigInteger.valueOf(new SecureRandom().nextInt(Integer.MAX_VALUE));
        Date notBeforeDate = new Date(System.currentTimeMillis() - (MILLI_SECONDS * notBeforeDays));
        Date notAfterDate = new Date(System.currentTimeMillis() + (MILLI_SECONDS * notAfterDays));
        certificateBuilder = new JcaX509v3CertificateBuilder(caCert, serialNumber, notBeforeDate, notAfterDate,
                new X500Principal(commonName), jcaRequest.getPublicKey());

        //Adding extensions to the signed certificate.
        certificateBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature));
        certificateBuilder.addExtension(Extension.extendedKeyUsage, false,
                new ExtendedKeyUsage(KeyPurposeId.id_kp_clientAuth));
        certificateBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(false));

        signer = new JcaContentSignerBuilder(PluginConstants.CertificateEnrolment.ALGORITHM)
                .setProvider(PluginConstants.CertificateEnrolment.PROVIDER).build(privateKey);

        signedCertificate = new JcaX509CertificateConverter()
                .setProvider(PluginConstants.CertificateEnrolment.PROVIDER)
                .getCertificate(certificateBuilder.build(signer));
    } catch (InvalidKeyException e) {
        throw new CertificateGenerationException("CSR's public key is invalid", e);
    } catch (NoSuchAlgorithmException e) {
        throw new CertificateGenerationException("Certificate cannot be generated", e);
    } catch (CertIOException e) {
        throw new CertificateGenerationException("Cannot add extension(s) to signed certificate", e);
    } catch (OperatorCreationException e) {
        throw new CertificateGenerationException("Content signer cannot be created", e);
    } catch (CertificateException e) {
        throw new CertificateGenerationException("Signed certificate cannot be generated", e);
    }
    return signedCertificate;
}