Example usage for java.security KeyStore getInstance

List of usage examples for java.security KeyStore getInstance

Introduction

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

Prototype

public static final KeyStore getInstance(File file, LoadStoreParameter param)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException 

Source Link

Document

Returns a loaded keystore object of the appropriate keystore 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  .  java2 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:ImportKey.java

/**
 * <p>/*from  ww  w.  java2s.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:net.firejack.platform.web.security.x509.KeyUtils.java

public static KeyPair generate(File keystore) {
    if (keystore == null) {
        throw new IllegalArgumentException("Key Store file should not be null.");
    }//from   www .  j a v  a  2 s  . c o m

    try {
        KeyStore ks = KeyStore.getInstance("JKS", "SUN");
        if (keystore.exists()) {
            FileInputStream stream = new FileInputStream(keystore);
            ks.load(stream, SECRET);
            IOUtils.closeQuietly(stream);
        } else {
            ks.load(null, SECRET);
        }

        if (ks.containsAlias(ALIAS)) {
            PrivateKey privateKey = (PrivateKey) ks.getKey(ALIAS, SECRET);
            PublicKey publicKey = ks.getCertificate(ALIAS).getPublicKey();
            return new KeyPair(publicKey, privateKey);
        } else {
            KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
            generator.initialize(KEYSIZE, new SecureRandom());
            return generator.generateKeyPair();
        }
    } catch (Throwable th) {
        logger.error("Failed to initialize key store");
        throw new OpenFlameRuntimeException(th.getMessage(), th);
    }
}

From source file:net.firejack.platform.web.security.x509.KeyUtils.java

public static void add(File keystore, KeyPair pair, String domain) {
    if (keystore == null) {
        throw new IllegalArgumentException("Key Store file should not be null.");
    }/*ww  w.  j av  a 2  s  . c  o m*/

    try {
        KeyStore ks = KeyStore.getInstance("JKS", "SUN");
        if (keystore.exists()) {
            FileInputStream stream = new FileInputStream(keystore);
            ks.load(stream, SECRET);
            IOUtils.closeQuietly(stream);
        } else {
            ks.load(null, SECRET);
        }

        if (!ks.containsAlias(ALIAS)) {
            X509Certificate certificate = generateCertificate(domain, 1, pair);

            ks.setKeyEntry(ALIAS, pair.getPrivate(), SECRET, new Certificate[] { certificate });

            FileOutputStream stream = new FileOutputStream(keystore);
            ks.store(stream, SECRET);
            IOUtils.closeQuietly(stream);
        }
    } catch (Throwable th) {
        logger.error("Failed to initialize key store");
        throw new OpenFlameRuntimeException(th.getMessage(), th);
    }
}

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

public List<String> getAliases() throws KeyStoreException, NoSuchAlgorithmException, CertificateException,
        IOException, UnrecoverableEntryException {
    List<String> aliases = new LinkedList<String>();
    try {//  w  w w .j  a v  a  2 s.  co m
        this.keyStore = KeyStore.getInstance("PKCS11", this.pkcs11Provider);
    } catch (KeyStoreException e) {
        JOptionPane.showMessageDialog(null, "No keystore present: " + e.getMessage(), "PKCS#11 error",
                JOptionPane.ERROR_MESSAGE);
        throw e;
    }
    LoadStoreParameter loadStoreParameter = new Pkcs11LoadStoreParameter();
    try {
        this.keyStore.load(loadStoreParameter);
    } catch (IOException e) {
        LOG.debug("I/O error: " + e.getMessage(), e);
        Throwable cause = e.getCause();
        if (null != cause) {
            if (cause instanceof FailedLoginException) {
                JOptionPane.showMessageDialog(null, "PIN incorrect", "Login failed", JOptionPane.ERROR_MESSAGE);
            }
        }
        return aliases;
    }
    Enumeration<String> aliasesEnum = this.keyStore.aliases();
    while (aliasesEnum.hasMoreElements()) {
        String alias = aliasesEnum.nextElement();
        LOG.debug("keystore alias: " + alias);
        if (false == this.keyStore.isKeyEntry(alias)) {
            continue;
        }
        aliases.add(alias);
    }
    return aliases;
}

