Example usage for java.security.cert CertificateFactory generateCertificate

List of usage examples for java.security.cert CertificateFactory generateCertificate

Introduction

In this page you can find the example usage for java.security.cert CertificateFactory generateCertificate.

Prototype

public final Certificate generateCertificate(InputStream inStream) throws CertificateException 

Source Link

Document

Generates a certificate object and initializes it with the data read from the input stream inStream .

Usage

From source file:mitm.application.djigzo.james.Certificates.java

private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
    try {/* www  .j a v  a  2s . c o  m*/
        CertificateFactory certificateFactory = SecurityFactoryFactory.getSecurityFactory()
                .createCertificateFactory("X.509");

        certificates = new HashSet<X509Certificate>();

        long version = in.readLong();

        if (version != serialVersionUID) {
            throw new SerializationException("Version expected '" + serialVersionUID + "' but got '" + version);
        }

        /*
         * Read how many certificates we have to read.
         */
        int nrOfCertificates = in.readInt();

        for (int i = 0; i < nrOfCertificates; i++) {
            int encodedSize = in.readInt();

            byte[] encoded = new byte[encodedSize];

            in.readFully(encoded);

            X509Certificate certificate = (X509Certificate) certificateFactory
                    .generateCertificate(new ByteArrayInputStream(encoded));

            certificates.add(certificate);
        }
    } catch (NoSuchProviderException e) {
        throw new NoSuchProviderRuntimeException(e);
    } catch (CertificateException e) {
        throw new IOException(e);
    } catch (SecurityFactoryFactoryException e) {
        throw new IOException(e);
    }
}

From source file:org.signserver.client.cli.defaultimpl.TimeStampCommand.java

/**
 * Reads a certificate in PEM-format from an InputStream.
 *
 * The stream may contain other things, the first certificate in the
 * stream is read./*from   w  ww  . j  av a2s  .  co  m*/
 *
 * @param certstream the input stream containing the certificate in
 * PEM-format
 * @return Ordered List of X509Certificate, first certificate first,
 * or empty List
 * @exception IOException if the stream cannot be read.
 * @exception CertificateException if the stream does not contain a
 * correct certificate.
 */
private List<X509Certificate> getCertsFromPEM(final InputStream certstream)
        throws IOException, CertificateException {
    final ArrayList<X509Certificate> ret = new ArrayList<X509Certificate>();

    final BufferedReader bufRdr = new BufferedReader(new InputStreamReader(certstream));

    while (bufRdr.ready()) {
        final ByteArrayOutputStream ostr = new ByteArrayOutputStream();
        final PrintStream opstr = new PrintStream(ostr);
        String temp;
        while ((temp = bufRdr.readLine()) != null && !temp.equals(PEM_BEGIN)) {
        }
        if (temp == null) {
            throw new IOException("Error in " + certstream.toString() + ", missing " + PEM_BEGIN + " boundary");
        }
        while ((temp = bufRdr.readLine()) != null && !temp.equals(PEM_END)) {
            opstr.print(temp);
        }
        if (temp == null) {
            throw new IOException("Error in " + certstream.toString() + ", missing " + PEM_END + " boundary");
        }
        opstr.close();

        final byte[] certbuf = Base64.decode(ostr.toByteArray());
        ostr.close();
        // Phweeew, were done, now decode the cert from file back to
        // X509Certificate object
        final CertificateFactory cf = getCertificateFactory();
        final X509Certificate x509cert = (X509Certificate) cf
                .generateCertificate(new ByteArrayInputStream(certbuf));
        ret.add(x509cert);
    }
    return ret;
}

From source file:be.fedict.eid.applet.service.impl.handler.AuthenticationDataMessageHandler.java

