Java Code Examples for java.security.KeyStore.load()

The following are Jave code examples for showing how to use load() of the java.security.KeyStore class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: iot-edge-greengrass   File: ConfigurationTools.java   View Source Code Vote up 6 votes
public static CertificateInfo loadCertificate(KeystoreConfiguration configuration)
    throws GeneralSecurityException, IOException {
  try {
    KeyStore keyStore = KeyStore.getInstance(configuration.getType());
    keyStore.load(getResourceAsStream(configuration.getLocation()), configuration.getPassword().toCharArray());

    Key key = keyStore.getKey(configuration.getAlias(), configuration.getKeyPassword().toCharArray());
    if (key instanceof PrivateKey) {
      X509Certificate certificate = (X509Certificate) keyStore.getCertificate(configuration.getAlias());
      PublicKey publicKey = certificate.getPublicKey();
      KeyPair keyPair = new KeyPair(publicKey, (PrivateKey) key);
      return new CertificateInfo(certificate, keyPair);
    } else {
      throw new GeneralSecurityException(configuration.getAlias() + " is not a private key!");
    }
  } catch (IOException | GeneralSecurityException e) {
    log.error("Keystore configuration: [{}] is invalid!", configuration, e);
    throw e;
  }
}
 
Example 2
Project: RoughWorld   File: WebInterfaceSSL.java   View Source Code Vote up 6 votes
/**
     * Creates an SSLSocketFactory for HTTPS. Pass a KeyStore resource with your
     * certificate and passphrase
     */
    public static SSLServerSocketFactory makeSSLSocketFactory(String keyAndTrustStoreClasspathPath, char[] passphrase)
    {
        try {
            KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
            File keystrorefile = new File(keyAndTrustStoreClasspathPath);
            System.out.println(keystrorefile.getAbsolutePath());
            InputStream keystoreStream = new FileInputStream(keystrorefile);//NanoHTTPD.class.getResourceAsStream(keyAndTrustStoreClasspathPath);

//            if (keystoreStream == null) 
//            {
//            	System.out.println("Unable to load keystore from classpath: " + keyAndTrustStoreClasspathPath);
//                //throw new IOException("Unable to load keystore from classpath: " + keyAndTrustStoreClasspathPath);
//            	return null;
//            }

            keystore.load(keystoreStream, passphrase);
            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(keystore, passphrase);
            return makeSSLSocketFactory(keystore, keyManagerFactory);
        } catch (Exception e) {
        	System.out.println(e.toString());
            //throw new IOException(e.getMessage());
        }
        return null;
    }
 
Example 3
Project: flume-release-1.7.0   File: ThriftRpcClient.java   View Source Code Vote up 6 votes
/**
 * Lifted from ACCUMULO-3318 - Lifted from TSSLTransportFactory in Thrift-0.9.1.
 * The method to create a client socket with an SSLContextFactory object is not visible to us.
 * Have to use * SslConnectionParams instead of TSSLTransportParameters because no getters exist
 * on TSSLTransportParameters.
 */
private static SSLContext createSSLContext(String truststore,
                                           String truststorePassword,
                                           String truststoreType) throws FlumeException {
  SSLContext ctx;
  try {
    ctx = SSLContext.getInstance("TLS");
    TrustManagerFactory tmf;
    tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    KeyStore ts = null;
    if (truststore != null && truststoreType != null) {
      ts = KeyStore.getInstance(truststoreType);
      ts.load(new FileInputStream(truststore), truststorePassword.toCharArray());
      tmf.init(ts);
    }

    tmf.init(ts);
    ctx.init(null, tmf.getTrustManagers(), null);

  } catch (Exception e) {
    throw new FlumeException("Error creating the transport", e);
  }
  return ctx;
}
 
Example 4
Project: hands-on-api-proxy   File: App.java   View Source Code Vote up 6 votes
public SSLContextPinner(String pemAssetName) {
    try {
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, null);
        InputStream certInputStream = getAssets().open(pemAssetName);
        BufferedInputStream bis = new BufferedInputStream(certInputStream);
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        int idx = -1;
        while (bis.available() > 0) {
            Certificate cert = certificateFactory.generateCertificate(bis);
            keyStore.setCertificateEntry("" + ++idx, cert);
            Log.i("App", "pinned " + idx + ": " + ((X509Certificate) cert).getSubjectDN());
        }
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
        trustManager = trustManagers[0];
        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustManagers, null);
    } catch(Exception e) {
        sslContext = null;
        trustManager = null;
        Log.e("App", e.toString());
    }
}
 