From source file:com.oneis.common.utils.SSLCertificates.java

public static SSLContext load(String keysDirectory, String certsName, String clientCAName, boolean quiet)
        throws Exception {
    // For some indiciation of what's going on early in the boot process
    if (!quiet) {
        System.out.println("Loading " + certsName + " SSL certificates from " + keysDirectory);
    }//from   w  ww .  ja v  a2  s  .  co  m

    // Get filenames
    String keyPathname = keysDirectory + "/" + certsName + ".key";
    String certPathname = keysDirectory + "/" + certsName + ".crt";
    final String intermediateCertPathnameBase = keysDirectory + "/" + certsName + "-intermediate";
    String clientCAPathname = null;
    if (clientCAName != null) {
        clientCAPathname = keysDirectory + "/" + clientCAName + ".crt";
    }

    if (!new File(keyPathname).exists()) {
        System.out.println("Doesn't exist: " + keyPathname);
        return null;
    }
    if (!new File(certPathname).exists()) {
        System.out.println("Doesn't exist: " + certPathname);
        return null;
    }
    if (clientCAPathname != null) {
        if (!new File(clientCAPathname).exists()) {
            System.out.println("Doesn't exist: " + clientCAPathname);
            return null;
        }
    }

    char[] nullPassword = {};

    PrivateKey privateKey = readPEMPrivateKey(keyPathname);

    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    // Server certificate
    ArrayList<java.security.cert.Certificate> certList = new ArrayList<java.security.cert.Certificate>(4);
    java.security.cert.Certificate cert = cf.generateCertificate(readPEM(certPathname));
    certList.add(cert);
    // Optional intermediate certificates
    int intermediateCounter = 1;
    while (true) {
        String intermediateCertPathname = intermediateCertPathnameBase;
        if (intermediateCounter != 1) {
            intermediateCertPathname += "-" + intermediateCounter;
        }
        intermediateCounter++;
        intermediateCertPathname += ".crt";
        if (new File(intermediateCertPathname).exists()) {
            certList.add(cf.generateCertificate(readPEM(intermediateCertPathname)));
        } else {
            // End of cert list
            break;
        }
    }
    // Optional client CA certificate
    java.security.cert.Certificate clientCACert = null;
    if (clientCAPathname != null) {
        clientCACert = cf.generateCertificate(readPEM(clientCAPathname));
    }
    if (clientCAName != null && clientCACert == null) {
        throw new RuntimeException("Logic error, failed to load client CA cert when required");
    }

    KeyStore ks = KeyStore.getInstance("JKS", "SUN");
    ks.load(null, nullPassword);
    ks.setKeyEntry("ONEIS", (Key) privateKey, "".toCharArray(),
            certList.toArray(new java.security.cert.Certificate[certList.size()]));

    if (clientCACert != null) {
        KeyStore.TrustedCertificateEntry tce = new KeyStore.TrustedCertificateEntry(clientCACert);
        ks.setEntry("CLIENTCA", tce, null);
    }

    // Generate some random Java API stuff, just for entertainment
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
    kmf.init(ks, nullPassword);
    TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
    tmf.init(ks);

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

    if (!quiet) {
        System.out.println(" - server cert chain length " + certList.size()
                + (clientCACert != null ? ", requires client cert" : ", public server"));
    }
    return sslContext;
}

From source file:eu.musesproject.client.connectionmanager.TLSManager.java

/**
 * Convert local certificate to BKS/*  ww w .j  a v a 2s. co m*/
 * @param cerStream
 * @param alias
 *    
 * @param password
 * @return keyStore
 */
private KeyStore convertCerToBKS(InputStream cerStream, String alias, char[] password) {
    KeyStore keyStore = null;
    try {
        keyStore = KeyStore.getInstance("BKS", "BC");
        CertificateFactory factory = CertificateFactory.getInstance("X.509", "BC");
        Certificate certificate = factory.generateCertificate(cerStream);
        keyStore.load(null, password);
        keyStore.setCertificateEntry(alias, certificate);
    } catch (Exception e) {
        Log.d(TAG, e.getLocalizedMessage());
    }
    return keyStore;
}

From source file:be.bzbit.framework.spring.support.KeyStoreFactoryBean.java

