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:com.lyndir.lhunath.opal.network.SSLFactory.java

private SSLFactory(final File keyStore, final String password) {

    try (InputStream keyStoreStream = new FileInputStream(keyStore)) {
        KeyStore store = KeyStore.getInstance("JKS");
        store.load(keyStoreStream, password.toCharArray());

        TrustManagerFactory tFactory = TrustManagerFactory.getInstance("SunX509");
        tFactory.init(store);//w  ww . j a  v a2  s.c  o m

        context = SSLContext.getInstance("TLS");
        context.init(null, tFactory.getTrustManagers(), null);
    } catch (final KeyStoreException e) {
        throw new IllegalArgumentException(
                "Keystore type not supported or keystore could not be used to initialize trust.", e);
    } catch (final NoSuchAlgorithmException e) {
        throw new IllegalStateException("Key algorithm not supported.", e);
    } catch (final CertificateException e) {
        throw new IllegalArgumentException("Keystore could not be loaded.", e);
    } catch (final FileNotFoundException e) {
        throw new IllegalArgumentException("Keystore not found.", e);
    } catch (final IOException e) {
        throw new RuntimeException("Could not read the keys from the keystore.", e);
    } catch (final KeyManagementException e) {
        throw new RuntimeException("Could not use the keys for trust.", e);
    }
}

From source file:com.vmware.identity.samlservice.SamlServiceTest.java

@BeforeClass
public static void setUp() throws Exception {
    SharedUtils.bootstrap(false); // use real data
    String tenantName = ServerConfig.getTenant(0);
    String rpName = ServerConfig.getRelyingParty(tenantName, 0);
    String issuerUrl = ServerConfig.getRelyingPartyUrl(rpName);
    String acsName = ServerConfig.getAssertionConsumerService(rpName, 0);
    acsUrl = ServerConfig.getServiceEndpoint(acsName);

    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    InputStream is = new FileInputStream(SamlServiceTest.class.getResource("/sts-store.jks").getFile());
    char[] stsKeystorePassword = "ca$hc0w".toCharArray();
    ks.load(is, stsKeystorePassword);/*w  w w .j  a va 2 s. com*/

    String stsAlias = "stskey";
    Certificate certificate = ks.getCertificate(stsAlias);
    Key key = ks.getKey(stsAlias, stsKeystorePassword);

    List<X509Certificate> certificates = new ArrayList<X509Certificate>();
    certificates.add((X509Certificate) certificate);

    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
    CertPath certPath = certFactory.generateCertPath(certificates);

    privateKey = (PrivateKey) key;
    x509Certificate = (X509Certificate) certificate;

    SamlServiceFactory factory = new DefaultSamlServiceFactory();
    service = factory.createSamlService(privateKey, SignatureAlgorithm.RSA_SHA256,
            SignatureAlgorithm.RSA_SHA256, issuerUrl, certPath);
}

From source file:com.github.restdriver.clientdriver.unit.SecureClientDriverFactoryTest.java

static KeyStore getKeystore() throws Exception {
    ClassLoader loader = SecureClientDriverTest.class.getClassLoader();
    byte[] binaryContent = IOUtils.toByteArray(loader.getResourceAsStream("keystore.jks"));
    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(new ByteArrayInputStream(binaryContent), "password".toCharArray());
    return keyStore;
}

From source file:edu.rit.csh.androidwebnews.WebnewsHttpClient.java

/**
 * Makes the SSL cert work correctly.//from w  w  w. j a  va2  s. com
 *
 * @return SSLSocketFactory - provides the SSLFactory for communicating
 *         with the scheme
 */
private SSLSocketFactory newSslSocketFactory() {
    try {
        // Get an instance of the Bouncy Castle KeyStore format
        KeyStore trusted = KeyStore.getInstance(KeyStore.getDefaultType());
        trusted.load(null, null);
        // Pass the keystore to the SSLSocketFactory. The factory is responsible
        // for the verification of the server certificate.
        SSLSocketFactory sf = new WebnewsSocketFactory(trusted);
        // Hostname verification from certificate
        // http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d4e506
        sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
        return sf;
    } catch (Exception e) {
        throw new AssertionError(e);
    }
}

From source file:com.splunk.shuttl.archiver.http.InsecureHttpClientFactory.java