private X509Certificate getCertificate(byte[] certData) {
    CertificateFactory certificateFactory;
    try {//from   w w w. j a v  a2s .com
        certificateFactory = CertificateFactory.getInstance("X.509");
    } catch (CertificateException e) {
        throw new RuntimeException("cert factory error: " + e.getMessage(), e);
    }
    try {
        X509Certificate certificate = (X509Certificate) certificateFactory
                .generateCertificate(new ByteArrayInputStream(certData));
        return certificate;
    } catch (CertificateException e) {
        throw new RuntimeException("certificate decoding error: " + e.getMessage(), e);
    }
}

From source file:org.jvnet.hudson.update_center.Main.java

/**
 * Loads a certificate chain and makes sure it's valid.
 *//* w  ww. j  a  v  a 2 s .c  o m*/
protected List<X509Certificate> getCertificateChain() throws IOException, GeneralSecurityException {
    CertificateFactory cf = CertificateFactory.getInstance("X509");
    List<X509Certificate> certs = new ArrayList<X509Certificate>();
    for (File f : certificates) {
        X509Certificate c = loadCertificate(cf, f);
        c.checkValidity(new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(30)));
        certs.add(c);
    }

    Set<TrustAnchor> rootCAs = CertificateUtil.getDefaultRootCAs();
    rootCAs.add(new TrustAnchor(
            (X509Certificate) cf.generateCertificate(getClass().getResourceAsStream("/hudson-community.cert")),
            null));
    for (File f : rootCA) {
        rootCAs.add(new TrustAnchor(loadCertificate(cf, f), null));
    }

    try {
        CertificateUtil.validatePath(certs, rootCAs);
    } catch (GeneralSecurityException e) {
        e.printStackTrace();
    }
    return certs;
}

From source file:org.wso2.carbon.certificate.mgt.core.impl.CertificateGenerator.java

public List<X509Certificate> getRootCertificates(byte[] ca, byte[] ra) throws KeystoreException {

    if (ca == null) {
        throw new KeystoreException("CA certificate is mandatory");
    }/*from  w  ww.  j  a v  a  2  s. c  om*/

    if (ra == null) {
        throw new KeystoreException("RA certificate is mandatory");
    }

    List<X509Certificate> certificateList = new ArrayList<X509Certificate>();
    InputStream caInputStream = null;
    InputStream raInputStream = null;

    try {
        CertificateFactory certificateFactory = CertificateFactory
                .getInstance(CertificateManagementConstants.X_509);
        caInputStream = new ByteArrayInputStream(ca);
        raInputStream = new ByteArrayInputStream(ra);

        X509Certificate caCert = (X509Certificate) certificateFactory.generateCertificate(caInputStream);
        X509Certificate raCert = (X509Certificate) certificateFactory.generateCertificate(raInputStream);

        certificateList.add(caCert);
        certificateList.add(raCert);
    } catch (CertificateException e) {
        String errorMsg = "Error occurred while fetching root certificates";
        throw new KeystoreException(errorMsg, e);
    } finally {
        if (caInputStream != null) {
            try {
                caInputStream.close();
            } catch (IOException e) {
                log.error("Error occurred when closing CA input stream");
            }
        }

        if (raInputStream != null) {
            try {
                raInputStream.close();
            } catch (IOException e) {
                log.error("Error occurred when closing RA input stream");
            }
        }
    }

    return certificateList;
}

From source file:be.fedict.eid.tsl.TrustService.java

public X509Certificate getServiceDigitalIdentity(DigitalIdentityListType digitalIdentityList) {

    try {//from ww  w .  jav a  2s.c o  m
        final CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        for (final DigitalIdentityType digitalIdentity : digitalIdentityList.getDigitalId()) {
            byte[] x509CertificateData = digitalIdentity.getX509Certificate();
            if (x509CertificateData != null) {
                try {
                    X509Certificate certificate = (X509Certificate) certificateFactory
                            .generateCertificate(new ByteArrayInputStream(x509CertificateData));
                    return certificate;
                } catch (CertificateException e) {
                    throw new RuntimeException("X509 error: " + e.getMessage(), e);
                }
            }
        }
        throw new RuntimeException("No X509Certificate identity specified");
    } catch (CertificateException e) {
        throw new RuntimeException("X509 error: " + e.getMessage(), e);
    }
}

