Example usage for java.security KeyStore load

List of usage examples for java.security KeyStore load

Introduction

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

Prototype

public final void load(InputStream stream, char[] password)
        throws IOException, NoSuchAlgorithmException, CertificateException 

Source Link

Document

Loads this KeyStore from the given input stream.

Usage

From source file:com.peterphi.std.crypto.keygen.CaHelper.java

public static void main(String[] args) throws Exception {

    String casubject = "C=UK, O=SOMEORG, OU=Org Unit, CN=Example Certificate Authority";

    X509Certificate cacert = null;
    PrivateKey caPrivateKey = null;

    if (true) {//w w w. j  a  va 2  s . co  m
        KeyStore ks = KeyStore.getInstance("PKCS12", "BC");

        ks.load(new FileInputStream(new File("/tmp/someorg-ca.p12")), new char[] {});
        caPrivateKey = (PrivateKey) ks.getKey("ca", new char[] {});

        cacert = (X509Certificate) ks.getCertificate("ca");
    } else {
        KeyPair cakeys = generateKeyPair(2048);
        caPrivateKey = cakeys.getPrivate();
        cacert = generateCaCertificate(casubject, cakeys, (BigInteger) null, new X509Name(casubject));
    }

    {
        // CA .p12
        {
            KeyStore ks = KeyStore.getInstance("PKCS12", "BC");
            ks.load(null);
            //ks.setCertificateEntry("ca", cacert);
            ks.setKeyEntry("ca", caPrivateKey, new char[] {}, new java.security.cert.Certificate[] { cacert });

            ks.store(new FileOutputStream("/tmp/someorg-ca.p12"), new char[] {});
        }

        // CA .jks (public key only)
        {
            KeyStore ks = KeyStore.getInstance("JKS");
            ks.load(null);
            ks.setCertificateEntry("ca", cacert);

            ks.store(new FileOutputStream("/tmp/ca-public.jks"), new char[] {});
        }

        // CA .pem (public key only)
        {
            PEMWriter pem = new PEMWriter(new FileWriter(new File("/tmp/d3ca.crt")));

            pem.writeObject(cacert);
            pem.close();
        }
    }

    /*
    // User
    {
       String user = "C=UK, O=SOMEORG, OU=Org Unit, L=SomeCompany, CN=Some User (test)";
       KeyPair keys = generateKeyPair(1024);
       X509Certificate cert = generateClientCertificate(keys.getPublic(), caPrivateKey, new X509Name(subject),
     new X509Name(user));
            
       {
    KeyStore ks = KeyStore.getInstance("PKCS12", "BC");
    ks.load(null);
    ks.setCertificateEntry("issuer", cacert);
    ks.setCertificateEntry("me", cert);
    ks.setKeyEntry("me", keys.getPrivate(), new char[] {}, new java.security.cert.Certificate[] { cert, cacert });
            
    ks.store(new FileOutputStream("/tmp/someorg-someuser.p12"), "SomeCompanysecurity".toCharArray());
       }
            
       {
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null);
    ks.setKeyEntry("me", keys.getPrivate(), new char[] {}, new java.security.cert.Certificate[] { cert, cacert });
    // ks.setCertificateEntry("issuer", cacert);
    // ks.setCertificateEntry("me", cert);
            
    ks.store(new FileOutputStream("/tmp/someorg-someuser.jks"), new char[] {});
       }
    }//*/

    // examplehost hostkey:
    {
        String user = "C=UK, O=SOMEORG, OU=Org Unit, L=SomeCompany, CN=examplehost.example.com";
        KeyPair keys = generateKeyPair(1024);
        X509Certificate cert = generateServerCertificate(keys.getPublic(), caPrivateKey,
                new X509Name(casubject), new X509Name(user));

        {
            KeyStore ks = KeyStore.getInstance("JKS");
            ks.load(null);
            ks.setKeyEntry("me", keys.getPrivate(), new char[] {},
                    new java.security.cert.Certificate[] { cert, cacert });
            // ks.setCertificateEntry("issuer", cacert);
            // ks.setCertificateEntry("me", cert);

            ks.store(new FileOutputStream("/tmp/host.jks"), new char[] {});
        }

        {
            KeyStore ks = KeyStore.getInstance("PKCS12", "BC");
            ks.load(null);
            ks.setCertificateEntry("issuer", cacert);
            ks.setCertificateEntry("me", cert);
            ks.setKeyEntry("me", keys.getPrivate(), new char[] {},
                    new java.security.cert.Certificate[] { cert, cacert });

            ks.store(new FileOutputStream("/tmp/host.p12"), new char[] {});
        }
    }
}

From source file:com.vmware.photon.controller.core.Main.java

