Example usage for org.bouncycastle.cert.jcajce JcaX509CertificateConverter JcaX509CertificateConverter

List of usage examples for org.bouncycastle.cert.jcajce JcaX509CertificateConverter JcaX509CertificateConverter

Introduction

In this page you can find the example usage for org.bouncycastle.cert.jcajce JcaX509CertificateConverter JcaX509CertificateConverter.

Prototype

public JcaX509CertificateConverter() 

Source Link

Document

Base constructor, configure with the default provider.

Usage

From source file:org.signserver.server.dispatchers.FirstActiveDispatcherTest.java

License:Open Source License

private void addCertificate(PrivateKey issuerPrivateKey, int workerId, String workerName)
        throws CryptoTokenOfflineException, InvalidWorkerIdException, IOException, CertificateException,
        OperatorCreationException {//from w w  w.  j  av  a  2 s  .  c  om
    Base64SignerCertReqData reqData = (Base64SignerCertReqData) workerSession.getCertificateRequest(workerId,
            new PKCS10CertReqInfo("SHA1withRSA", "CN=" + workerName, null), false);
    PKCS10CertificationRequest csr = new PKCS10CertificationRequest(Base64.decode(reqData.getBase64CertReq()));
    X509CertificateHolder cert = new X509v3CertificateBuilder(new X500Name("CN=Issuer"), BigInteger.ONE,
            new Date(), new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(365)), csr.getSubject(),
            csr.getSubjectPublicKeyInfo()).build(
                    new JcaContentSignerBuilder("SHA256WithRSA").setProvider("BC").build(issuerPrivateKey));
    workerSession.setWorkerProperty(workerId, "SIGNERCERTCHAIN", new String(
            CertTools.getPEMFromCerts(Arrays.asList(new JcaX509CertificateConverter().getCertificate(cert)))));
    workerSession.reloadConfiguration(workerId);
}

From source file:org.signserver.server.log.SystemLoggingTest.java

License:Open Source License