Example 5
Project: MQTT-Essentials-A-Lightweight-IoT-Protocol   File: SecurityHelper.java   View Source Code Vote up 6 votes
private static TrustManagerFactory createTrustManagerFactory(
	final String caCertificateFileName) 
	throws CertificateException, NoSuchAlgorithmException, IOException, KeyStoreException 
{
	// Creates a trust manager factory
	// Load CA certificate
	final X509Certificate caCertificate = (X509Certificate) createX509CertificateFromFile(caCertificateFileName);
	// CA certificate is used to authenticate server
	final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); 
	keyStore.load(null, null);
	keyStore.setCertificateEntry("ca-certificate", caCertificate);
	final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
	trustManagerFactory.init(keyStore);

	return trustManagerFactory;
}
 
Example 6
Project: iotplatform   File: MqttSslHandlerProvider.java   View Source Code Vote up 5 votes
public SslHandler getSslHandler() {
    try {
        URL ksUrl = Resources.getResource(keyStoreFile);
        File ksFile = new File(ksUrl.toURI());
        URL tsUrl = Resources.getResource(keyStoreFile);
        File tsFile = new File(tsUrl.toURI());

        TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        KeyStore trustStore = KeyStore.getInstance(keyStoreType);
        trustStore.load(new FileInputStream(tsFile), keyStorePassword.toCharArray());
        tmFactory.init(trustStore);

        KeyStore ks = KeyStore.getInstance(keyStoreType);

        ks.load(new FileInputStream(ksFile), keyStorePassword.toCharArray());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ks, keyPassword.toCharArray());

        KeyManager[] km = kmf.getKeyManagers();
        TrustManager x509wrapped = getX509TrustManager(tmFactory);
        TrustManager[] tm = {x509wrapped};
        SSLContext sslContext = SSLContext.getInstance(TLS);
        sslContext.init(km, tm, null);
        SSLEngine sslEngine = sslContext.createSSLEngine();
        sslEngine.setUseClientMode(false);
        sslEngine.setNeedClientAuth(false);
        sslEngine.setWantClientAuth(true);
        sslEngine.setEnabledProtocols(sslEngine.getSupportedProtocols());
        sslEngine.setEnabledCipherSuites(sslEngine.getSupportedCipherSuites());
        sslEngine.setEnableSessionCreation(true);
        return new SslHandler(sslEngine);
    } catch (Exception e) {
        log.error("Unable to set up SSL context. Reason: " + e.getMessage(), e);
        throw new RuntimeException("Failed to get SSL handler", e);
    }
}
 
Example 7
Project: android-util2   File: HttpsHelper.java   View Source Code Vote up 5 votes
/**
     * create ssl socket factory. by target crt file.
     * @param context the context.
     * @param assetsFilePath the crt file path in assets.
     * @return an instance of SSLSocketFactory.
     */
    public static SSLSocketFactory createSSLSocketFactory(Context context, String assetsFilePath) {
        SSLContext sslContext = null;
        try {
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            InputStream certificates = new BufferedInputStream(context.getAssets().open(assetsFilePath));
            Certificate ca;
            try {
                ca = certificateFactory.generateCertificate(certificates);
                System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN());
            } finally {
                certificates.close();
            }

            // Create a KeyStore containing our trusted CAs
            String keyStoreType = KeyStore.getDefaultType();
            KeyStore keyStore = KeyStore.getInstance(keyStoreType);
            keyStore.load(null, null);
            keyStore.setCertificateEntry("ca", ca);

            // Create a TrustManager that trusts the CAs in our KeyStore
            String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
            tmf.init(keyStore);

            // Create an SSLContext that uses our TrustManager
            sslContext = SSLContext.getInstance("TLSv1", "AndroidOpenSSL");
//            sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, tmf.getTrustManagers(), null);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return sslContext != null ? sslContext.getSocketFactory() : null;
    }
 
Example 8
Project: sealtalk-android-master   File: MySSLSocketFactory.java   View Source Code Vote up 5 votes
public static KeyStore getKeystore() {
    KeyStore trustStore = null;
    try {
        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
    } catch (Throwable t) {
        t.printStackTrace();
    }
    return trustStore;
}
 