From source file:be.fedict.eid.tsl.TrustService.java

public X509Certificate getServiceDigitalIdentity() {
    TSPServiceInformationType tspServiceInformation = this.tspService.getServiceInformation();
    DigitalIdentityListType digitalIdentityList = tspServiceInformation.getServiceDigitalIdentity();
    try {/*from w w w .ja v  a  2s . com*/
        final CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        for (final DigitalIdentityType digitalIdentity : digitalIdentityList.getDigitalId()) {
            byte[] x509CertificateData = digitalIdentity.getX509Certificate();
            if (x509CertificateData != null) {
                try {
                    X509Certificate certificate = (X509Certificate) certificateFactory
                            .generateCertificate(new ByteArrayInputStream(x509CertificateData));
                    return certificate;
                } catch (CertificateException e) {
                    throw new RuntimeException("X509 error: " + e.getMessage(), e);
                }
            }
        }
        throw new RuntimeException("No X509Certificate identity specified");
    } catch (CertificateException e) {
        throw new RuntimeException("X509 error: " + e.getMessage(), e);
    }
}

From source file:be.fedict.eid.tsl.TrustService.java

public byte[] getServiceDigitalIdentityData() {
    TSPServiceInformationType tspServiceInformation = this.tspService.getServiceInformation();
    DigitalIdentityListType digitalIdentityList = tspServiceInformation.getServiceDigitalIdentity();
    try {/*from   ww  w .  ja v  a  2s  .c  om*/
        final CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        for (final DigitalIdentityType digitalIdentity : digitalIdentityList.getDigitalId()) {
            byte[] x509CertificateData = digitalIdentity.getX509Certificate();
            if (x509CertificateData != null) {
                try {
                    X509Certificate certificate = (X509Certificate) certificateFactory
                            .generateCertificate(new ByteArrayInputStream(x509CertificateData));
                    return x509CertificateData;
                } catch (CertificateException e) {
                    throw new RuntimeException("X509 error: " + e.getMessage(), e);
                }
            }
        }
        throw new RuntimeException("No X509Certificate identity specified");
    } catch (CertificateException e) {
        throw new RuntimeException("X509 error: " + e.getMessage(), e);
    }
}

From source file:org.warlock.itk.distributionenvelope.Payload.java

/**
 * Retrieves the certificate used for an enveloping signature.
 * @param signature//from  w w  w . j a va 2  s  .co m
 * @return
 * @throws Exception 
 */
private X509Certificate getCertificate(Element signature) throws Exception {
    NodeList nl = signature.getElementsByTagNameNS(CfHNamespaceContext.DSNAMESPACE, "X509Certificate");
    if (nl.getLength() == 0) {
        throw new Exception("Cannot find certificate in signature");
    }
    Element x509cert = (Element) nl.item(0);
    StringBuilder sb = new StringBuilder("-----BEGIN CERTIFICATE-----\n");
    String encodedKey = x509cert.getTextContent();
    sb.append(encodedKey);
    if (encodedKey.charAt(encodedKey.length() - 1) != '\n') {
        sb.append("\n");
    }
    sb.append("-----END CERTIFICATE-----");
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509Certificate x = (X509Certificate) cf
            .generateCertificate(new ByteArrayInputStream(sb.toString().getBytes()));
    return x;
}

From source file:com.cws.esolutions.security.dao.certmgmt.impl.CertificateManagerImpl.java

/**
 * @see com.cws.esolutions.security.dao.certmgmt.interfaces.ICertificateManager#createCertificateRequest(List, String, int, int)
 *//*from  w  w  w.  ja  v a2  s  .  co  m*/