public static void main(String[] args) throws Throwable {
    try {// w w  w  .j a v a2  s.c o  m
        LoggingFactory.bootstrap();

        logger.info("args: " + Arrays.toString(args));

        ArgumentParser parser = ArgumentParsers.newArgumentParser("PhotonControllerCore").defaultHelp(true)
                .description("Photon Controller Core");
        parser.addArgument("config-file").help("photon controller configuration file");
        parser.addArgument("--manual").type(Boolean.class).setDefault(false)
                .help("If true, create default deployment.");

        Namespace namespace = parser.parseArgsOrFail(args);

        PhotonControllerConfig photonControllerConfig = getPhotonControllerConfig(namespace);
        DeployerConfig deployerConfig = photonControllerConfig.getDeployerConfig();

        new LoggingFactory(photonControllerConfig.getLogging(), "photon-controller-core").configure();

        SSLContext sslContext;
        if (deployerConfig.getDeployerContext().isAuthEnabled()) {
            sslContext = SSLContext.getInstance(KeyStoreUtils.THRIFT_PROTOCOL);
            TrustManagerFactory tmf = null;

            tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            KeyStore keyStore = KeyStore.getInstance("JKS");
            InputStream in = FileUtils
                    .openInputStream(new File(deployerConfig.getDeployerContext().getKeyStorePath()));
            keyStore.load(in, deployerConfig.getDeployerContext().getKeyStorePassword().toCharArray());
            tmf.init(keyStore);
            sslContext.init(null, tmf.getTrustManagers(), null);
        } else {
            KeyStoreUtils.generateKeys("/thrift/");
            sslContext = KeyStoreUtils.acceptAllCerts(KeyStoreUtils.THRIFT_PROTOCOL);
        }

        ThriftModule thriftModule = new ThriftModule(sslContext);
        PhotonControllerXenonHost xenonHost = startXenonHost(photonControllerConfig, thriftModule,
                deployerConfig, sslContext);

        if ((Boolean) namespace.get("manual")) {
            DefaultDeployment.createDefaultDeployment(photonControllerConfig.getXenonConfig().getPeerNodes(),
                    deployerConfig, xenonHost);
        }

        // Creating a temp configuration file for apife with modification to some named sections in photon-controller-config
        // so that it can match the Configuration class of dropwizard.
        File apiFeTempConfig = File.createTempFile("apiFeTempConfig", ".tmp");
        File source = new File(args[0]);
        FileInputStream fis = new FileInputStream(source);
        BufferedReader in = new BufferedReader(new InputStreamReader(fis));

        FileWriter fstream = new FileWriter(apiFeTempConfig, true);
        BufferedWriter out = new BufferedWriter(fstream);

        String aLine = null;
        while ((aLine = in.readLine()) != null) {
            if (aLine.equals("apife:")) {
                aLine = aLine.replace("apife:", "server:");
            }
            out.write(aLine);
            out.newLine();
        }
        in.close();
        out.close();

        // This approach can be simplified once the apife container is gone, but for the time being
        // it expects the first arg to be the string "server".
        String[] apiFeArgs = new String[2];
        apiFeArgs[0] = "server";
        apiFeArgs[1] = apiFeTempConfig.getAbsolutePath();
        ApiFeService.setupApiFeConfigurationForServerCommand(apiFeArgs);
        ApiFeService.addServiceHost(xenonHost);
        ApiFeService.setSSLContext(sslContext);

        ApiFeService apiFeService = new ApiFeService();
        apiFeService.run(apiFeArgs);
        apiFeTempConfig.deleteOnExit();

        LocalApiClient localApiClient = apiFeService.getInjector().getInstance(LocalApiClient.class);
        xenonHost.setApiClient(localApiClient);

        // in the non-auth enabled scenario we need to be able to accept any self-signed certificate
        if (!deployerConfig.getDeployerContext().isAuthEnabled()) {
            KeyStoreUtils.acceptAllCerts(KeyStoreUtils.THRIFT_PROTOCOL);
        }

        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                logger.info("Shutting down");
                xenonHost.stop();
                logger.info("Done");
                LoggingFactory.detachAndStop();
            }
        });
    } catch (Exception e) {
        logger.error("Failed to start photon controller ", e);
        throw e;
    }
}

From source file:com.tremolosecurity.openunison.util.OpenUnisonUtils.java