@Test
public void test01LogCertInstalled() throws Exception {
    LOG.info(">test01LogCertInstalled");
    int linesBefore = readEntriesCount(auditLogFile);

    // Test with uploadSignerCertificate method (global scope)
    final X509Certificate cert = new JcaX509CertificateConverter().getCertificate(new CertBuilder().build());
    workerSession.uploadSignerCertificate(signerId, cert.getEncoded(), GlobalConfiguration.SCOPE_GLOBAL);

    List<String> lines = readEntries(auditLogFile, linesBefore, 2);
    LOG.info(lines);//from  w w  w  .  j av  a 2  s  . c o m
    String line = getTheLineContaining(lines, "EVENT: SET_WORKER_CONFIG");
    assertNotNull("Contains event", line);
    assertTrue("Contains module", line.contains("MODULE: WORKER_CONFIG"));
    assertTrue("Contains worker id", line.contains("WORKER_ID: " + signerId));

    line = getTheLineContaining(lines, "EVENT: CERTINSTALLED");
    assertNotNull("Contains event", line);
    assertTrue("Contains module", line.contains("MODULE: WORKER_CONFIG"));
    assertTrue("Contains worker id", line.contains("WORKER_ID: " + signerId));
    String certLine = new String(CertTools.getPEMFromCerts(Arrays.asList(cert))).replace("\r\n", "\n");
    assertTrue("Contains certificate", line.contains(certLine));
    assertTrue("Contains scope", line.contains("SCOPE: GLOBAL"));

    // Test removeProperty
    workerSession.removeWorkerProperty(signerId, "SIGNERCERT");
    lines = readEntries(auditLogFile, linesBefore + 2, 2);
    LOG.info(lines);

    line = getTheLineContaining(lines, "EVENT: CERTINSTALLED");
    assertNotNull("Contains event", line);
    assertTrue("Contains module", line.contains("MODULE: WORKER_CONFIG"));
    assertTrue("Contains worker id", line.contains("WORKER_ID: " + signerId));
    assertTrue("Contains empty certificate", line.contains("CERTIFICATE: ;"));
    assertTrue("Contains scope", line.contains("SCOPE: GLOBAL"));

    line = getTheLineContaining(lines, "EVENT: SET_WORKER_CONFIG");
    assertNotNull("Contains event", line);
    assertTrue("Contains module", line.contains("MODULE: WORKER_CONFIG"));
    assertTrue("Contains worker id", line.contains("WORKER_ID: " + signerId));

    // Test with uploadSignerCertificate method (node scope)
    linesBefore = readEntriesCount(auditLogFile);
    workerSession.uploadSignerCertificate(signerId, cert.getEncoded(), GlobalConfiguration.SCOPE_NODE);

    lines = readEntries(auditLogFile, linesBefore, 2);
    LOG.info(lines);
    line = getTheLineContaining(lines, "EVENT: SET_WORKER_CONFIG");
    assertNotNull("Contains event", line);
    assertTrue("Contains module", line.contains("MODULE: WORKER_CONFIG"));
    assertTrue("Contains worker id", line.contains("WORKER_ID: " + signerId));

    line = getTheLineContaining(lines, "EVENT: CERTINSTALLED");
    assertNotNull("Contains event", line);
    assertTrue("Contains module", line.contains("MODULE: WORKER_CONFIG"));
    assertTrue("Contains worker id", line.contains("WORKER_ID: " + signerId));
    assertTrue("Contains certificate",
            line.contains(new String(CertTools.getPEMFromCerts(Arrays.asList(cert))).replace("\r\n", "\n")));
    assertTrue("Contains scope", line.contains("SCOPE: NODE"));
    assertTrue("Contains node", line.contains("NODE: " + WorkerConfig.getNodeId()));

    // Remove the property
    workerSession.removeWorkerProperty(signerId, WorkerConfig.getNodeId() + ".SIGNERCERT");

    // Test when setting the property manually (global scope)
    linesBefore = readEntriesCount(auditLogFile);
    workerSession.setWorkerProperty(signerId, "SIGNERCERT",
            new String(CertTools.getPEMFromCerts(Arrays.asList(cert))).replace("\r\n", "\n"));

    lines = readEntries(auditLogFile, linesBefore, 2);
    LOG.info(lines);
    line = getTheLineContaining(lines, "EVENT: SET_WORKER_CONFIG");
    assertNotNull("Contains event", line);
    assertTrue("Contains module", line.contains("MODULE: WORKER_CONFIG"));
    assertTrue("Contains worker id", line.contains("WORKER_ID: " + signerId));

    line = getTheLineContaining(lines, "EVENT: CERTINSTALLED");
    assertNotNull("Contains event", line);
    assertTrue("Contains module", line.contains("MODULE: WORKER_CONFIG"));
    assertTrue("Contains worker id", line.contains("WORKER_ID: " + signerId));
    assertTrue("Contains certificate",
            line.contains(new String(CertTools.getPEMFromCerts(Arrays.asList(cert))).replace("\r\n", "\n")));
    assertTrue("Contains scope", line.contains("SCOPE: GLOBAL"));

    // Remove the property
    workerSession.removeWorkerProperty(signerId, "SIGNERCERT");

    // Test when setting the property manually (node scope)
    linesBefore = readEntriesCount(auditLogFile);
    workerSession.setWorkerProperty(signerId, "NODE47.SIGNERCERT",
            new String(CertTools.getPEMFromCerts(Arrays.asList(cert))).replace("\r\n", "\n"));

    lines = readEntries(auditLogFile, linesBefore, 2);
    LOG.info(lines);
    line = getTheLineContaining(lines, "EVENT: SET_WORKER_CONFIG");
    assertNotNull("Contains event", line);
    assertTrue("Contains module", line.contains("MODULE: WORKER_CONFIG"));
    assertTrue("Contains worker id", line.contains("WORKER_ID: " + signerId));

    line = getTheLineContaining(lines, "EVENT: CERTINSTALLED");
    assertNotNull("Contains event", line);
    assertTrue("Contains module", line.contains("MODULE: WORKER_CONFIG"));
    assertTrue("Contains worker id", line.contains("WORKER_ID: " + signerId));
    assertTrue("Contains certificate",
            line.contains(new String(CertTools.getPEMFromCerts(Arrays.asList(cert))).replace("\r\n", "\n")));
    assertTrue("Contains scope", line.contains("SCOPE: NODE"));
    assertTrue("Contains node", line.contains("NODE: NODE47"));

    // Remove the property
    workerSession.removeWorkerProperty(signerId, "NODE47.SIGNERCERT");
}