public final void afterPropertiesSet() throws GeneralSecurityException, IOException {
    if (StringUtils.hasLength(provider) && StringUtils.hasLength(type)) {
        keyStore = KeyStore.getInstance(type, provider);
    } else if (StringUtils.hasLength(type)) {
        keyStore = KeyStore.getInstance(type);
    } else {/*from   www .  ja  va  2s.  co m*/
        keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    }
    InputStream is = null;
    try {
        if (location != null && location.exists()) {
            is = location.getInputStream();
            if (logger.isInfoEnabled()) {
                logger.info("Loading key store from " + location);
            }
        } else if (logger.isWarnEnabled()) {
            logger.warn("Creating empty key store");
        }
        keyStore.load(is, password);
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

From source file:KeystoreGeneratorTest.java

@Test
public void test() throws Exception {
    File dir = null;//from w  w  w.jav  a  2s. c  om
    FileInputStream fis = null;
    try {
        dir = Files.createTempDir();
        File keystoreFile = new File(dir, KEYSTORE_NAME);

        String config = GSON.toJson(ImmutableMap.builder().put("password", KEYSTORE_PASSWORD)
                .put("entries", ImmutableList.builder()
                        .add(ImmutableMap.builder().put("label", "rsatest1").put("algorithm", "SHA256WithRSA")
                                .put("keyAlgorithm", "RSA").put("rsaKeySize", "2048").build())
                        .add(ImmutableMap.builder().put("label", "ecdsatest1")
                                .put("algorithm", "SHA256WithECDSA").put("keyAlgorithm", "ECDSA")
                                .put("ecdsaNamedCurve", "secp192r1").build())
                        .add(ImmutableMap.builder().put("label", "ecdsatest2")
                                .put("algorithm", "SHA256WithECDSA").put("keyAlgorithm", "ECDSA")
                                .put("ecdsaNamedCurve", "secp256r1").build())
                        .build())
                .build());
        // generate
        KeyStore store = new KeystoreGenerator().generate(GSON.fromJson(config, KeystoreConfig.class));
        // write to disk
        try (FileOutputStream out = new FileOutputStream(keystoreFile)) {
            store.store(out, KEYSTORE_PASSWORD.toCharArray());
        }
        // load
        fis = new FileInputStream(keystoreFile);
        KeyStore ks = KeyStore.getInstance("PKCS12", "SunJSSE");
        ks.load(fis, KEYSTORE_PASSWORD.toCharArray());
        Enumeration<String> aliases = ks.aliases();
        while (aliases.hasMoreElements()) {
            String al = aliases.nextElement();
            System.out.println("Label: [" + al + "]");
            X509Certificate cert = (X509Certificate) ks.getCertificate(al);
            System.out.println("  Algorithm: [" + cert.getSigAlgName() + "]");
            PublicKey key = cert.getPublicKey();
            if (key instanceof ECKey) {
                ECKey eckey = (ECKey) key;
                ECParameterSpec spec = eckey.getParams();
                System.out.println("  EC spec: [" + spec + "]");
            }
        }
    } finally {
        closeQuietly(fis);
        FileUtils.deleteDirectory(dir);
    }
}

From source file:net.firejack.platform.web.security.x509.KeyUtils.java

public static KeyPair load(File keyStoreFile) {
    if (keyStoreFile != null) {
        try {//from  w w w  . j a v  a 2  s .co  m
            KeyStore ks = KeyStore.getInstance("JKS", "SUN");
            if (keyStoreFile.exists()) {
                FileInputStream stream = new FileInputStream(keyStoreFile);
                ks.load(stream, SECRET);
                IOUtils.closeQuietly(stream);

                PrivateKey privateKey = (PrivateKey) ks.getKey(ALIAS, SECRET);
                if (privateKey == null)
                    return null;
                PublicKey publicKey = ks.getCertificate(ALIAS).getPublicKey();
                return new KeyPair(publicKey, privateKey);
            }
        } catch (Throwable th) {
            logger.error("Failed to initialize key store");
            throw new OpenFlameRuntimeException(th.getMessage(), th);
        }
    } else {
        throw new IllegalArgumentException("Key Store file should not be null.");
    }
    return null;
}