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:net.shirayu.android.WlanLogin.MyHttpClient.java

public static KeyStore loadKeyStore(Context context) throws KeyStoreException, NoSuchAlgorithmException,
        CertificateException, FileNotFoundException, IOException, NoSuchProviderException {
    /*//from   www  .j av a  2  s .c om
     * Original implementation.
    I refer the following sites about the default keystore.
    http://wiki.livedoor.jp/syo1976/d/javassl
    http://d.hatena.ne.jp/Kazzz/20110319/p1
     */
    KeyStore certstore;
    if (Integer.valueOf(Build.VERSION.SDK) >= 14) {
        // load from unified key store
        certstore = KeyStore.getInstance("AndroidCAStore");
        certstore.load(null, null);
    } else {
        certstore = KeyStore.getInstance(KeyStore.getDefaultType());
        certstore.load(new FileInputStream(System.getProperty("javax.net.ssl.trustStore")), null); //load default keystore
    }

    //load self_signed_certificate?
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    final Boolean use_self_signed_certificate = sharedPreferences.getBoolean("use_self_signed_certificate",
            false);
    if (use_self_signed_certificate) {
        final Boolean use_folder = sharedPreferences.getBoolean("use_self_signed_certificate_folder", false);
        final String filename = sharedPreferences.getString("self_signed_certificate_path", "//");
        File myfile = new File(filename);

        if (use_folder) {
            for (File file : new File(myfile.getParent()).listFiles()) {
                if (file.isDirectory())
                    continue;
                FileInputStream stream = new FileInputStream(file);
                X509Certificate cert = MyHttpClient.readPem(stream);
                certstore.setCertificateEntry(file.getName(), cert);
            }
        } else {
            FileInputStream stream = new FileInputStream(myfile);
            X509Certificate cert = MyHttpClient.readPem(stream);
            certstore.setCertificateEntry(myfile.getName(), cert);
        }
        ;
    }
    ;

    return certstore;
}

From source file:org.wso2.carbon.identity.jwt.client.extension.util.JWTClientUtil.java

private static KeyStore loadKeyStore(final File keystoreFile, final String password, final String keyStoreType)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {
    if (null == keystoreFile) {
        throw new IllegalArgumentException("Keystore url may not be null");
    }//from   w  ww  .  j  a v  a2 s  . c  om
    URI keystoreUri = keystoreFile.toURI();
    URL keystoreUrl = keystoreUri.toURL();
    KeyStore keystore = KeyStore.getInstance(keyStoreType);
    InputStream is = null;
    try {
        is = keystoreUrl.openStream();
        keystore.load(is, null == password ? null : password.toCharArray());
    } finally {
        if (null != is) {
            is.close();
        }
    }
    return keystore;
}

From source file:it.cnr.icar.eric.client.xml.registry.util.CertificateUtil.java