From source file:org.signserver.server.log.SystemLoggingTest.java

License:Open Source License

@Test
public void test01LogCertChainInstalled() throws Exception {
    LOG.info(">test01LogCertChainInstalled");
    int linesBefore = readEntriesCount(auditLogFile);

    // Test with uploadSignerCertificateChain method (global scope)
    KeyPair issuerKeyPair = CryptoUtils.generateRSA(512);
    final X509Certificate issuerCert = new JcaX509CertificateConverter().getCertificate(
            new CertBuilder().setSelfSignKeyPair(issuerKeyPair).setSubject("CN=Issuer, C=SE").build());
    final X509Certificate cert = new JcaX509CertificateConverter()
            .getCertificate(new CertBuilder().setIssuerPrivateKey(issuerKeyPair.getPrivate())
                    .setSubject("CN=Signer,C=SE").setIssuer("CN=Issuer, C=SE").build());
    workerSession.uploadSignerCertificateChain(signerId,
            Arrays.asList(cert.getEncoded(), issuerCert.getEncoded()), GlobalConfiguration.SCOPE_GLOBAL);

    List<String> lines = readEntries(auditLogFile, linesBefore, 2);
    LOG.info(lines);/*www.  ja  v a  2 s. c  om*/
    String line = getTheLineContaining(lines, "EVENT: SET_WORKER_CONFIG");
    assertNotNull("Contains event", line);
    assertTrue("Contains module", line.contains("MODULE: WORKER_CONFIG"));
    assertTrue("Contains worker id", line.contains("WORKER_ID: " + signerId));

    line = getTheLineContaining(lines, "EVENT: CERTCHAININSTALLED");
    assertNotNull("Contains event", line);
    assertTrue("Contains module", line.contains("MODULE: WORKER_CONFIG"));
    assertTrue("Contains worker id", line.contains("WORKER_ID: " + signerId));
    assertTrue("Contains certificate", line.contains(
            new String(CertTools.getPEMFromCerts(Arrays.asList(cert, issuerCert))).replace("\r\n", "\n")));
    assertTrue("Contains scope", line.contains("SCOPE: GLOBAL"));

    // Test removeProperty
    if (!workerSession.removeWorkerProperty(signerId, "SIGNERCERTCHAIN")) {
        throw new Exception("Property could not be removed");
    }
    lines = readEntries(auditLogFile, linesBefore + 2, 2);
    LOG.info(lines);

    line = getTheLineContaining(lines, "EVENT: CERTCHAININSTALLED");
    assertNotNull("Contains event", line);
    assertTrue("Contains module", line.contains("MODULE: WORKER_CONFIG"));
    assertTrue("Contains worker id", line.contains("WORKER_ID: " + signerId));
    assertTrue("Contains empty certificate chain", line.contains("CERTIFICATECHAIN: ;"));
    assertTrue("Contains scope", line.contains("SCOPE: GLOBAL"));

    line = getTheLineContaining(lines, "EVENT: SET_WORKER_CONFIG");
    assertNotNull("Contains event", line);
    assertTrue("Contains module", line.contains("MODULE: WORKER_CONFIG"));
    assertTrue("Contains worker id", line.contains("WORKER_ID: " + signerId));

    // Test with uploadSignerCertificateChain method (node scope)
    linesBefore = readEntriesCount(auditLogFile);
    workerSession.uploadSignerCertificateChain(signerId,
            Arrays.asList(cert.getEncoded(), issuerCert.getEncoded()), GlobalConfiguration.SCOPE_NODE);

    lines = readEntries(auditLogFile, linesBefore, 2);
    LOG.info(lines);
    line = getTheLineContaining(lines, "EVENT: SET_WORKER_CONFIG");
    assertNotNull("Contains event", line);
    assertTrue("Contains module", line.contains("MODULE: WORKER_CONFIG"));
    assertTrue("Contains worker id", line.contains("WORKER_ID: " + signerId));

    line = getTheLineContaining(lines, "EVENT: CERTCHAININSTALLED");
    assertNotNull("Contains event", line);
    assertTrue("Contains module", line.contains("MODULE: WORKER_CONFIG"));
    assertTrue("Contains worker id", line.contains("WORKER_ID: " + signerId));
    assertTrue("Contains certificate", line.contains(
            new String(CertTools.getPEMFromCerts(Arrays.asList(cert, issuerCert))).replace("\r\n", "\n")));
    assertTrue("Contains scope", line.contains("SCOPE: NODE"));
    assertTrue("Contains node", line.contains("NODE: " + WorkerConfig.getNodeId()));

    // Remove the property
    workerSession.removeWorkerProperty(signerId, "SIGNERCERTCHAIN");

    // Test when setting the property manually (global scope)
    linesBefore = readEntriesCount(auditLogFile);
    workerSession.setWorkerProperty(signerId, "SIGNERCERTCHAIN",
            new String(CertTools.getPEMFromCerts(Arrays.asList(cert, issuerCert))).replace("\r\n", "\n"));

    lines = readEntries(auditLogFile, linesBefore, 2);
    LOG.info(lines);
    line = getTheLineContaining(lines, "EVENT: SET_WORKER_CONFIG");
    assertNotNull("Contains event", line);
    assertTrue("Contains module", line.contains("MODULE: WORKER_CONFIG"));
    assertTrue("Contains worker id", line.contains("WORKER_ID: " + signerId));

    line = getTheLineContaining(lines, "EVENT: CERTCHAININSTALLED");
    assertNotNull("Contains event", line);
    assertTrue("Contains module", line.contains("MODULE: WORKER_CONFIG"));
    assertTrue("Contains worker id", line.contains("WORKER_ID: " + signerId));
    assertTrue("Contains certificate", line.contains(
            new String(CertTools.getPEMFromCerts(Arrays.asList(cert, issuerCert))).replace("\r\n", "\n")));
    assertTrue("Contains scope", line.contains("SCOPE: GLOBAL"));

    // Remove the property
    if (!workerSession.removeWorkerProperty(signerId, "SIGNERCERTCHAIN")) {
        throw new Exception("Could not remove property");
    }

    // Test when setting the property manually (node scope)
    linesBefore = readEntriesCount(auditLogFile);
    workerSession.setWorkerProperty(signerId, "NODE47.SIGNERCERTCHAIN",
            new String(CertTools.getPEMFromCerts(Arrays.asList(cert, issuerCert))).replace("\r\n", "\n"));

    lines = readEntries(auditLogFile, linesBefore, 2);
    LOG.info(lines);
    line = getTheLineContaining(lines, "EVENT: SET_WORKER_CONFIG");
    assertNotNull("Contains event", line);
    assertTrue("Contains module", line.contains("MODULE: WORKER_CONFIG"));
    assertTrue("Contains worker id", line.contains("WORKER_ID: " + signerId));

    line = getTheLineContaining(lines, "EVENT: CERTCHAININSTALLED");
    assertNotNull("Contains event", line);
    assertTrue("Contains module", line.contains("MODULE: WORKER_CONFIG"));
    assertTrue("Contains worker id", line.contains("WORKER_ID: " + signerId));
    assertTrue("Contains certificate", line.contains(
            new String(CertTools.getPEMFromCerts(Arrays.asList(cert, issuerCert))).replace("\r\n", "\n")));
    assertTrue("Contains scope", line.contains("SCOPE: NODE"));
    assertTrue("Contains node", line.contains("NODE: NODE47"));

    // Remove the property
    workerSession.removeWorkerProperty(signerId, "NODE47.SIGNERCERTCHAIN");
}