Example 9
Project: JAVA-   File: HTTPSPKCSCoder.java   View Source Code Vote up 5 votes
/**
 * 获得KeyStore
 * 
 * @param keyStorePath 密钥库路径
 * @param password 密码
 * @return KeyStore 密钥库
 * @throws Exception
 */
private static KeyStore getKeyStore(String keyStorePath, String password) throws Exception {
	// 实例化密钥库
	KeyStore ks = KeyStore.getInstance("PKCS12");
	// KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
	// 获得密钥库文件流
	FileInputStream is = new FileInputStream(keyStorePath);
	// 加载密钥库
	ks.load(is, password.toCharArray());
	// 关闭密钥库文件流
	is.close();
	return ks;
}
 
Example 10
Project: iBase4J-Common   File: HTTPSPKCSCoder.java   View Source Code Vote up 5 votes
/**
 * 获得KeyStore
 * 
 * @param keyStorePath 密钥库路径
 * @param password 密码
 * @return KeyStore 密钥库
 * @throws Exception
 */
private static KeyStore getKeyStore(String keyStorePath, String password) throws Exception {
	// 实例化密钥库
	KeyStore ks = KeyStore.getInstance("PKCS12");
	// KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
	// 获得密钥库文件流
	FileInputStream is = new FileInputStream(keyStorePath);
	// 加载密钥库
	ks.load(is, password.toCharArray());
	// 关闭密钥库文件流
	is.close();
	return ks;
}
 
Example 11
Project: openjdk-jdk10   File: CipherTestUtils.java   View Source Code Vote up 5 votes
private static KeyStore createServerKeyStore(String publicKey,
        String keySpecStr) throws KeyStoreException, IOException,
        NoSuchAlgorithmException, CertificateException,
        InvalidKeySpecException {

    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);
    if (publicKey == null || keySpecStr == null) {
        throw new IllegalArgumentException("publicKey or "
                + "keySpecStr cannot be null");
    }
    String strippedPrivateKey = keySpecStr.substring(
            keySpecStr.indexOf("\n"), keySpecStr.lastIndexOf("\n"));

    // generate the private key.
    PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec(
            Base64.getMimeDecoder().decode(strippedPrivateKey));
    KeyFactory kf = KeyFactory.getInstance("RSA");
    RSAPrivateKey priKey
            = (RSAPrivateKey) kf.generatePrivate(priKeySpec);

    // generate certificate chain
    try (InputStream is = new ByteArrayInputStream(publicKey.getBytes())) {
        // generate certificate from cert string
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        Certificate keyCert = cf.generateCertificate(is);
        Certificate[] chain = {keyCert};
        ks.setKeyEntry("TestEntry", priKey, PASSWORD, chain);
    }

    return ks;
}
 
Example 12
Project: rebase-android   File: BlackBox.java   View Source Code Vote up 5 votes
/**
 * Decrypt the encrypted secret.
 *
 * @param encrypted the encrypted secret.
 * @return the decrypted secret.
 * @throws Exception
 */
public String decrypt(String encrypted) throws Exception {
    byte[] encryptedBytes = Base64.decode(encrypted, Base64.DEFAULT);
    KeyStore keyStore = KeyStore.getInstance(ANDROID_KEY_STORE);
    keyStore.load(null);
    KeyStore.PrivateKeyEntry privateKeyEntry =
        (KeyStore.PrivateKeyEntry) keyStore.getEntry(alias, null);
    Cipher output = Cipher.getInstance(RSA_ALGORITHM);
    output.init(Cipher.DECRYPT_MODE, privateKeyEntry.getPrivateKey());
    CipherInputStream cipherInputStream = new CipherInputStream(
        new ByteArrayInputStream(encryptedBytes), output);
    ArrayList<Byte> values = new ArrayList<>();
    int nextByte;
    while ((nextByte = cipherInputStream.read()) != -1) {
        values.add((byte) nextByte);
    }

    byte[] bytes = new byte[values.size()];
    for (int i = 0; i < bytes.length; i++) {
        bytes[i] = values.get(i);
    }
    return new String(bytes);
}
 
Example 13
Project: openjdk-jdk10   File: CertReplace.java   View Source Code Vote up 5 votes
/**
 * @param args {cacerts keystore, cert chain}
 */