@SuppressWarnings("static-access")
private static Certificate[] getCertificateSignedByRegistry(LifeCycleManager lcm, X509Certificate inCert)
        throws JAXRException {
    Certificate[] certChain = new Certificate[2];

    try {/* w  w  w .j av a2  s .  c om*/
        // Save cert in a temporary keystore file which is sent as
        // repository item to server so it can be signed
        KeyStore tmpKeystore = KeyStore.getInstance("JKS");
        tmpKeystore.load(null, bu.FREEBXML_REGISTRY_KS_PASS_REQ.toCharArray());

        tmpKeystore.setCertificateEntry(bu.FREEBXML_REGISTRY_USERCERT_ALIAS_REQ, inCert);
        File repositoryItemFile = File.createTempFile(".eric-ca-req", ".jks");
        repositoryItemFile.deleteOnExit();
        FileOutputStream fos = new java.io.FileOutputStream(repositoryItemFile);
        tmpKeystore.store(fos, bu.FREEBXML_REGISTRY_KS_PASS_REQ.toCharArray());
        fos.flush();
        fos.close();

        // Now have server sign the cert using extensionRequest
        javax.activation.DataHandler repositoryItem = new DataHandler(new FileDataSource(repositoryItemFile));
        String id = it.cnr.icar.eric.common.Utility.getInstance().createId();
        HashMap<String, Object> idToRepositoryItemsMap = new HashMap<String, Object>();
        idToRepositoryItemsMap.put(id, repositoryItem);

        HashMap<String, String> slotsMap = new HashMap<String, String>();
        slotsMap.put(BindingUtility.FREEBXML_REGISTRY_PROTOCOL_SIGNCERT, "true");

        RegistryRequestType req = bu.rsFac.createRegistryRequestType();
        bu.addSlotsToRequest(req, slotsMap);

        RegistryResponseHolder respHolder = ((LifeCycleManagerImpl) lcm).extensionRequest(req,
                idToRepositoryItemsMap);
        DataHandler responseRepositoryItem = (DataHandler) respHolder.getAttachmentsMap().get(id);

        InputStream is = responseRepositoryItem.getInputStream();
        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(is, bu.FREEBXML_REGISTRY_KS_PASS_RESP.toCharArray());
        is.close();

        certChain[0] = keyStore.getCertificate(bu.FREEBXML_REGISTRY_USERCERT_ALIAS_RESP);
        if (certChain[0] == null) {
            throw new JAXRException(JAXRResourceBundle.getInstance().getString("message.CannotFindUserCert"));
        }
        certChain[1] = keyStore.getCertificate(bu.FREEBXML_REGISTRY_CACERT_ALIAS);
        if (certChain[1] == null) {
            throw new JAXRException(JAXRResourceBundle.getInstance().getString("message.CannotFindCARootCert"));
        }
    } catch (Exception e) {
        throw new JAXRException(JAXRResourceBundle.getInstance().getString("message.CertSignFailed"), e);
    }

    return certChain;
}

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

public static X500Name getInfo(File keystore) {
    try {//from   w ww . ja  va  2s  . co  m
        KeyStore ks = KeyStore.getInstance("JKS", "SUN");
        FileInputStream stream = new FileInputStream(keystore);
        ks.load(stream, SECRET);
        IOUtils.closeQuietly(stream);
        X509CertImpl x509Cert = (X509CertImpl) ks.getCertificate(ALIAS);
        return (X500Name) x509Cert.getSubjectDN();
    } catch (Exception e) {
        return null;
    }
}

From source file:be.fedict.trust.service.KeyStoreUtils.java

public static PrivateKeyEntry loadPrivateKeyEntry(KeyStoreType type, String path, String storePassword,
        String entryPassword, String alias) throws KeyStoreLoadException {

    LOG.debug("load keystore");
    InputStream keyStoreStream = null;

    if (type.equals(KeyStoreType.PKCS11)) {
        Security.addProvider(new SunPKCS11(path));
    } else {//from w  ww . j  a v a  2s .co m
        try {
            keyStoreStream = new FileInputStream(path);
        } catch (FileNotFoundException e) {
            throw new KeyStoreLoadException("Can't load keystore from config-specified location: " + path, e);
        }
    }

    /* Find the keystore. */
    KeyStore keyStore;
    try {
        keyStore = KeyStore.getInstance(type.name());
    } catch (Exception e) {
        throw new KeyStoreLoadException("keystore instance not available: " + e.getMessage(), e);
    }

    /* Open the keystore and find the key entry. */
    try {
        keyStore.load(keyStoreStream, storePassword.toCharArray());
    } catch (Exception e) {
        throw new KeyStoreLoadException("keystore load error: " + e.getMessage(), e);
    }
    Enumeration<String> aliases;
    try {
        aliases = keyStore.aliases();
    } catch (KeyStoreException e) {
        throw new KeyStoreLoadException("could not get aliases: " + e.getMessage(), e);
    }
    if (!aliases.hasMoreElements()) {
        throw new KeyStoreLoadException("keystore is empty");
    }
    if (null == alias || alias.isEmpty()) {
        alias = aliases.nextElement();
        LOG.debug("alias: " + alias);
    }

    try {
        if (!keyStore.isKeyEntry(alias))
            throw new KeyStoreLoadException("not key entry: " + alias);
    } catch (KeyStoreException e) {
        throw new KeyStoreLoadException("key store error: " + e.getMessage(), e);
    }

    /* Get the private key entry. */
    try {
        PrivateKeyEntry privateKeyEntry = (PrivateKeyEntry) keyStore.getEntry(alias,
                new KeyStore.PasswordProtection(entryPassword.toCharArray()));
        return privateKeyEntry;
    } catch (Exception e) {
        throw new KeyStoreLoadException("error retrieving key: " + e.getMessage(), e);
    }
}