From source file:org.signserver.server.log.SystemLoggingTest.java

License:Open Source License

/**
 * Tests that importing a certificate chain to a token is audit logged
 * including the complete chain.//from ww  w.  ja v a2s.  c  o  m
 * @throws Exception 
 */
@Test
public void test01LogCertChainInstalledToToken() throws Exception {
    LOG.info(">test01LogCertChainInstalledToToken");

    final String tokenName = "TestCryptoTokenP12_001";
    final String alias = "testkeyalias10";

    try {
        setupCryptoToken(WORKERID_CRYPTOWORKER1, tokenName, "foo123");
        workerSession.generateSignerKey(WORKERID_CRYPTOWORKER1, "RSA", "512", alias, null);

        PKCS10CertReqInfo certReqInfo = new PKCS10CertReqInfo("SHA1WithRSA", "CN=testkeyalias10,C=SE", null);
        ICertReqData req = workerSession.getCertificateRequest(WORKERID_CRYPTOWORKER1, certReqInfo, false);
        Base64SignerCertReqData reqData = (Base64SignerCertReqData) req;
        PKCS10CertificationRequest csr = new PKCS10CertificationRequest(
                Base64.decode(reqData.getBase64CertReq()));

        int linesBefore = readEntriesCount(auditLogFile);

        // Test with uploadSignerCertificateChain method (global scope)
        KeyPair issuerKeyPair = CryptoUtils.generateRSA(512);
        final X509Certificate issuerCert = new JcaX509CertificateConverter().getCertificate(
                new CertBuilder().setSelfSignKeyPair(issuerKeyPair).setSubject("CN=Issuer, C=SE").build());
        final X509Certificate cert = new JcaX509CertificateConverter()
                .getCertificate(new X509v3CertificateBuilder(new X500Name("CN=Issuer, C=SE"), BigInteger.ONE,
                        new Date(), new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(365)),
                        csr.getSubject(), csr.getSubjectPublicKeyInfo())
                                .build(new JcaContentSignerBuilder("SHA256WithRSA").setProvider("BC")
                                        .build(issuerKeyPair.getPrivate())));

        workerSession.importCertificateChain(WORKERID_CRYPTOWORKER1,
                Arrays.asList(cert.getEncoded(), issuerCert.getEncoded()), alias, null);

        List<String> lines = readEntries(auditLogFile, linesBefore, 2);
        LOG.info(lines);

        String line = getTheLineContaining(lines, "EVENT: CERTCHAININSTALLED");
        assertNotNull("Contains event", line);
        assertTrue("Contains module", line.contains("MODULE: KEY_MANAGEMENT"));
        assertTrue("Contains worker id", line.contains("WORKER_ID: " + WORKERID_CRYPTOWORKER1));
        assertTrue("Contains crypto token", line.contains("CRYPTOTOKEN: " + tokenName));
        assertTrue("Contains key alias", line.contains("KEYALIAS: " + alias));
        assertTrue("Contains certificate",
                line.contains(new String(org.cesecore.util.CertTools
                        .getPemFromCertificateChain(Arrays.<Certificate>asList(cert, issuerCert)))
                                .replace("\r\n", "\n")));
    } finally {
        removeWorker(WORKERID_CRYPTOWORKER1);
        if (keystoreFile != null) {
            FileUtils.deleteQuietly(keystoreFile);
        }
    }
}