private static KeyStore getTrustStore() {
    try {/*from  w  w w  .jav a  2s . c o m*/
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        return trustStore;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.baasbox.android.HttpUrlConnectionClient.java

private static SSLSocketFactory createSocketFactory(Context context, int certStoreId, String certPassword) {
    TrustManagerFactory tmf;/*from  www  .ja v  a 2  s. c om*/
    InputStream in = null;
    try {
        in = context.getResources().openRawResource(certStoreId);
        KeyStore keyStore = KeyStore.getInstance("BKS");
        keyStore.load(in, certPassword.toCharArray());

        tmf = TrustManagerFactory.getInstance("X509");
        tmf.init(keyStore);

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

        return sslContext.getSocketFactory();
    } catch (Exception e) {
        throw new BaasRuntimeException(e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                // swallow
            }
        }
    }
}

From source file:net.sf.ufsc.ftp.FTPSClient.java

public FTPSClient() {
    super();/*from   w w w .j  a  v a 2 s.  com*/

    try {
        KeyStore keyStore = KeyStore.getInstance(KEY_STORE_TYPE);
        keyStore.load(null, PASSWORD.toCharArray());

        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());

        keyManagerFactory.init(keyStore, PASSWORD.toCharArray());

        SSLContext context = SSLContext.getInstance(PROTOCOL);
        context.init(keyManagerFactory.getKeyManagers(), new TrustManager[] { new SimpleTrustManager() }, null);

        this.socketFactory = new SecureSocketFactory(context);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:nl.surfnet.mujina.model.IdpConfigurationImpl.java

@Override
public void reset() {
    authMethod = AuthenticationMethod.Method.ALL;
    entityId = "http://mock-idp";
    attributes.clear();/*from w  ww .java2 s  .  com*/
    putAttribute("urn:mace:dir:attribute-def:uid", "john.doe");
    putAttribute("urn:mace:dir:attribute-def:cn", "John Doe");
    putAttribute("urn:mace:dir:attribute-def:givenName", "John");
    putAttribute("urn:mace:dir:attribute-def:sn", "Doe");
    putAttribute("urn:mace:dir:attribute-def:displayName", "John Doe");
    putAttribute("urn:mace:dir:attribute-def:mail", "j.doe@example.com");
    putAttribute("urn:mace:terena.org:attribute-def:schacHomeOrganization", "example.com");
    putAttribute("urn:mace:dir:attribute-def:eduPersonPrincipalName", "j.doe@example.com");
    putAttribute("urn:oid:1.3.6.1.4.1.1076.20.100.10.10.1", "guest");
    try {
        keyStore = KeyStore.getInstance("JKS");
        keyStore.load(null, keystorePassword.toCharArray());
        KeyStoreUtil.appendKeyToKeyStore(keyStore, "http://mock-idp",
                new ClassPathResource("idp-crt.pem").getInputStream(),
                new ClassPathResource("idp-key.pkcs8.der").getInputStream(), keystorePassword.toCharArray());
        privateKeyPasswords.put("http://mock-idp", keystorePassword);
    } catch (Exception e) {
        LOGGER.error("Unable to create default keystore", e);
    }
    users.clear();
    List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    authorities.add(new GrantedAuthorityImpl("ROLE_USER"));
    authorities.add(new GrantedAuthorityImpl("ROLE_ADMIN"));
    final SimpleAuthentication admin = new SimpleAuthentication("admin", "secret", authorities);
    users.add(admin);
    authorities = new ArrayList<GrantedAuthority>();
    authorities.add(new GrantedAuthorityImpl("ROLE_USER"));
    final SimpleAuthentication user = new SimpleAuthentication("user", "secret", authorities);
    users.add(user);
    setSigning(false);
    setAcsEndpoint(null);
}

From source file:eu.trentorise.smartcampus.ac.network.HttpsClientBuilder.java

private static HttpClient getAcceptAllHttpClient(HttpParams inParams) {
    HttpClient client = null;//from w w  w. ja  v a2  s.  c  o m

    HttpParams params = inParams != null ? inParams : new BasicHttpParams();

    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

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

        // IMPORTANT: use CustolSSLSocketFactory for 2.2
        SSLSocketFactory sslSocketFactory = new SSLSocketFactory(trustStore);
        if (android.os.Build.VERSION.SDK_INT <= android.os.Build.VERSION_CODES.FROYO) {
            sslSocketFactory = new CustomSSLSocketFactory(trustStore);
        }

        sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        registry.register(new Scheme("https", sslSocketFactory, 443));

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

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

    return client;
}

From source file:com.netscape.cmstools.pkcs11.PKCS11KeyShowCLI.java

public void execute(String[] args) throws Exception {

    CommandLine cmd = parser.parse(options, args);

    if (cmd.hasOption("help")) {
        printHelp();//w w  w . j av a2  s.  co  m
        return;
    }

    if (cmd.hasOption("verbose")) {
        PKILogger.setLevel(PKILogger.Level.INFO);

    } else if (cmd.hasOption("debug")) {
        PKILogger.setLevel(PKILogger.Level.DEBUG);
    }

    String[] cmdArgs = cmd.getArgs();

    if (cmdArgs.length < 1) {
        throw new Exception("Missing key ID.");
    }

    String alias = cmdArgs[0];

    String tokenName = getConfig().getTokenName();
    CryptoToken token = CryptoUtil.getKeyStorageToken(tokenName);

    KeyStore ks = KeyStore.getInstance("pkcs11");
    ks.load(new JSSLoadStoreParameter(token));

    Key key = ks.getKey(alias, null);

    if (key == null) {
        throw new Exception("Key not found: " + alias);
    }

    PKCS11KeyCLI.printKeyInfo(alias, key);
}