From source file:com.aqnote.shared.cryptology.cert.util.KeyStoreFileUtil.java

/**
 * ?PFX?/*  w w w.  jav  a  2s  . co m*/
 * 
 * @param alias ??
 * @param pfxPath PFX
 * @param password ?
 * @return
 * @throws KeyStoreException
 * @throws NoSuchAlgorithmException
 * @throws CertificateException
 * @throws IOException
 * @throws UnrecoverableKeyException
 */
public static PrivateKey readPrivateKey(String alias, String pfxPath, String password) throws KeyStoreException,
        NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException {

    KeyStore keyStore = KeyStore.getInstance("pkcs12");

    FileInputStream fis = null;

    fis = new FileInputStream(pfxPath);

    keyStore.load(fis, password.toCharArray());

    fis.close();

    return (PrivateKey) keyStore.getKey(alias, password.toCharArray());
}

From source file:com.github.tomakehurst.wiremock.HttpsAcceptanceTest.java

static KeyStore readKeyStore(String path, String password)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    FileInputStream instream = new FileInputStream(path);
    try {//from w w w  . j av a  2  s  . co  m
        trustStore.load(instream, password.toCharArray());
    } finally {
        instream.close();
    }
    return trustStore;
}

From source file:org.elasticsearch.test.rest.client.RestTestClient.java

private static RestClient createRestClient(URL[] urls, Settings settings) throws IOException {
    String protocol = settings.get(PROTOCOL, "http");
    HttpHost[] hosts = new HttpHost[urls.length];
    for (int i = 0; i < hosts.length; i++) {
        URL url = urls[i];/*w ww .j ava 2s .  c  o  m*/
        hosts[i] = new HttpHost(url.getHost(), url.getPort(), protocol);
    }
    RestClient.Builder builder = RestClient.builder(hosts).setMaxRetryTimeoutMillis(30000)
            .setRequestConfigCallback(requestConfigBuilder -> requestConfigBuilder.setSocketTimeout(30000));

    String keystorePath = settings.get(TRUSTSTORE_PATH);
    if (keystorePath != null) {
        final String keystorePass = settings.get(TRUSTSTORE_PASSWORD);
        if (keystorePass == null) {
            throw new IllegalStateException(TRUSTSTORE_PATH + " is provided but not " + TRUSTSTORE_PASSWORD);
        }
        Path path = PathUtils.get(keystorePath);
        if (!Files.exists(path)) {
            throw new IllegalStateException(TRUSTSTORE_PATH + " is set but points to a non-existing file");
        }
        try {
            KeyStore keyStore = KeyStore.getInstance("jks");
            try (InputStream is = Files.newInputStream(path)) {
                keyStore.load(is, keystorePass.toCharArray());
            }
            SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(keyStore, null).build();
            SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslcontext);
            builder.setHttpClientConfigCallback(
                    new SSLSocketFactoryHttpConfigCallback(sslConnectionSocketFactory));
        } catch (KeyStoreException | NoSuchAlgorithmException | KeyManagementException
                | CertificateException e) {
            throw new RuntimeException(e);
        }
    }

    try (ThreadContext threadContext = new ThreadContext(settings)) {
        Header[] defaultHeaders = new Header[threadContext.getHeaders().size()];
        int i = 0;
        for (Map.Entry<String, String> entry : threadContext.getHeaders().entrySet()) {
            defaultHeaders[i++] = new BasicHeader(entry.getKey(), entry.getValue());
        }
        builder.setDefaultHeaders(defaultHeaders);
    }
    return builder.build();
}