From source file:org.signserver.validationservice.server.ValidationUtils.java

License:Open Source License

/**
 * Sends a request to the OCSP responder and returns the results.
 *
 * Note: Based on code from the EJBCA ValidationTool.
 *
 * @param url of the OCSP responder//from   w  w w  .ja  va 2  s .  co  m
 * @param request to send
 * @return An OCSPResponse object filled with information about the response
 * @throws IOException in case of networking related errors
 * @throws OCSPException in case of error parsing the response
 */
public static OCSPResponse queryOCSPResponder(URL url, OCSPReq request) throws IOException, OCSPException {
    final OCSPResponse result = new OCSPResponse();

    final HttpURLConnection con;
    final URLConnection urlCon = url.openConnection();
    if (!(urlCon instanceof HttpURLConnection)) {
        throw new IOException("Unsupported protocol in URL: " + url);
    }
    con = (HttpURLConnection) urlCon;

    // POST the OCSP request
    con.setDoOutput(true);
    con.setRequestMethod("POST");

    // POST it
    con.setRequestProperty("Content-Type", "application/ocsp-request");
    OutputStream os = null;
    try {
        os = con.getOutputStream();
        os.write(request.getEncoded());
    } finally {
        if (os != null) {
            os.close();
        }
    }

    result.setHttpReturnCode(con.getResponseCode());
    if (result.getHttpReturnCode() != 200) {
        if (result.getHttpReturnCode() == 401) {
            result.setError(OCSPResponse.Error.httpUnauthorized);
        } else {
            result.setError(OCSPResponse.Error.unknown);
        }
        return result;
    }

    OCSPResp response = null;
    InputStream in = null;
    try {
        in = con.getInputStream();
        if (in != null) {
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            int b;
            while ((b = in.read()) != -1) {
                bout.write(b);
            }
            response = new OCSPResp(bout.toByteArray());
        }
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException ignored) {
            } // NOPMD
        }
    }

    if (response == null) {
        result.setError(OCSPResponse.Error.noResponse);
        return result;
    }
    result.setResp(response);

    if (response.getStatus() != OCSPResponseStatus.SUCCESSFUL) {
        result.setError(OCSPResponse.Error.fromBCOCSPResponseStatus(response.getStatus()));
        return result;
    }

    final BasicOCSPResp brep = (BasicOCSPResp) response.getResponseObject();
    result.setResponseObject(brep);
    if (brep == null) {
        result.setError(OCSPResponse.Error.noResponse);
        return result;
    }

    final RespID id = brep.getResponderId();
    final DERTaggedObject to = (DERTaggedObject) id.toASN1Object().toASN1Object();
    final RespID respId;

    final X509CertificateHolder[] chain = brep.getCerts();
    JcaX509CertificateConverter converter = new JcaX509CertificateConverter();
    X509Certificate signerCertificate;
    try {
        signerCertificate = converter.getCertificate(chain[0]);
    } catch (CertificateException ex) {
        throw new IOException("Could not convert certificate: " + ex.getMessage());
    }
    result.setSignerCertificate(signerCertificate);

    if (to.getTagNo() == 1) {
        // This is Name
        respId = new JcaRespID(signerCertificate.getSubjectX500Principal());
    } else {
        // This is KeyHash
        final PublicKey signerPub = signerCertificate.getPublicKey();
        try {
            respId = new JcaRespID(signerPub,
                    new JcaDigestCalculatorProviderBuilder().build().get(RespID.HASH_SHA1));
        } catch (OperatorCreationException ex) {
            throw new IOException("Could not create respId: " + ex.getMessage());
        }
    }
    if (!id.equals(respId)) {
        // Response responderId does not match signer certificate responderId!
        result.setError(OCSPResponse.Error.invalidSignerId);
    }

    result.setIssuerDN(signerCertificate.getIssuerX500Principal());

    if (result.getError() == null) {
        result.setError(OCSPResponse.Error.responseSuccess);
    }

    return result;
}