public static void main(String[] args) throws Exception {

    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(new FileInputStream(args[0]), "changeit".toCharArray());
    Validator v = Validator.getInstance
        (Validator.TYPE_PKIX, Validator.VAR_GENERIC, ks);
    X509Certificate[] chain = createPath(args[1]);
    System.out.println("Chain: ");
    for (X509Certificate c: v.validate(chain)) {
        System.out.println("   " + c.getSubjectX500Principal() +
                " issued by " + c.getIssuerX500Principal());
    }
}
 
Example 14
Project: GitHub   File: MySSLSocketFactory.java   View Source Code Vote up 5 votes
/**
 * Gets a Default KeyStore
 *
 * @return KeyStore
 */
public static KeyStore getKeystore() {
    KeyStore trustStore = null;
    try {
        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
    } catch (Throwable t) {
        t.printStackTrace();
    }
    return trustStore;
}
 
Example 15
Project: openjdk-jdk10   File: KeyToolTest.java   View Source Code Vote up 5 votes
/**
 * Helper method, load a keystore
 * @param file file for keystore, null or "NONE" for PKCS11
 * @pass password for the keystore
 * @type keystore type
 * @returns the KeyStore object
 * @exception Exception if anything goes wrong
 */
KeyStore loadStore(String file, String pass, String type) throws Exception {
    KeyStore ks = KeyStore.getInstance(type);
    FileInputStream is = null;
    if (file != null && !file.equals("NONE")) {
        is = new FileInputStream(file);
    }
    ks.load(is, pass.toCharArray());
    is.close();
    return ks;
}
 
Example 16
Project: azeroth   File: RSA.java   View Source Code Vote up 5 votes
/**
 * 从KeyStore获取私钥
 * @param location
 * @param alias
 * @param storeType
 * @param storePass
 * @param keyPass
 * @return
 */
public static PrivateKey loadPrivateKeyFromKeyStore(String location, String alias, String storeType, String storePass, String keyPass) {
    try {
        storeType = null == storeType ? KeyStore.getDefaultType() : storeType;
        keyPass = keyPass == null ? storePass : keyPass;
        KeyStore keyStore = KeyStore.getInstance(storeType);
        InputStream is = new FileInputStream(location);
        keyStore.load(is, storePass.toCharArray());
        // 由密钥库获取密钥的两种方式
        return (PrivateKey) keyStore.getKey(alias, keyPass.toCharArray());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 17
Project: openjdk-jdk10   File: SelfIssuedCert.java   View Source Code Vote up 4 votes
private static SSLContext getSSLContext(String trusedCertStr,
        String keyCertStr, String keySpecStr) throws Exception {

    // generate certificate from cert string
    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    // create a key store
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);

    // import the trused cert
    Certificate trusedCert = null;
    ByteArrayInputStream is = null;
    if (trusedCertStr != null) {
        is = new ByteArrayInputStream(trusedCertStr.getBytes());
        trusedCert = cf.generateCertificate(is);
        is.close();

        ks.setCertificateEntry("RSA Export Signer", trusedCert);
    }

    if (keyCertStr != null) {
        // generate the private key.
        PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec(
                            Base64.getMimeDecoder().decode(keySpecStr));
        KeyFactory kf = KeyFactory.getInstance("RSA");
        RSAPrivateKey priKey =
                (RSAPrivateKey)kf.generatePrivate(priKeySpec);

        // generate certificate chain
        is = new ByteArrayInputStream(keyCertStr.getBytes());
        Certificate keyCert = cf.generateCertificate(is);
        is.close();

        Certificate[] chain = null;
        if (trusedCert != null) {
            chain = new Certificate[2];
            chain[0] = keyCert;
            chain[1] = trusedCert;
        } else {
            chain = new Certificate[1];
            chain[0] = keyCert;
        }

        // import the key entry.
        ks.setKeyEntry("Whatever", priKey, passphrase, chain);
    }

    // create SSL context
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmAlgorithm);
    tmf.init(ks);

    SSLContext ctx = SSLContext.getInstance("TLS");
    if (keyCertStr != null && !keyCertStr.isEmpty()) {
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("NewSunX509");
        kmf.init(ks, passphrase);

        ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
        ks = null;
    } else {
        ctx.init(null, tmf.getTrustManagers(), null);
    }

    return ctx;
}
 
Example 18
Project: java-buildpack-security-provider   File: CloudFoundryContainerKeyManagerFactoryTest.java   View Source Code Vote up 4 votes
private KeyStore getKeyStore() throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException {
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(null);
    return keyStore;
}
 