public static void main(String[] args) throws Exception {

    logger = org.apache.logging.log4j.LogManager.getLogger(OpenUnisonUtils.class.getName());

    Options options = new Options();
    options.addOption("unisonXMLFile", true, "The full path to the Unison xml file");
    options.addOption("keystorePath", true, "The full path to the Unison keystore");
    options.addOption("chainName", true, "The name of the authentication chain");
    options.addOption("mechanismName", true, "The name of the authentication mechanism for SAML2");
    options.addOption("idpName", true, "The name of the identity provider application");
    options.addOption("pathToMetaData", true, "The full path to the saml2 metadata file");
    options.addOption("createDefault", false, "If set, add default parameters");
    options.addOption("action", true,
            "export-sp-metadata, import-sp-metadata, export-secretkey, print-secretkey, import-idp-metadata, export-idp-metadata, clear-dlq, import-secretkey, create-secretkey");
    options.addOption("urlBase", true, "Base URL, no URI; https://host:port");
    options.addOption("alias", true, "Key alias");
    options.addOption("newKeystorePath", true, "Path to the new keystore");
    options.addOption("newKeystorePassword", true, "Password for the new keystore");
    options.addOption("help", false, "Prints this message");
    options.addOption("signMetadataWithKey", true, "Signs the metadata with the specified key");
    options.addOption("dlqName", true, "The name of the dead letter queue");
    options.addOption("upgradeFrom106", false, "Updates workflows from 1.0.6");
    options.addOption("secretkey", true, "base64 encoded secret key");
    options.addOption("envFile", true, "Environment variables for parmaterized configs");

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args, true);

    if (args.length == 0 || cmd.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("OpenUnisonUtils", options);
    }/*from   w ww  . j av a 2 s . com*/

    logger.info("Loading Unison Configuration");
    String unisonXMLFile = loadOption(cmd, "unisonXMLFile", options);
    TremoloType ttRead = loadTremoloType(unisonXMLFile, cmd, options);

    String action = loadOption(cmd, "action", options);
    TremoloType ttWrite = null;
    if (action.equalsIgnoreCase("import-sp-metadata") || action.equalsIgnoreCase("import-idp-metadata")) {
        ttWrite = loadTremoloType(unisonXMLFile);
    }

    logger.info("Configuration loaded");

    logger.info("Loading the keystore...");
    String ksPath = loadOption(cmd, "keystorePath", options);

    KeyStore ks = loadKeyStore(ksPath, ttRead);

    logger.info("...loaded");

    if (action.equalsIgnoreCase("import-sp-metadata")) {

        importMetaData(options, cmd, unisonXMLFile, ttRead, ttWrite, ksPath, ks);
    } else if (action.equalsIgnoreCase("export-sp-metadata")) {
        exportSPMetaData(options, cmd, ttRead, ks);

    } else if (action.equalsIgnoreCase("print-secretkey")) {
        printSecreyKey(options, cmd, ttRead, ks);
    } else if (action.equalsIgnoreCase("import-secretkey")) {
        importSecreyKey(options, cmd, ttRead, ks, ksPath);
    } else if (action.equalsIgnoreCase("create-secretkey")) {
        Security.addProvider(new BouncyCastleProvider());
        logger.info("Creating AES-256 secret key");
        String alias = loadOption(cmd, "alias", options);
        logger.info("Alias : '" + alias + "'");
        KeyGenerator kg = KeyGenerator.getInstance("AES", "BC");
        kg.init(256, new SecureRandom());
        SecretKey sk = kg.generateKey();
        ks.setKeyEntry(alias, sk, ttRead.getKeyStorePassword().toCharArray(), null);
        logger.info("Saving key");
        ks.store(new FileOutputStream(ksPath), ttRead.getKeyStorePassword().toCharArray());
        logger.info("Finished");
    } else if (action.equalsIgnoreCase("export-secretkey")) {
        logger.info("Export Secret Key");

        logger.info("Loading key");
        String alias = loadOption(cmd, "alias", options);
        SecretKey key = (SecretKey) ks.getKey(alias, ttRead.getKeyStorePassword().toCharArray());
        logger.info("Loading new keystore path");
        String pathToNewKeystore = loadOption(cmd, "newKeystorePath", options);
        logger.info("Loading new keystore password");
        String ksPassword = loadOption(cmd, "newKeystorePassword", options);

        KeyStore newKS = KeyStore.getInstance("PKCS12");
        newKS.load(null, ttRead.getKeyStorePassword().toCharArray());
        newKS.setKeyEntry(alias, key, ksPassword.toCharArray(), null);
        newKS.store(new FileOutputStream(pathToNewKeystore), ksPassword.toCharArray());
        logger.info("Exported");
    } else if (action.equalsIgnoreCase("import-idp-metadata")) {
        importIdpMetadata(options, cmd, unisonXMLFile, ttRead, ttWrite, ksPath, ks);

    } else if (action.equalsIgnoreCase("export-idp-metadata")) {
        exportIdPMetadata(options, cmd, ttRead, ks);
    } else if (action.equalsIgnoreCase("clear-dlq")) {
        logger.info("Getting the DLQ Name...");
        String dlqName = loadOption(cmd, "dlqName", options);
        QueUtils.emptyDLQ(ttRead, dlqName);
    } else if (action.equalsIgnoreCase("upgradeFrom106")) {
        logger.info("Upgrading OpenUnison's configuration from 1.0.6");

        String backupFileName = unisonXMLFile + ".bak";

        logger.info("Backing up to '" + backupFileName + "'");

        BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(unisonXMLFile)));
        PrintWriter out = new PrintWriter(new FileOutputStream(backupFileName));
        String line = null;
        while ((line = in.readLine()) != null) {
            out.println(line);
        }
        out.flush();
        out.close();
        in.close();

        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        AddChoiceToTasks.convert(new FileInputStream(unisonXMLFile), bout);
        FileOutputStream fsout = new FileOutputStream(unisonXMLFile);
        fsout.write(bout.toByteArray());
        fsout.flush();
        fsout.close();

    }

}