From source file:org.signserver.validationservice.server.X509ExtendedKeyUsageExistsCertSelector.java

License:Open Source License

@Override
public boolean match(final Object o) {
    //match certificate containing specified extended key usage
    X509Certificate xcert;/*from w  w w  .j  a v  a 2s .com*/
    if (o instanceof X509Certificate) {
        xcert = (X509Certificate) o;
    } else if (o instanceof X509CertificateHolder) {
        try {
            xcert = new JcaX509CertificateConverter().getCertificate((X509CertificateHolder) o);
        } catch (CertificateException ex) {
            return false;
        }
    } else {
        return false;
    }

    try {
        if (xcert.getExtendedKeyUsage() != null) {

            for (String ext : xcert.getExtendedKeyUsage()) {
                if (ext.equals(oIDToCheck)) {
                    return true;
                }
            }
        }
    } catch (CertificateParsingException e) {
        return false;
    }

    return false;
}

From source file:org.sipfoundry.sipxconfig.cert.CertificateUtils.java

License:Contributor Agreement License

public static X509Certificate generateCert(X509v3CertificateBuilder gen, String algorithm, PrivateKey key)
        throws GeneralSecurityException {
    ContentSigner sigGen;/*from  w ww  . jav a 2 s. c om*/
    try {
        sigGen = new JcaContentSignerBuilder(algorithm).setProvider(PROVIDER).build(key);
        JcaX509CertificateConverter converter = new JcaX509CertificateConverter().setProvider(PROVIDER);
        return converter.getCertificate(gen.build(sigGen));
    } catch (OperatorCreationException e) {
        throw new GeneralSecurityException(e);
    } catch (CertificateException e) {
        throw new GeneralSecurityException(e);
    }
}

