Example usage for java.security.cert CertificateFactory getInstance

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

Introduction

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

Prototype

public static final CertificateFactory getInstance(String type) throws CertificateException 

Source Link

Document

Returns a certificate factory object that implements the specified certificate type.

Usage

From source file:CertificateSigner.java

public static void main(String[] args) {
    String ksname = null; // the keystore name
    String alias = null; // the private key alias
    String inname = null; // the input file name
    String outname = null; // the output file name
    for (int i = 0; i < args.length; i += 2) {
        if (args[i].equals("-keystore"))
            ksname = args[i + 1];/*from   ww  w.  j  a  va2  s. co m*/
        else if (args[i].equals("-alias"))
            alias = args[i + 1];
        else if (args[i].equals("-infile"))
            inname = args[i + 1];
        else if (args[i].equals("-outfile"))
            outname = args[i + 1];
        else
            usage();
    }

    if (ksname == null || alias == null || inname == null || outname == null)
        usage();

    try {
        Console console = System.console();
        if (console == null)
            error("No console");
        char[] password = console.readPassword("Keystore password: ");
        KeyStore store = KeyStore.getInstance("JKS", "SUN");
        InputStream in = new FileInputStream(ksname);
        store.load(in, password);
        Arrays.fill(password, ' ');
        in.close();

        char[] keyPassword = console.readPassword("Key password for %s: ", alias);
        PrivateKey issuerPrivateKey = (PrivateKey) store.getKey(alias, keyPassword);
        Arrays.fill(keyPassword, ' ');

        if (issuerPrivateKey == null)
            error("No such private key");

        in = new FileInputStream(inname);

        CertificateFactory factory = CertificateFactory.getInstance("X.509");

        X509Certificate inCert = (X509Certificate) factory.generateCertificate(in);
        in.close();
        byte[] inCertBytes = inCert.getTBSCertificate();

        X509Certificate issuerCert = (X509Certificate) store.getCertificate(alias);
        Principal issuer = issuerCert.getSubjectDN();
        String issuerSigAlg = issuerCert.getSigAlgName();

        FileOutputStream out = new FileOutputStream(outname);

        X509CertInfo info = new X509CertInfo(inCertBytes);
        info.set(X509CertInfo.ISSUER, new CertificateIssuerName((X500Name) issuer));

        X509CertImpl outCert = new X509CertImpl(info);
        outCert.sign(issuerPrivateKey, issuerSigAlg);
        outCert.derEncode(out);

        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:createSod.java

/**
 * @param args//from  w  w  w.  j a v a2 s.c  o m
 * @throws CMSException 
 */
public static void main(String[] args) throws Exception {

    try {
        CommandLine options = verifyArgs(args);
        String privateKeyLocation = options.getOptionValue("privatekey");
        String keyPassword = options.getOptionValue("keypass");
        String certificate = options.getOptionValue("certificate");
        String sodContent = options.getOptionValue("content");
        String sod = "";
        if (options.hasOption("out")) {
            sod = options.getOptionValue("out");
        }

        // CHARGEMENT DU FICHIER PKCS#12

        KeyStore ks = null;
        char[] password = null;

        Security.addProvider(new BouncyCastleProvider());
        try {
            ks = KeyStore.getInstance("PKCS12");
            // Password pour le fichier personnal_nyal.p12
            password = keyPassword.toCharArray();
            ks.load(new FileInputStream(privateKeyLocation), password);
        } catch (Exception e) {
            System.out.println("Erreur: fichier " + privateKeyLocation
                    + " n'est pas un fichier pkcs#12 valide ou passphrase incorrect");
            return;
        }

        // RECUPERATION DU COUPLE CLE PRIVEE/PUBLIQUE ET DU CERTIFICAT PUBLIQUE

        X509Certificate cert = null;
        PrivateKey privatekey = null;
        PublicKey publickey = null;

        try {
            Enumeration en = ks.aliases();
            String ALIAS = "";
            Vector vectaliases = new Vector();

            while (en.hasMoreElements())
                vectaliases.add(en.nextElement());
            String[] aliases = (String[]) (vectaliases.toArray(new String[0]));
            for (int i = 0; i < aliases.length; i++)
                if (ks.isKeyEntry(aliases[i])) {
                    ALIAS = aliases[i];
                    break;
                }
            privatekey = (PrivateKey) ks.getKey(ALIAS, password);
            cert = (X509Certificate) ks.getCertificate(ALIAS);
            publickey = ks.getCertificate(ALIAS).getPublicKey();
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        // Chargement du certificat  partir du fichier

        InputStream inStream = new FileInputStream(certificate);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        cert = (X509Certificate) cf.generateCertificate(inStream);
        inStream.close();

        // Chargement du fichier qui va tre sign

        File file_to_sign = new File(sodContent);
        byte[] buffer = new byte[(int) file_to_sign.length()];
        DataInputStream in = new DataInputStream(new FileInputStream(file_to_sign));
        in.readFully(buffer);
        in.close();

        // Chargement des certificats qui seront stocks dans le fichier .p7
        // Ici, seulement le certificat personnal_nyal.cer sera associ.
        // Par contre, la chane des certificats non.

        ArrayList certList = new ArrayList();
        certList.add(cert);
        CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList),
                "BC");

        CMSSignedDataGenerator signGen = new CMSSignedDataGenerator();

        // privatekey correspond  notre cl prive rcupre du fichier PKCS#12
        // cert correspond au certificat publique personnal_nyal.cer
        // Le dernier argument est l'algorithme de hachage qui sera utilis

        signGen.addSigner(privatekey, cert, CMSSignedDataGenerator.DIGEST_SHA1);
        signGen.addCertificatesAndCRLs(certs);
        CMSProcessable content = new CMSProcessableByteArray(buffer);

        // Generation du fichier CMS/PKCS#7
        // L'argument deux permet de signifier si le document doit tre attach avec la signature
        //     Valeur true:  le fichier est attach (c'est le cas ici)
        //     Valeur false: le fichier est dtach

        CMSSignedData signedData = signGen.generate(content, true, "BC");
        byte[] signeddata = signedData.getEncoded();

        // Ecriture du buffer dans un fichier.   

        if (sod.equals("")) {
            System.out.print(signeddata.toString());
        } else {
            FileOutputStream envfos = new FileOutputStream(sod);
            envfos.write(signeddata);
            envfos.close();
        }

    } catch (OptionException oe) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(NAME, getOptions());
        System.exit(-1);
    } catch (Exception e) {
        e.printStackTrace();
        return;
    }

}