public synchronized File createCertificateRequest(final List<String> subjectData, final String storePassword,
        final int validityPeriod, final int keySize) throws CertificateManagementException {
    final String methodName = ICertificateManager.CNAME
            + "#createCertificateRequest(final List<String> subjectData, final String storePassword, final int validityPeriod, final int keySize) throws CertificateManagementException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", subjectData);
        DEBUGGER.debug("Value: {}", validityPeriod);
        DEBUGGER.debug("Value: {}", keySize);
    }

    final File rootDirectory = certConfig.getRootDirectory();
    final String signatureAlgorithm = certConfig.getSignatureAlgorithm();
    final String certificateAlgorithm = certConfig.getCertificateAlgorithm();
    final File privateKeyDirectory = FileUtils
            .getFile(certConfig.getPrivateKeyDirectory() + "/" + subjectData.get(0));
    final File publicKeyDirectory = FileUtils
            .getFile(certConfig.getPublicKeyDirectory() + "/" + subjectData.get(0));
    final File csrDirectory = FileUtils.getFile(certConfig.getCsrDirectory() + "/" + subjectData.get(0));
    final File storeDirectory = FileUtils.getFile(certConfig.getStoreDirectory() + "/" + subjectData.get(0));
    final X500Name x500Name = new X500Name("CN=" + subjectData.get(0) + ",OU=" + subjectData.get(1) + ",O="
            + subjectData.get(2) + ",L=" + subjectData.get(3) + ",ST=" + subjectData.get(4) + ",C="
            + subjectData.get(5) + ",E=" + subjectData.get(6));

    if (DEBUG) {
        DEBUGGER.debug("rootDirectory: {}", rootDirectory);
        DEBUGGER.debug("signatureAlgorithm: {}", signatureAlgorithm);
        DEBUGGER.debug("certificateAlgorithm: {}", certificateAlgorithm);
        DEBUGGER.debug("privateKeyDirectory: {}", privateKeyDirectory);
        DEBUGGER.debug("publicKeyDirectory: {}", publicKeyDirectory);
        DEBUGGER.debug("csrDirectory: {}", csrDirectory);
        DEBUGGER.debug("storeDirectory: {}", storeDirectory);
        DEBUGGER.debug("x500Name: {}", x500Name);
    }

    File csrFile = null;
    JcaPEMWriter csrPemWriter = null;
    JcaPEMWriter publicKeyWriter = null;
    JcaPEMWriter privateKeyWriter = null;
    FileOutputStream csrFileStream = null;
    FileOutputStream keyStoreStream = null;
    FileOutputStream publicKeyFileStream = null;
    FileOutputStream privateKeyFileStream = null;
    OutputStreamWriter csrFileStreamWriter = null;
    OutputStreamWriter privateKeyStreamWriter = null;
    OutputStreamWriter publicKeyStreamWriter = null;

    try {
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, storePassword.toCharArray());

        if (DEBUG) {
            DEBUGGER.debug("KeyStore: {}", keyStore);
        }

        SecureRandom random = new SecureRandom();
        KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance(certificateAlgorithm);
        keyGenerator.initialize(keySize, random);

        if (DEBUG) {
            DEBUGGER.debug("KeyGenerator: {}", keyGenerator);
        }

        KeyPair keyPair = keyGenerator.generateKeyPair();

        if (DEBUG) {
            DEBUGGER.debug("KeyPair: {}", keyPair);
        }

        if (keyPair != null) {
            final Signature sig = Signature.getInstance(signatureAlgorithm);
            final PrivateKey privateKey = keyPair.getPrivate();
            final PublicKey publicKey = keyPair.getPublic();

            if (DEBUG) {
                DEBUGGER.debug("Signature: {}", sig);
                DEBUGGER.debug("PrivateKey: {}", privateKey);
                DEBUGGER.debug("PublicKey: {}", publicKey);
            }

            sig.initSign(privateKey, random);
            ContentSigner signGen = new JcaContentSignerBuilder(signatureAlgorithm).build(privateKey);

            if (DEBUG) {
                DEBUGGER.debug("ContentSigner: {}", signGen);
            }

            Calendar expiry = Calendar.getInstance();
            expiry.add(Calendar.DAY_OF_YEAR, validityPeriod);

            if (DEBUG) {
                DEBUGGER.debug("Calendar: {}", expiry);
            }

            CertificateFactory certFactory = CertificateFactory.getInstance(certConfig.getCertificateType());

            if (DEBUG) {
                DEBUGGER.debug("CertificateFactory: {}", certFactory);
            }

            X509Certificate[] issuerCert = new X509Certificate[] { (X509Certificate) certFactory
                    .generateCertificate(new FileInputStream(certConfig.getIntermediateCertificateFile())) };

            if (DEBUG) {
                DEBUGGER.debug("X509Certificate[]: {}", (Object) issuerCert);
            }

            keyStore.setCertificateEntry(certConfig.getRootCertificateName(), certFactory.generateCertificate(
                    new FileInputStream(FileUtils.getFile(certConfig.getRootCertificateFile()))));
            keyStore.setCertificateEntry(certConfig.getIntermediateCertificateName(),
                    certFactory.generateCertificate(new FileInputStream(
                            FileUtils.getFile(certConfig.getIntermediateCertificateFile()))));

            PKCS10CertificationRequestBuilder builder = new JcaPKCS10CertificationRequestBuilder(x500Name,
                    publicKey);

            if (DEBUG) {
                DEBUGGER.debug("PKCS10CertificationRequestBuilder: {}", builder);
            }

            PKCS10CertificationRequest csr = builder.build(signGen);

            if (DEBUG) {
                DEBUGGER.debug("PKCS10CertificationRequest: {}", csr);
            }

            // write private key
            File privateKeyFile = FileUtils.getFile(privateKeyDirectory + "/" + subjectData.get(0)
                    + SecurityServiceConstants.PRIVATEKEY_FILE_EXT);

            if (DEBUG) {
                DEBUGGER.debug("privateKeyFile: {}", privateKeyFile);
            }

            if (!(privateKeyFile.createNewFile())) {
                throw new IOException("Failed to store private file");
            }

            privateKeyFileStream = new FileOutputStream(privateKeyFile);
            privateKeyStreamWriter = new OutputStreamWriter(privateKeyFileStream);

            if (DEBUG) {
                DEBUGGER.debug("privateKeyFileStream: {}", privateKeyFileStream);
                DEBUGGER.debug("privateKeyStreamWriter: {}", privateKeyStreamWriter);
            }

            privateKeyWriter = new JcaPEMWriter(privateKeyStreamWriter);
            privateKeyWriter.writeObject(privateKey);
            privateKeyWriter.flush();
            privateKeyStreamWriter.flush();
            privateKeyFileStream.flush();

            // write public key
            File publicKeyFile = FileUtils.getFile(publicKeyDirectory + "/" + subjectData.get(0)
                    + SecurityServiceConstants.PUBLICKEY_FILE_EXT);

            if (DEBUG) {
                DEBUGGER.debug("publicKeyFile: {}", publicKeyFile);
            }

            if (!(publicKeyFile.createNewFile())) {
                throw new IOException("Failed to store public key file");
            }

            publicKeyFileStream = new FileOutputStream(publicKeyFile);
            publicKeyStreamWriter = new OutputStreamWriter(publicKeyFileStream);

            if (DEBUG) {
                DEBUGGER.debug("publicKeyFileStream: {}", publicKeyFileStream);
                DEBUGGER.debug("publicKeyStreamWriter: {}", publicKeyStreamWriter);
            }

            publicKeyWriter = new JcaPEMWriter(publicKeyStreamWriter);
            publicKeyWriter.writeObject(publicKey);
            publicKeyWriter.flush();
            publicKeyStreamWriter.flush();
            publicKeyFileStream.flush();

            // write csr
            csrFile = FileUtils
                    .getFile(csrDirectory + "/" + subjectData.get(0) + SecurityServiceConstants.CSR_FILE_EXT);

            if (DEBUG) {
                DEBUGGER.debug("csrFile: {}", csrFile);
            }

            if (!(csrFile.createNewFile())) {
                throw new IOException("Failed to store CSR file");
            }

            csrFileStream = new FileOutputStream(csrFile);
            csrFileStreamWriter = new OutputStreamWriter(csrFileStream);

            if (DEBUG) {
                DEBUGGER.debug("publicKeyFileStream: {}", publicKeyFileStream);
                DEBUGGER.debug("publicKeyStreamWriter: {}", publicKeyStreamWriter);
            }

            csrPemWriter = new JcaPEMWriter(csrFileStreamWriter);
            csrPemWriter.writeObject(csr);
            csrPemWriter.flush();
            csrFileStreamWriter.flush();
            csrFileStream.flush();

            File keyStoreFile = FileUtils
                    .getFile(storeDirectory + "/" + subjectData.get(0) + "." + KeyStore.getDefaultType());

            if (DEBUG) {
                DEBUGGER.debug("keyStoreFile: {}", keyStoreFile);
            }

            keyStoreStream = FileUtils.openOutputStream(keyStoreFile);

            if (DEBUG) {
                DEBUGGER.debug("keyStoreStream: {}", keyStoreStream);
            }

            keyStore.setKeyEntry(subjectData.get(0), (Key) keyPair.getPrivate(), storePassword.toCharArray(),
                    issuerCert);
            keyStore.store(keyStoreStream, storePassword.toCharArray());
            keyStoreStream.flush();

            if (DEBUG) {
                DEBUGGER.debug("KeyStore: {}", keyStore);
            }
        } else {
            throw new CertificateManagementException("Failed to generate keypair. Cannot continue.");
        }
    } catch (FileNotFoundException fnfx) {
        throw new CertificateManagementException(fnfx.getMessage(), fnfx);
    } catch (IOException iox) {
        throw new CertificateManagementException(iox.getMessage(), iox);
    } catch (NoSuchAlgorithmException nsax) {
        throw new CertificateManagementException(nsax.getMessage(), nsax);
    } catch (IllegalStateException isx) {
        throw new CertificateManagementException(isx.getMessage(), isx);
    } catch (InvalidKeyException ikx) {
        throw new CertificateManagementException(ikx.getMessage(), ikx);
    } catch (OperatorCreationException ocx) {
        throw new CertificateManagementException(ocx.getMessage(), ocx);
    } catch (KeyStoreException ksx) {
        throw new CertificateManagementException(ksx.getMessage(), ksx);
    } catch (CertificateException cx) {
        throw new CertificateManagementException(cx.getMessage(), cx);
    } finally {
        if (csrFileStreamWriter != null) {
            IOUtils.closeQuietly(csrFileStreamWriter);
        }

        if (csrFileStream != null) {
            IOUtils.closeQuietly(csrFileStream);
        }

        if (csrPemWriter != null) {
            IOUtils.closeQuietly(csrPemWriter);
        }

        if (publicKeyFileStream != null) {
            IOUtils.closeQuietly(publicKeyFileStream);
        }

        if (publicKeyStreamWriter != null) {
            IOUtils.closeQuietly(publicKeyStreamWriter);
        }

        if (publicKeyWriter != null) {
            IOUtils.closeQuietly(publicKeyWriter);
        }

        if (privateKeyFileStream != null) {
            IOUtils.closeQuietly(privateKeyFileStream);
        }

        if (privateKeyStreamWriter != null) {
            IOUtils.closeQuietly(privateKeyStreamWriter);
        }

        if (privateKeyWriter != null) {
            IOUtils.closeQuietly(privateKeyWriter);
        }

        if (keyStoreStream != null) {
            IOUtils.closeQuietly(keyStoreStream);
        }
    }

    return csrFile;
}