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 KeyStore getInstance(String type) throws KeyStoreException 

Source Link

Document

Returns a keystore object of the specified type.

Usage

From source file:Main.java

/**
 * Initializes the keystore and creates the key if necessary
 *
 * @return true, if a new key has been generated
 * @throws GeneralSecurityException/*ww w.j  a  va 2s.c  o  m*/
 * @throws IOException
 */
static boolean init() throws GeneralSecurityException, IOException {
    mKeyStore = KeyStore.getInstance("AndroidKeyStore");
    mKeyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
    if (!hasKey()) {
        createKey();
        return true;
    } else {
        return false;
    }
}

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

public static KeyStore coverString2KeyStore(String base64PKS, String password) throws CertException {

    byte[] keyStoreByte = Base64.decodeBase64(base64PKS);
    InputStream istream = StreamUtil.bytes2Stream(keyStoreByte);
    try {//from   w ww.j  ava  2  s  .c  om
        KeyStore keyStore = KeyStore.getInstance(PKCS12_STORE_TYPE);
        keyStore.load(istream, password.toCharArray());
        istream.close();
        return keyStore;
    } catch (KeyStoreException e) {
        throw new CertException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new CertException(e);
    } catch (CertificateException e) {
        throw new CertException(e);
    } catch (IOException e) {
        throw new CertException(e);
    }
}

From source file:com.nesscomputing.tinyhttp.ssl.HttpsTrustManagerFactory.java

@Nonnull
private static KeyStore loadKeystore(@Nonnull String location, @Nonnull String keystoreType,
        @Nonnull String keystorePassword) throws GeneralSecurityException, IOException {
    final KeyStore keystore = KeyStore.getInstance(keystoreType);
    URL keystoreUrl;//from w  w w  .  j a  va  2 s  .  c o  m
    if (StringUtils.startsWithIgnoreCase(location, "classpath:")) {
        keystoreUrl = Resources.getResource(HttpsTrustManagerFactory.class, location.substring(10));
    } else {
        keystoreUrl = new URL(location);
    }
    keystore.load(keystoreUrl.openStream(), keystorePassword.toCharArray());
    return keystore;
}

From source file:org.everit.osgi.authentication.cas.tests.SecureHttpClient.java

public SecureHttpClient(final String principal, final BundleContext bundleContext) throws Exception {
    this.principal = principal;

    httpClientContext = HttpClientContext.create();
    httpClientContext.setCookieStore(new BasicCookieStore());

    KeyStore trustStore = KeyStore.getInstance("jks");
    trustStore.load(bundleContext.getBundle().getResource("/jetty-keystore").openStream(),
            "changeit".toCharArray());

    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(trustStore);
    TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, trustManagers, new SecureRandom());

    httpClient = HttpClientBuilder.create().setSslcontext(sslContext)
            .setRedirectStrategy(new DefaultRedirectStrategy()).build();
}

From source file:SigningProcess.java

public static HashMap returnCertificates() {
    HashMap map = new HashMap();
    try {/*ww  w  . j  a  v a 2s .c  om*/
        providerMSCAPI = new SunMSCAPI();
        Security.addProvider(providerMSCAPI);
        ks = KeyStore.getInstance("Windows-MY");
        ks.load(null, null);
        Field spiField = KeyStore.class.getDeclaredField("keyStoreSpi");
        spiField.setAccessible(true);
        KeyStoreSpi spi = (KeyStoreSpi) spiField.get(ks);
        Field entriesField = spi.getClass().getSuperclass().getDeclaredField("entries");
        entriesField.setAccessible(true);
        Collection entries = (Collection) entriesField.get(spi);
        for (Object entry : entries) {
            alias = (String) invokeGetter(entry, "getAlias");
            //                System.out.println("alias :" + alias);
            privateKey = (Key) invokeGetter(entry, "getPrivateKey");
            certificateChain = (X509Certificate[]) invokeGetter(entry, "getCertificateChain");
            //                System.out.println(alias + ": " + privateKey + "CERTIFICATES -----------"+Arrays.toString(certificateChain));
        }
        map.put("privateKey", privateKey);
        map.put("certificateChain", certificateChain);

    } catch (KeyStoreException ex) {
        System.out.println("Exception :" + ex.getLocalizedMessage());
    } catch (IOException ex) {
        System.out.println("Exception :" + ex.getLocalizedMessage());
    } catch (NoSuchAlgorithmException ex) {
        System.out.println("Exception :" + ex.getLocalizedMessage());
    } catch (CertificateException ex) {
        System.out.println("Exception :" + ex.getLocalizedMessage());
    } catch (NoSuchFieldException ex) {
        System.out.println("Exception :" + ex.getLocalizedMessage());
    } catch (SecurityException ex) {
        System.out.println("Exception :" + ex.getLocalizedMessage());
    } catch (IllegalArgumentException ex) {
        System.out.println("Exception :" + ex.getLocalizedMessage());
    } catch (IllegalAccessException ex) {
        System.out.println("Exception :" + ex.getLocalizedMessage());
    } catch (NoSuchMethodException ex) {
        System.out.println("Exception :" + ex.getLocalizedMessage());
    } catch (InvocationTargetException ex) {
        System.out.println("Exception :" + ex.getLocalizedMessage());
    }
    return map;
}

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 ww w  . j a  va 2  s  .  c o  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.nesscomputing.httpclient.internal.HttpClientTrustManagerFactory.java