Example 19
Project: openjdk-jdk10   File: ConnectorBootstrap.java   View Source Code Vote up 4 votes
private static SslRMIServerSocketFactory createSslRMIServerSocketFactory(
        String sslConfigFileName,
        String[] enabledCipherSuites,
        String[] enabledProtocols,
        boolean sslNeedClientAuth,
        String bindAddress) {
    if (sslConfigFileName == null) {
        return new HostAwareSslSocketFactory(
                enabledCipherSuites,
                enabledProtocols,
                sslNeedClientAuth, bindAddress);
    } else {
        checkRestrictedFile(sslConfigFileName);
        try {
            // Load the SSL keystore properties from the config file
            Properties p = new Properties();
            try (InputStream in = new FileInputStream(sslConfigFileName)) {
                BufferedInputStream bin = new BufferedInputStream(in);
                p.load(bin);
            }
            String keyStore =
                    p.getProperty("javax.net.ssl.keyStore");
            String keyStorePassword =
                    p.getProperty("javax.net.ssl.keyStorePassword", "");
            String trustStore =
                    p.getProperty("javax.net.ssl.trustStore");
            String trustStorePassword =
                    p.getProperty("javax.net.ssl.trustStorePassword", "");

            char[] keyStorePasswd = null;
            if (keyStorePassword.length() != 0) {
                keyStorePasswd = keyStorePassword.toCharArray();
            }

            char[] trustStorePasswd = null;
            if (trustStorePassword.length() != 0) {
                trustStorePasswd = trustStorePassword.toCharArray();
            }

            KeyStore ks = null;
            if (keyStore != null) {
                ks = KeyStore.getInstance(KeyStore.getDefaultType());
                try (FileInputStream ksfis = new FileInputStream(keyStore)) {
                    ks.load(ksfis, keyStorePasswd);
                }
            }
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(
                    KeyManagerFactory.getDefaultAlgorithm());
            kmf.init(ks, keyStorePasswd);

            KeyStore ts = null;
            if (trustStore != null) {
                ts = KeyStore.getInstance(KeyStore.getDefaultType());
                try (FileInputStream tsfis = new FileInputStream(trustStore)) {
                    ts.load(tsfis, trustStorePasswd);
                }
            }
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(
                    TrustManagerFactory.getDefaultAlgorithm());
            tmf.init(ts);

            SSLContext ctx = SSLContext.getInstance("SSL");
            ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

            return new HostAwareSslSocketFactory(
                    ctx,
                    enabledCipherSuites,
                    enabledProtocols,
                    sslNeedClientAuth, bindAddress);
        } catch (Exception e) {
            throw new AgentConfigurationError(AGENT_EXCEPTION, e, e.toString());
        }
    }
}
 
Example 20
Project: openjdk-jdk10   File: TestKeyStoreEntry.java   View Source Code Vote up 4 votes
public void runTest(Provider p) throws Exception {
    try (FileOutputStream fos = new FileOutputStream("jceks");
            FileInputStream fis = new FileInputStream("jceks");) {

        KeyStore ks = KeyStore.getInstance("jceks", p);
        // create an empty key store
        ks.load(null, null);

        // store the secret keys
        String aliasHead = new String("secretKey");
        for (int j = 0; j < NUM_ALGOS; j++) {
            ks.setKeyEntry(aliasHead + j, sks[j], PASSWDK, null);
        }

        // write the key store out to a file
        ks.store(fos, PASSWDF);
        // wipe clean the existing key store
        for (int k = 0; k < NUM_ALGOS; k++) {
            ks.deleteEntry(aliasHead + k);
        }
        if (ks.size() != 0) {
            throw new RuntimeException("ERROR: re-initialization failed");
        }

        // reload the key store with the file
        ks.load(fis, PASSWDF);

        // check the integrity/validaty of the key store
        Key temp = null;
        String alias = null;
        if (ks.size() != NUM_ALGOS) {
            throw new RuntimeException("ERROR: wrong number of key"
                    + " entries");
        }

        for (int m = 0; m < ks.size(); m++) {
            alias = aliasHead + m;
            temp = ks.getKey(alias, PASSWDK);
            // compare the keys
            if (!temp.equals(sks[m])) {
                throw new RuntimeException("ERROR: key comparison (" + m
                        + ") failed");
            }
            // check the type of key
            if (ks.isCertificateEntry(alias) || !ks.isKeyEntry(alias)) {
                throw new RuntimeException("ERROR: type identification ("
                        + m + ") failed");
            }
        }
    }
}