From source file:Main.java

/**
 * Check if the file provide is PKCS12/*from   ww  w. j a  va2  s. c  o m*/
 * @param cert certificate to be validated
 * @param pass password to be provided
 * @throws Exception to indicate an invalid certificate
 */
public static void validate(byte[] cert, String pass) throws Exception {

    try {
        KeyStore keyStore = KeyStore.getInstance(ALGORITHM);
        keyStore.load(new ByteArrayInputStream(cert), pass.toCharArray());
    } catch (Exception e) {
        throw new Exception("Certificate is not valid!", e);
    }
}

From source file:Main.java

/**
 * Creates an SSLSocketFactory which contains {@code certChainFile} as its only root certificate.
 *//*from  w ww.jav  a2 s  . co  m*/
public static SSLSocketFactory newSslSocketFactoryForCa(InputStream certChain) throws Exception {
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(null, null);
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509Certificate cert = (X509Certificate) cf.generateCertificate(new BufferedInputStream(certChain));
    X500Principal principal = cert.getSubjectX500Principal();
    ks.setCertificateEntry(principal.getName("RFC2253"), cert);
    //    ks.setCertificateEntry("ca", cert);

    // Set up trust manager factory to use our key store.
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(ks);
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, trustManagerFactory.getTrustManagers(), null);
    return context.getSocketFactory();
}

From source file:com.cloudseal.spring.client.namespace.CloudSealKeyManagerImpl.java

protected static KeyStore createKeyStore(Resource storeFile, String storePass, String storeType) {
    InputStream inputStream = null;
    try {//  w ww.ja  va  2s.  c o m
        inputStream = storeFile.getInputStream();
        KeyStore ks = KeyStore.getInstance(storeType);
        ks.load(inputStream, storePass.toCharArray());
        return ks;
    } catch (Exception e) {
        throw new RuntimeException("Error initializing keystore", e);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:Main.java

private static KeyManager[] prepareKeyManager(InputStream bksFile, String password) {
    try {/*  w w  w.j av  a 2 s  .c o  m*/
        if (bksFile != null && password != null) {
            KeyStore e = KeyStore.getInstance("BKS");
            e.load(bksFile, password.toCharArray());
            KeyManagerFactory keyManagerFactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(e, password.toCharArray());
            return keyManagerFactory.getKeyManagers();
        }

        return null;
    } catch (KeyStoreException var4) {
        var4.printStackTrace();
    } catch (NoSuchAlgorithmException var5) {
        var5.printStackTrace();
    } catch (UnrecoverableKeyException var6) {
        var6.printStackTrace();
    } catch (CertificateException var7) {
        var7.printStackTrace();
    } catch (IOException var8) {
        var8.printStackTrace();
    } catch (Exception var9) {
        var9.printStackTrace();
    }

    return null;
}

From source file:Main.java

private static KeyStore newEmptyKeyStore(char[] password) {
    try {/*from   ww w.  ja v a 2  s.c om*/
        KeyStore e = KeyStore.getInstance(KeyStore.getDefaultType());
        Object in = null;
        e.load((InputStream) in, password);
        return e;
    } catch (Exception var3) {
        var3.printStackTrace();
    }
    return null;
}

From source file:Main.java

private static KeyManager[] prepareKeyManager(InputStream bksFile, String password) {
    try {/* w ww.jav  a 2 s .  c o  m*/
        if (bksFile == null || password == null)
            return null;

        KeyStore clientKeyStore = KeyStore.getInstance("BKS");
        clientKeyStore.load(bksFile, password.toCharArray());
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(clientKeyStore, password.toCharArray());
        return keyManagerFactory.getKeyManagers();

    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.dealoka.lib.net.HttpUtils.java

public static HttpClient getNewHttpClient() {
    try {//ww  w.jav  a2s  .  c om
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new EasySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}