From source file:it.cnr.icar.eric.client.xml.registry.util.CertificateUtil.java

/**
 * Generate a self signed certificate and store it in the keystore.
 * //from  ww  w .j  av a  2s . c  o m
 * @param userRegInfo
 * @throws JAXRException
 */
public static void generateRegistryIssuedCertificate(UserRegistrationInfo userRegInfo) throws JAXRException {
    User user = userRegInfo.getUser();
    LifeCycleManager lcm = user.getLifeCycleManager();
    String dname = getDNameFromUser(userRegInfo);
    File keystoreFile = KeystoreUtil.getKeystoreFile();
    KeystoreUtil.createKeystoreDirectory(keystoreFile);
    String keystoreType = ProviderProperties.getInstance().getProperty("jaxr-ebxml.security.storetype", "JKS");
    String storePassStr = new String(userRegInfo.getStorePassword());
    String keyPassStr = new String(userRegInfo.getKeyPassword());
    String alias = userRegInfo.getAlias();
    String keyAlg = "RSA"; // XWSS does not support DSA which is default is
    // KeyTool. Hmm. Weird.

    String[] args = { "-genkey", "-keyAlg", keyAlg, "-alias", alias, "-keypass", keyPassStr, "-keystore",
            keystoreFile.getAbsolutePath(), "-storepass", storePassStr, "-storetype", keystoreType, "-dname",
            dname };

    try {
        KeyTool keytool = new KeyTool();
        keytool.run(args, System.out);

        // Now load the KeyStore and get the cert
        FileInputStream fis = new FileInputStream(keystoreFile);

        KeyStore keyStore = KeyStore.getInstance(keystoreType);
        keyStore.load(fis, storePassStr.toCharArray());
        fis.close();

        X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias);
        Certificate[] certChain = getCertificateSignedByRegistry(lcm, cert);
        Key key = keyStore.getKey(alias, userRegInfo.getKeyPassword());

        // Now overwrite original cert with signed cert
        keyStore.deleteEntry(alias);

        // keyStore.setCertificateEntry(alias, cert);
        keyStore.setKeyEntry(alias, key, userRegInfo.getKeyPassword(), certChain);
        FileOutputStream fos = new java.io.FileOutputStream(keystoreFile);
        keyStore.store(fos, storePassStr.toCharArray());
        fos.flush();
        fos.close();
    } catch (Exception e) {
        throw new JAXRException(JAXRResourceBundle.getInstance().getString("message.CertGenFailed"), e);
    }

    log.debug(JAXRResourceBundle.getInstance().getString("message.StoredUserInKeyStore",
            new Object[] { alias, keystoreFile.getAbsolutePath() }));

    try {
        // Export registry issued cert to certFile so it can be available
        // for import into a web browser for SSL access to registry
        exportRegistryIssuedCert(userRegInfo);
    } catch (Exception e) {
        String msg = JAXRResourceBundle.getInstance().getString(
                "message.UnableToExportCertificateSeeNextExceptionNoteThatThisFeatureRequiresUseOfJDK5");
        log.warn(msg, e);
        // Do not throw exception as user reg can be done despite not
        // exporting the p12 file for the web browser.
    }
}

From source file:io.kubernetes.client.util.SSLUtils.java

private static boolean loadDefaultStoreFile(KeyStore keyStore, File fileToLoad, char[] passphrase)
        throws CertificateException, NoSuchAlgorithmException, IOException {
    if (fileToLoad.exists() && fileToLoad.isFile() && fileToLoad.length() > 0) {
        keyStore.load(new FileInputStream(fileToLoad), passphrase);
        return true;
    }//from  w ww . jav a 2 s .co  m
    return false;
}