From source file:org.sonatype.nexus.ssl.CertificateUtil.java

License:Open Source License

/**
 * Decodes a PEM formatted certificate.//from w  ww.j  a  v a 2 s  .co m
 *
 * @param pemFormattedCertificate text to be decoded as a PEM certificate.
 * @return the Certificate decoded from the input text.
 * @throws CertificateParsingException
 *          thrown if the PEM formatted string cannot be parsed into a Certificate.
 */
public static Certificate decodePEMFormattedCertificate(final String pemFormattedCertificate)
        throws CertificateException {
    log.trace("Parsing PEM formatted certificate string:\n{}", pemFormattedCertificate);

    // make sure we have something to parse
    if (pemFormattedCertificate != null) {
        StringReader stringReader = new StringReader(pemFormattedCertificate);
        PEMParser pemReader = new PEMParser(stringReader);
        try {
            Object object = pemReader.readObject();
            log.trace("Object found while paring PEM formatted string: {}", object);

            if (object instanceof X509CertificateHolder) {
                X509CertificateHolder holder = (X509CertificateHolder) object;
                JcaX509CertificateConverter converter = new JcaX509CertificateConverter();
                return converter.getCertificate(holder);
            }
        } catch (IOException e) {
            throw new CertificateParsingException(
                    "Failed to parse valid certificate from expected PEM formatted certificate:\n"
                            + pemFormattedCertificate,
                    e);
        }
    }

    // cert was not a valid object
    throw new CertificateParsingException(
            "Failed to parse valid certificate from expected PEM formatted certificate:\n"
                    + pemFormattedCertificate);
}

From source file:org.syncany.crypto.CipherUtil.java

License:Open Source License

/**
 * Generates a self-signed certificate, given a public/private key pair.
 *
 * @see <a href="https://code.google.com/p/gitblit/source/browse/src/com/gitblit/MakeCertificate.java?r=88598bb2f779b73479512d818c675dea8fa72138">Original source of this method</a>
 *//*from   www. ja  v  a  2  s  .c  o  m*/