@Nonnull
private static KeyStore loadKeystore(@Nonnull String location, @Nonnull String keystoreType,
        @Nonnull String keystorePassword) throws GeneralSecurityException, IOException {
    final KeyStore keystore = KeyStore.getInstance(keystoreType);
    URL keystoreUrl;/*from  ww  w . j a v  a 2 s . com*/
    if (StringUtils.startsWithIgnoreCase(location, "classpath:")) {
        keystoreUrl = Resources.getResource(HttpClientTrustManagerFactory.class, location.substring(10));
    } else {
        keystoreUrl = new URL(location);
    }
    keystore.load(keystoreUrl.openStream(), keystorePassword.toCharArray());
    return keystore;
}

From source file:be.fedict.commons.eid.jca.BeIDX509KeyManager.java

public BeIDX509KeyManager(final BeIDManagerFactoryParameters beIDSpec)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
    LOG.debug("constructor");
    this.keyStore = KeyStore.getInstance("BeID");
    BeIDKeyStoreParameter beIDKeyStoreParameter;
    if (null == beIDSpec) {
        beIDKeyStoreParameter = null;//w w w .j a  v a  2 s  .co  m
    } else {
        beIDKeyStoreParameter = new BeIDKeyStoreParameter();
        beIDKeyStoreParameter.setLocale(beIDSpec.getLocale());
        beIDKeyStoreParameter.setParentComponent(beIDSpec.getParentComponent());
        beIDKeyStoreParameter.setAutoRecovery(beIDSpec.getAutoRecovery());
        beIDKeyStoreParameter.setCardReaderStickiness(beIDSpec.getCardReaderStickiness());
    }
    this.keyStore.load(beIDKeyStoreParameter);
}

From source file:org.zywx.wbpalmstar.platform.certificates.Http.java

public static HNetSSLSocketFactory getSSLSocketFactoryWithCert(String cPassWord, String cPath, Context ctx) {
    InputStream inStream = null;//from   w w w.  j av a  2  s  .co  m
    HNetSSLSocketFactory ssSocketFactory = null;
    try {
        int index = cPath.lastIndexOf('/');
        String keyName = cPath.substring(index);
        KeyStore ksP12 = KEY_STORE.get(keyName);
        if (null == ksP12) {
            inStream = getInputStream(cPath, ctx);
            ksP12 = KeyStore.getInstance("pkcs12");
            ksP12.load(inStream, cPassWord.toCharArray());
            KEY_STORE.put(keyName, ksP12);
        }
        ssSocketFactory = new HNetSSLSocketFactory(ksP12, cPassWord);
    } catch (Exception e) {
        e.printStackTrace();
        ssSocketFactory = getSSLSocketFactory();
    }
    return ssSocketFactory;
}

From source file:com.cloudera.nav.sdk.client.SSLUtilsTest.java

@Before
public void setUp() throws Exception {
    Map<String, Object> confMap = Maps.newHashMap();
    confMap.put(ClientConfigFactory.APP_URL, "localhost");
    confMap.put(ClientConfigFactory.NAV_URL, "localhost");
    confMap.put(ClientConfigFactory.NAMESPACE, "test");
    confMap.put(ClientConfigFactory.USERNAME, "user");
    confMap.put(ClientConfigFactory.PASSWORD, "pass");
    confMap.put(ClientConfigFactory.API_VERSION, 9);
    config = (new ClientConfigFactory()).fromConfigMap(confMap);

    KeyStore keyStore = KeyStore.getInstance("jks");
    ClassLoader classLoader = getClass().getClassLoader();
    String keyStoreLocation = classLoader.getResource("client.jks").getFile();
    try (InputStream is = new FileInputStream(keyStoreLocation)) {
        keyStore.load(is, "clientP".toCharArray());
    }/*w  ww. j a va  2  s  .com*/
    certs = Maps.newHashMap();
    Enumeration<String> aliasesEn = keyStore.aliases();
    String alias;
    while (aliasesEn.hasMoreElements()) {
        alias = aliasesEn.nextElement();
        certs.put(alias, keyStore.getCertificate(alias));
    }
}