From source file:ImportKey.java

/**
 * <p>/* w  w  w  .  j a v  a  2  s .  c  o  m*/
 * Takes two file names for a key and the certificate for the key, and
 * imports those into a keystore. Optionally it takes an alias for the key.
 * <p>
 * The first argument is the filename for the key. The key should be in
 * PKCS8-format.
 * <p>
 * The second argument is the filename for the certificate for the key.
 * <p>
 * If a third argument is given it is used as the alias. If missing, the key
 * is imported with the alias importkey
 * <p>
 * The name of the keystore file can be controlled by setting the keystore
 * property (java -Dkeystore=mykeystore). If no name is given, the file is
 * named <code>keystore.ImportKey</code> and placed in your home directory.
 * 
 * @param args
 *            [0] Name of the key file, [1] Name of the certificate file [2]
 *            Alias for the key.
 **/
public static void main(String args[]) {

    // change this if you want another password by default
    String keypass = "password";

    // change this if you want another alias by default
    String defaultalias = "tomcat";

    // change this if you want another keystorefile by default
    String keystorename = null;

    // parsing command line input
    String keyfile = "";
    String certfile = "";
    if (args.length < 3 || args.length > 4) {
        System.out.println("Usage: java comu.ImportKey keystore keyfile certfile [alias]");
        System.exit(0);
    } else {
        keystorename = args[0];
        keyfile = args[1];
        certfile = args[2];
        if (args.length > 3)
            defaultalias = args[3];
    }

    try {
        // initializing and clearing keystore
        KeyStore ks = KeyStore.getInstance("JKS", "SUN");
        ks.load(null, keypass.toCharArray());
        System.out.println("Using keystore-file : " + keystorename);
        ks.store(new FileOutputStream(keystorename), keypass.toCharArray());
        ks.load(new FileInputStream(keystorename), keypass.toCharArray());

        // loading Key
        InputStream fl = fullStream(keyfile);
        byte[] key = new byte[fl.available()];
        KeyFactory kf = KeyFactory.getInstance("RSA");
        fl.read(key, 0, fl.available());
        fl.close();
        PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec(key);
        PrivateKey ff = kf.generatePrivate(keysp);

        // loading CertificateChain
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        InputStream certstream = fullStream(certfile);

        Collection c = cf.generateCertificates(certstream);
        Certificate[] certs = new Certificate[c.toArray().length];

        if (c.size() == 1) {
            certstream = fullStream(certfile);
            System.out.println("One certificate, no chain.");
            Certificate cert = cf.generateCertificate(certstream);
            certs[0] = cert;
        } else {
            System.out.println("Certificate chain length: " + c.size());
            certs = (Certificate[]) c.toArray(new Certificate[c.size()]);
        }

        // storing keystore
        ks.setKeyEntry(defaultalias, ff, keypass.toCharArray(), certs);
        System.out.println("Key and certificate stored.");
        System.out.println("Alias:" + defaultalias + "  Password:" + keypass);
        ks.store(new FileOutputStream(keystorename), keypass.toCharArray());
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:Main.java

static CertificateFactory createX509CertificateFactory(String provider)
        throws CertificateException, NoSuchProviderException {
    if (provider == null) {
        return CertificateFactory.getInstance("X.509");
    }//from ww w .j a  v a2s.  co  m

    return CertificateFactory.getInstance("X.509", provider);
}

From source file:Main.java

public static X509Certificate unserializeCert(String cert) throws CertificateException {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    InputStream in = new ByteArrayInputStream(cert.getBytes());
    return (X509Certificate) cf.generateCertificate(in);
}

From source file:Main.java

/**
 * populate X509Certificate from a certificate file at the certFilePath
 *//*from   w w w . j  a v  a2 s.  c  o  m*/
public static X509Certificate getX509(String certFilePath) throws CertificateException, FileNotFoundException {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    FileInputStream in = new FileInputStream(certFilePath);
    return (X509Certificate) cf.generateCertificate(in);
}

From source file:Main.java

public static List<Certificate> loadCertificates(String[] pemEncodedCerts) throws Exception {

    List<Certificate> certList = new ArrayList<>();
    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");

    for (String certPem : pemEncodedCerts) {
        InputStream certIn = new ByteArrayInputStream(certPem.getBytes());
        Certificate cert = certFactory.generateCertificate(certIn);
        certList.add(cert);/*from  w  w w.java 2s  . com*/
    }

    return certList;
}

From source file:Main.java

private static SSLContext sslContextForTrustedCertificates(InputStream in) {
    try {/*from ww  w.  ja  v  a 2s . c o m*/
        CertificateFactory e = CertificateFactory.getInstance("X.509");
        Collection certificates = e.generateCertificates(in);
        if (certificates.isEmpty()) {
            throw new IllegalArgumentException("expected non-empty set of trusted certificates");
        } else {
            char[] password = "password".toCharArray();
            KeyStore keyStore = newEmptyKeyStore(password);
            int index = 0;
            Iterator keyManagerFactory = certificates.iterator();
            while (keyManagerFactory.hasNext()) {
                Certificate trustManagerFactory = (Certificate) keyManagerFactory.next();
                String sslContext = Integer.toString(index++);
                keyStore.setCertificateEntry(sslContext, trustManagerFactory);
            }

            KeyManagerFactory var10 = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            var10.init(keyStore, password);
            TrustManagerFactory var11 = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            var11.init(keyStore);
            SSLContext var12 = SSLContext.getInstance("TLS");
            var12.init(var10.getKeyManagers(), var11.getTrustManagers(), new SecureRandom());
            return var12;
        }
    } catch (Exception var9) {
        var9.printStackTrace();
    }
    return null;
}

From source file:Main.java

public static SSLSocketFactory setCertificates(InputStream... certificates) {
    try {/*from   w  w  w  .j a  v a2 s.  c  o m*/
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null);
        int index = 0;
        for (InputStream certificate : certificates) {
            String certificateAlias = Integer.toString(index++);
            keyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(certificate));
            try {
                if (certificate != null)
                    certificate.close();
            } catch (IOException e) {
            }
        }
        SSLContext sslContext = SSLContext.getInstance("TLS");
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);
        sslContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());
        socketFactory = sslContext.getSocketFactory();

    } catch (Exception e) {
        e.printStackTrace();
    }
    return socketFactory;
}

From source file:Main.java

/**
 * parse a certificate file into ArrayList of certificates
 *///from w w w  . j ava2s  .c  om
public static ArrayList<Certificate> readCertificate(File f) throws CertificateException {
    ArrayList<Certificate> certs = new ArrayList<Certificate>();
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    BufferedInputStream in;
    try {
        in = new BufferedInputStream(new FileInputStream(f));
        while (in.available() > 0) {
            Certificate cert = cf.generateCertificate(in);
            certs.add(cert);
        }
        in.close();
        return certs;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}