public static X509Certificate generateSelfSignedCertificate(String commonName, KeyPair keyPair)
        throws OperatorCreationException, CertificateException, InvalidKeyException, NoSuchAlgorithmException,
        NoSuchProviderException, SignatureException {

    // Certificate CN, O and OU
    X500NameBuilder builder = new X500NameBuilder(BCStyle.INSTANCE);

    builder.addRDN(BCStyle.CN, commonName);
    builder.addRDN(BCStyle.O, CipherParams.CERTIFICATE_ORGANIZATION);
    builder.addRDN(BCStyle.OU, CipherParams.CERTIFICATE_ORGUNIT);

    // Dates and serial
    Date notBefore = new Date(System.currentTimeMillis() - 1 * 24 * 60 * 60 * 1000L);
    Date notAfter = new Date(System.currentTimeMillis() + 5 * 365 * 24 * 60 * 60 * 1000L);
    BigInteger serial = BigInteger.valueOf(System.currentTimeMillis());

    // Issuer and subject (identical, because self-signed)
    X500Name issuer = builder.build();
    X500Name subject = issuer;

    X509v3CertificateBuilder certificateGenerator = new JcaX509v3CertificateBuilder(issuer, serial, notBefore,
            notAfter, subject, keyPair.getPublic());

    ContentSigner signatureGenerator = new JcaContentSignerBuilder("SHA256WithRSAEncryption")
            .setProvider(CipherParams.CRYPTO_PROVIDER).build(keyPair.getPrivate());

    X509Certificate certificate = new JcaX509CertificateConverter().setProvider(CipherParams.CRYPTO_PROVIDER)
            .getCertificate(certificateGenerator.build(signatureGenerator));

    certificate.checkValidity(new Date());
    certificate.verify(certificate.getPublicKey());

    return certificate;
}

From source file:org.teknux.jettybootstrap.keystore.JettyKeystore.java

License:Apache License

private static Certificate generateCertificate(KeyPair keyPair, String domainName, String signatureAlgorithm,
        String rdnOuValue, String rdnOValue, int dateNotBeforeNumberOfDays, int dateNotAfterNumberOfDays)
        throws JettyKeystoreException {

    X500NameBuilder issuerX500Namebuilder = new X500NameBuilder(BCStyle.INSTANCE);
    if (rdnOuValue != null) {
        issuerX500Namebuilder.addRDN(BCStyle.OU, rdnOuValue);
    }/*  w ww  .  ja  va 2s.c o  m*/
    if (rdnOValue != null) {
        issuerX500Namebuilder.addRDN(BCStyle.O, rdnOValue);
    }
    X500Name issuer = issuerX500Namebuilder.addRDN(BCStyle.CN, domainName).build();

    BigInteger serial = BigInteger.valueOf(Math.abs(new SecureRandom().nextInt()));
    Date dateNotBefore = new Date(System.currentTimeMillis() - (dateNotBeforeNumberOfDays * DAY_IN_MILLIS));
    Date dateNotAfter = new Date(System.currentTimeMillis() + (dateNotAfterNumberOfDays * DAY_IN_MILLIS));

    X500NameBuilder subjectX500Namebuilder = new X500NameBuilder(BCStyle.INSTANCE);
    if (rdnOuValue != null) {
        subjectX500Namebuilder.addRDN(BCStyle.OU, rdnOuValue);
    }
    if (rdnOValue != null) {
        subjectX500Namebuilder.addRDN(BCStyle.O, rdnOValue);
    }
    X500Name subject = subjectX500Namebuilder.addRDN(BCStyle.CN, domainName).build();

    SubjectPublicKeyInfo publicKeyInfo = new SubjectPublicKeyInfo(
            ASN1Sequence.getInstance(keyPair.getPublic().getEncoded()));

    X509v3CertificateBuilder x509v3CertificateBuilder = new X509v3CertificateBuilder(issuer, serial,
            dateNotBefore, dateNotAfter, subject, publicKeyInfo);

    Provider provider = new BouncyCastleProvider();

    try {
        ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm).setProvider(provider)
                .build(keyPair.getPrivate());

        return new JcaX509CertificateConverter().setProvider(provider)
                .getCertificate(x509v3CertificateBuilder.build(signer));
    } catch (OperatorCreationException | CertificateException e) {
        throw new JettyKeystoreException(JettyKeystoreException.ERROR_CREATE_CERTIFICATE,
                "Can not generate certificate", e);
    }
}