/** * Create a new key in the Keystore */ private void createNewKey(){ try { final KeyStore keyStore = KeyStore.getInstance(AndroidKeyStore); keyStore.load(null); final KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, AndroidKeyStore); // Build one key to be used for encrypting and decrypting the file keyGenerator.init( new KeyGenParameterSpec.Builder(ALIAS, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT) .setBlockModes(KeyProperties.BLOCK_MODE_GCM) .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) .build()); keyGenerator.generateKey(); Log.i(TAG, "Key created in Keystore"); }catch (KeyStoreException | InvalidAlgorithmParameterException | NoSuchProviderException | NoSuchAlgorithmException | CertificateException | IOException kS){ Log.e(TAG, kS.getMessage()); } }
private static ServerSocketFactory getServerSocketFactory (boolean useSSL) throws Exception { if (useSSL) { SSLServerSocketFactory ssf = null; // set up key manager to do server authentication SSLContext ctx; KeyManagerFactory kmf; KeyStore ks; char[] passphrase = passwd.toCharArray(); ctx = SSLContext.getInstance("TLS"); kmf = KeyManagerFactory.getInstance("SunX509"); ks = KeyStore.getInstance("JKS"); ks.load(new FileInputStream(System.getProperty( "javax.net.ssl.keyStore")), passphrase); kmf.init(ks, passphrase); ctx.init(kmf.getKeyManagers(), null, null); ssf = ctx.getServerSocketFactory(); return ssf; } else { return ServerSocketFactory.getDefault(); } }
/** * Tests the JWT we get back from the auth service is valid. We test the JWT to make sure it was * signed correctly. * * <p>We do not validate other things, like the issued at time, expired time, etc. * * <p>The test case has access to the keystore that the server should have used to sign the JWT. */ @Test public void testLoginJwtValidity() throws Exception { // Get the JWT from the auth service. Response response = processRequest(authServiceURL, "GET", null, null); assertEquals( "HTTP response code should have been " + Status.OK.getStatusCode() + ".", Status.OK.getStatusCode(), response.getStatus()); String authHeader = response.getHeaderString("Authorization"); // Open the keystore that the server should have used to sign the JWT. KeyStore ks = KeyStore.getInstance("JCEKS"); InputStream ksStream = this.getClass().getResourceAsStream("/keystore.jceks"); char[] password = new String("secret").toCharArray(); ks.load(ksStream, password); java.security.cert.Certificate cert = ks.getCertificate("default"); PublicKey publicKey = cert.getPublicKey(); // Make sure it's valid. Use the server's public key to check. new JWTVerifier().validateJWT(authHeader, publicKey); }
/** * 获得SSLSocektFactory * * @param password 密码 * @param keyStorePath 密钥库路径 * @param trustStorePath 信任库路径 * @return SSLSocketFactory * @throws Exception */ private static SSLSocketFactory getSSLSocketFactory(String password, String keyStorePath, String trustStorePath) throws Exception { // 实例化密钥库 KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); // 获得密钥库 KeyStore keyStore = getKeyStore(keyStorePath, password); // 初始化密钥工厂 keyManagerFactory.init(keyStore, password.toCharArray()); // 实例化信任库 TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); // 获得信任库 KeyStore trustStore = getKeyStore(trustStorePath, password); // 初始化信任库 trustManagerFactory.init(trustStore); // 实例化SSL上下文 SSLContext ctx = SSLContext.getInstance(PROTOCOL); // 初始化SSL上下文 ctx.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom()); // 获得SSLSocketFactory return ctx.getSocketFactory(); }
/** * Returns a standard keystore which holds the respective credentials (private key and certificate chain). * * @param keyStoreIS The input stream of the keystore * @param keyStorePassword The password which protects the keystore * @param keyStoreType The type of the keystore, either "jks" or "pkcs12" * @return The respective keystore */ private static KeyStore getKeyStore(InputStream keyStoreIS, String keyStorePassword, String keyStoreType) { KeyStore keyStore = null; try { keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(keyStoreIS, keyStorePassword.toCharArray()); keyStoreIS.close(); return keyStore; } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException | NullPointerException e) { getLogger().error(e.getClass().getSimpleName() + " occurred while trying to load keystore", e); } return null; }
public DefaultX509TrustManager init() throws IOException { try { final TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); factory.init(KeyStore.getInstance(KeyStore.getDefaultType())); final TrustManager[] trustmanagers = factory.getTrustManagers(); if(trustmanagers.length == 0) { throw new NoSuchAlgorithmException("SunX509 trust manager not supported"); } system = (javax.net.ssl.X509TrustManager) trustmanagers[0]; } catch(NoSuchAlgorithmException | KeyStoreException e) { log.error(String.format("Initialization of trust store failed. %s", e.getMessage())); throw new IOException(e); } return this; }
/** * 创建Http/Https请求对象 * @author Rocye * @param url 请求地址 * @param method 请求方式:GET/POST * @param certPath 证书路径 * @param certPass 证书密码 * @param useCert 是否需要证书 * @return Https连接 * @throws Exception 任何异常 * @version 2017.11.14 */ private HttpsURLConnection createRequest(String url, String method, String certPath, String certPass, boolean useCert) throws Exception{ URL realUrl = new URL(url); HttpsURLConnection connection = (HttpsURLConnection)realUrl.openConnection(); //设置证书 if(useCert){ KeyStore clientStore = KeyStore.getInstance("PKCS12"); InputStream inputStream = new FileInputStream(certPath); clientStore.load(inputStream, certPass.toCharArray()); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(clientStore, certPass.toCharArray()); KeyManager[] kms = kmf.getKeyManagers(); SSLContext sslContext = SSLContext.getInstance("TLSv1"); sslContext.init(kms, null, new SecureRandom()); connection.setSSLSocketFactory(sslContext.getSocketFactory()); } // 设置通用的请求属性 connection.setRequestProperty("Accept", "*/*"); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setConnectTimeout(this.connectTimeout); connection.setReadTimeout(this.readTimeout); if("POST".equals(method)){ // 发送POST请求必须设置如下两行 connection.setDoOutput(true); connection.setDoInput(true); connection.setUseCaches(false); // 忽略缓存 connection.setRequestMethod("POST"); } return connection; }
/** * Creates an instance of {@code PKIXParameters} that * populates the set of most-trusted CAs from the trusted * certificate entries contained in the specified {@code KeyStore}. * Only keystore entries that contain trusted {@code X509Certificates} * are considered; all other certificate types are ignored. * * @param keystore a {@code KeyStore} from which the set of * most-trusted CAs will be populated * @throws KeyStoreException if the keystore has not been initialized * @throws InvalidAlgorithmParameterException if the keystore does * not contain at least one trusted certificate entry * @throws NullPointerException if the keystore is {@code null} */ public PKIXParameters(KeyStore keystore) throws KeyStoreException, InvalidAlgorithmParameterException { if (keystore == null) throw new NullPointerException("the keystore parameter must be " + "non-null"); Set<TrustAnchor> hashSet = new HashSet<TrustAnchor>(); Enumeration<String> aliases = keystore.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); if (keystore.isCertificateEntry(alias)) { Certificate cert = keystore.getCertificate(alias); if (cert instanceof X509Certificate) hashSet.add(new TrustAnchor((X509Certificate)cert, null)); } } setTrustAnchors(hashSet); this.unmodInitialPolicies = Collections.<String>emptySet(); this.certPathCheckers = new ArrayList<PKIXCertPathChecker>(); this.certStores = new ArrayList<CertStore>(); }
private void compareKeyStore(KeyStore a, KeyStore b, String inKeyPass, String outKeyPass, int keyStoreSize) throws Exception { if (a.size() != keyStoreSize || b.size() != keyStoreSize) { throw new RuntimeException("size not match or size not equal to " + keyStoreSize); } Enumeration<String> eA = a.aliases(); while (eA.hasMoreElements()) { String aliasA = eA.nextElement(); if (!b.containsAlias(aliasA)) { throw new RuntimeException("alias not match for alias:" + aliasA); } compareKeyEntry(a, b, inKeyPass, outKeyPass, aliasA); } }
private static String verifyCRL(KeyStore ks, CRL crl) throws Exception { X509CRLImpl xcrl = (X509CRLImpl)crl; X500Principal issuer = xcrl.getIssuerX500Principal(); for (String s: e2i(ks.aliases())) { Certificate cert = ks.getCertificate(s); if (cert instanceof X509Certificate) { X509Certificate xcert = (X509Certificate)cert; if (xcert.getSubjectX500Principal().equals(issuer)) { try { ((X509CRLImpl)crl).verify(cert.getPublicKey()); return s; } catch (Exception e) { } } } } return null; }
/** * Initialize the {@link Cipher} instance with the created key in the {@link #createKey()} * method. * * @return {@code true} if initialization is successful, {@code false} if the lock screen has * been disabled or reset after the key was generated, or if a fingerprint got enrolled after * the key was generated. */ private boolean initCipher() { try { if (mKeyStore == null) { mKeyStore = KeyStore.getInstance("AndroidKeyStore"); } createKey(); mKeyStore.load(null); SecretKey key = (SecretKey) mKeyStore.getKey(KEY_NAME, null); mCipher = Cipher.getInstance("AES/CBC/PKCS7Padding"); mCipher.init(Cipher.ENCRYPT_MODE, key); return true; } catch (NoSuchPaddingException | KeyStoreException | CertificateException | UnrecoverableKeyException | IOException | NoSuchAlgorithmException | InvalidKeyException e) { return false; } }
/** * Locates a signer for a given certificate from a given keystore and * returns the signer's certificate. * @param cert the certificate whose signer is searched, not null * @param ks the keystore to search with, not null * @return <code>cert</code> itself if it's already inside <code>ks</code>, * or a certificate inside <code>ks</code> who signs <code>cert</code>, * or null otherwise. */ private static Certificate getTrustedSigner(Certificate cert, KeyStore ks) throws Exception { if (ks.getCertificateAlias(cert) != null) { return cert; } for (Enumeration<String> aliases = ks.aliases(); aliases.hasMoreElements(); ) { String name = aliases.nextElement(); Certificate trustedCert = ks.getCertificate(name); if (trustedCert != null) { try { cert.verify(trustedCert.getPublicKey()); return trustedCert; } catch (Exception e) { // Not verified, skip to the next one } } } return null; }
/** * Creates an SSLSocketFactory for HTTPS. Pass a KeyStore resource with your * certificate and passphrase */ public static SSLServerSocketFactory makeSSLSocketFactory(String keyAndTrustStoreClasspathPath, char[] passphrase) throws IOException { try { KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); InputStream keystoreStream = NanoHTTPD.class.getResourceAsStream(keyAndTrustStoreClasspathPath); if (keystoreStream == null) { throw new IOException("Unable to load keystore from classpath: " + keyAndTrustStoreClasspathPath); } keystore.load(keystoreStream, passphrase); KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keystore, passphrase); return makeSSLSocketFactory(keystore, keyManagerFactory); } catch (Exception e) { throw new IOException(e.getMessage()); } }
public void dumpTrustedCerts() { try { TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory .getDefaultAlgorithm()); tmf.init((KeyStore) null); X509TrustManager xtm = (X509TrustManager) tmf.getTrustManagers()[0]; StringBuffer buff = new StringBuffer(); for (X509Certificate cert : xtm.getAcceptedIssuers()) { String certStr = "S:" + cert.getSubjectDN().getName() + "\nI:" + cert.getIssuerDN().getName(); Log.d(TAG, certStr); buff.append(certStr + "\n\n"); } } catch (GeneralSecurityException e) { throw new RuntimeException(e); } }
/** * This Initializes the TrustStoreController. */ public TrustStoreController(Dialog ownerDialog, File trustStoreFile, String trustStorePassword, boolean edit) { this.ownerDialog = ownerDialog; try { trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); if (trustStoreFile != null && trustStorePassword != null) { if(edit){ openTrustStore(trustStoreFile, trustStorePassword); } else { createTrustStore(trustStoreFile, trustStorePassword); } } } catch (KeyStoreException e) { e.printStackTrace(); } }
void sqeImportTest() throws Exception { KeyStore ks; remove("x.jks"); testOK("", "-keystore x.jks -storepass changeit -keypass changeit -genkeypair -dname CN=olala"); testOK("", "-keystore x.jks -storepass changeit -exportcert -file x.jks.p1.cert"); /* deleted */ testOK("", "-keystore x.jks -storepass changeit -delete -alias mykey"); testOK("", "-keystore x.jks -storepass changeit -importcert -file x.jks.p1.cert -noprompt"); /* deleted */ testOK("", "-keystore x.jks -storepass changeit -delete -alias mykey"); testOK("yes\n", "-keystore x.jks -storepass changeit -importcert -file x.jks.p1.cert"); ks = loadStore("x.jks", "changeit", "JKS"); assertTrue(ks.containsAlias("mykey"), "imported"); /* deleted */ testOK("", "-keystore x.jks -storepass changeit -delete -alias mykey"); testOK("\n", "-keystore x.jks -storepass changeit -importcert -file x.jks.p1.cert"); ks = loadStore("x.jks", "changeit", "JKS"); assertTrue(!ks.containsAlias("mykey"), "imported"); testOK("no\n", "-keystore x.jks -storepass changeit -importcert -file x.jks.p1.cert"); ks = loadStore("x.jks", "changeit", "JKS"); assertTrue(!ks.containsAlias("mykey"), "imported"); testFail("no\n", "-keystore x.jks -storepass changeit -importcert -file nonexist"); testFail("no\n", "-keystore x.jks -storepass changeit -importcert -file x.jks"); remove("x.jks"); }
/** * JBMR2+ If Key with the default alias exists, returns true, else false. * on pre-JBMR2 returns true always. */ public static boolean isSigningKey(String alias) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { try { KeyStore keyStore = KeyStore.getInstance(SecurityConstants.KEYSTORE_PROVIDER_ANDROID_KEYSTORE); keyStore.load(null); return keyStore.containsAlias(alias); } catch (Exception e) { Log.e(TAG, e.getMessage(), e); return false; } } else { return false; } }
private static void initSSL(AsyncHttpClient client) { try { /// We initialize a default Keystore KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); // We load the KeyStore trustStore.load(null, null); // We initialize a new SSLSocketFacrory MySSLSocketFactory socketFactory = new MySSLSocketFactory(trustStore); // We set that all host names are allowed in the socket factory socketFactory.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); // We set the SSL Factory client.setSSLSocketFactory(socketFactory); // We initialize a GET http request } catch (Exception e) { e.printStackTrace(); } }
@Override public Properties getCredentials(final Properties securityProperties, final DistributedMember server, final boolean isPeer) throws AuthenticationFailedException { final String keyStorePath = securityProperties.getProperty(KEYSTORE_FILE_PATH); if (keyStorePath == null) { throw new AuthenticationFailedException( "PKCSAuthInit: key-store file path property [" + KEYSTORE_FILE_PATH + "] not set."); } final String alias = securityProperties.getProperty(KEYSTORE_ALIAS); if (alias == null) { throw new AuthenticationFailedException( "PKCSAuthInit: key alias name property [" + KEYSTORE_ALIAS + "] not set."); } final String keyStorePass = securityProperties.getProperty(KEYSTORE_PASSWORD); try { final KeyStore ks = KeyStore.getInstance("PKCS12"); final char[] passPhrase = (keyStorePass != null ? keyStorePass.toCharArray() : null); final FileInputStream certificatefile = new FileInputStream(keyStorePath); try { ks.load(certificatefile, passPhrase); } finally { certificatefile.close(); } final Key key = ks.getKey(alias, passPhrase); if (key instanceof PrivateKey) { final PrivateKey privKey = (PrivateKey) key; final X509Certificate cert = (X509Certificate) ks.getCertificate(alias); final Signature sig = Signature.getInstance(cert.getSigAlgName()); sig.initSign(privKey); sig.update(alias.getBytes("UTF-8")); final byte[] signatureBytes = sig.sign(); final Properties newprops = new Properties(); newprops.put(KEYSTORE_ALIAS, alias); newprops.put(SIGNATURE_DATA, signatureBytes); return newprops; } else { throw new AuthenticationFailedException( "PKCSAuthInit: " + "Failed to load private key from the given file: " + keyStorePath); } } catch (Exception ex) { throw new AuthenticationFailedException( "PKCSAuthInit: Exception while getting credentials: " + ex, ex); } }
private static KeyManager[] prepareKeyManager(InputStream bksFile, String password) { try { if (bksFile == null || password == null) return null; KeyStore clientKeyStore = KeyStore.getInstance("BKS"); clientKeyStore.load(bksFile, password.toCharArray()); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(clientKeyStore, password.toCharArray()); return kmf.getKeyManagers(); } catch (Exception e) { Log.e("ssl", e.getMessage()); } return null; }
/** * Gets the initialized key managers. */ protected KeyManager[] getKeyManagers(String keystoreType, String keystoreProvider, String algorithm, String keyAlias) throws Exception { KeyManager[] kms = null; String keystorePass = getKeystorePassword(); KeyStore ks = getKeystore(keystoreType, keystoreProvider, keystorePass); if (keyAlias != null && !ks.isKeyEntry(keyAlias)) { throw new IOException( sm.getString("jsse.alias_no_key_entry", keyAlias)); } KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm); String keyPass = endpoint.getKeyPass(); if (keyPass == null) { keyPass = keystorePass; } kmf.init(ks, keyPass.toCharArray()); kms = kmf.getKeyManagers(); if (keyAlias != null) { String alias = keyAlias; if (JSSESocketFactory.defaultKeystoreType.equals(keystoreType)) { alias = alias.toLowerCase(Locale.ENGLISH); } for(int i=0; i<kms.length; i++) { kms[i] = new JSSEKeyManager((X509KeyManager)kms[i], alias); } } return kms; }
/** * 获得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; }
private void storeAttrs() throws UnrecoverableEntryException, GeneralSecurityException, NoSuchAlgorithmException, KeyStoreException, IOException { KeyStore ksIn = Utils.loadKeyStore(KEYSTORE_PATH, Utils.KeyStoreType.pkcs12, PASSWORD); KeyStore ksAttr = KeyStore .getInstance(Utils.KeyStoreType.pkcs12.name()); ksAttr.load(null); Key key = ksIn.getKey(ALIAS, PASSWORD); Certificate cert = ksIn.getCertificate(ALIAS); Set<KeyStore.Entry.Attribute> attrs = new HashSet<>(Arrays.asList(ATTR_SET)); KeyStore.Entry e = new KeyStore.PrivateKeyEntry((PrivateKey) key, new Certificate[]{cert}, attrs); ksAttr.setEntry(ALIAS, e, new KeyStore.PasswordProtection( KEY_PASSWORD)); out.println("Attributes before store:"); e.getAttributes().stream().forEach((attr) -> { out.println(attr.getName() + ", '" + attr.getValue() + "'"); }); Utils.saveKeyStore(ksAttr, WORKING_DIRECTORY + File.separator + KESTORE_NEW, PASSWORD); }
/** * Creates a new {@link KeyStore}. This method will be called * by the base class when Spring creates a bean using this FactoryBean. * * @return a new {@link KeyStore} instance. */ public KeyStore newInstance() throws KeyStoreException, NoSuchProviderException, NoSuchAlgorithmException, CertificateException, IOException { if (data == null) { throw new IllegalStateException("data property is not set."); } KeyStore ks; if (provider == null) { ks = KeyStore.getInstance(type); } else { ks = KeyStore.getInstance(type, provider); } InputStream is = new ByteArrayInputStream(data); try { ks.load(is, password); } finally { try { is.close(); } catch (IOException ignored) { // Do nothing } } return ks; }
public SSLContextBuilder loadTrustMaterial( final File file, final char[] storePassword, final TrustStrategy trustStrategy) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException { Args.notNull(file, "Truststore file"); final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); final FileInputStream instream = new FileInputStream(file); try { trustStore.load(instream, storePassword); } finally { instream.close(); } return loadTrustMaterial(trustStore, trustStrategy); }
/** * Gets getUrl 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; }
private synchronized static void removeAliasAndFiles(Context context, String alias, String dataFileName, String ivFileName) { KeyStore keyStore; try { keyStore = KeyStore.getInstance(ANDROID_KEY_STORE); keyStore.load(null); keyStore.deleteEntry(alias); new File(getFilePath(context, dataFileName)).delete(); new File(getFilePath(context, ivFileName)).delete(); } catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | IOException e) { e.printStackTrace(); } }
public X509Certificate getServerCertificate() { try { KeyStore keyStore = loadKeyStore(); return (X509Certificate) keyStore.getCertificate(SERVER_CERTIFICATE_ALIAS); } catch (KeyStoreException e) { throw new RuntimeException(e); } }
/** * Creates an SSLSocketFactory for HTTPS. Pass a loaded KeyStore and a * loaded KeyManagerFactory. These objects must properly loaded/initialized * by the caller. */ public static SSLServerSocketFactory makeSSLSocketFactory(KeyStore loadedKeyStore, KeyManagerFactory loadedKeyFactory) throws IOException { try { return makeSSLSocketFactory(loadedKeyStore, loadedKeyFactory.getKeyManagers()); } catch (Exception e) { throw new IOException(e.getMessage()); } }
/** * 获得KeyStore * * @param keyStorePath 密钥库路径 * @param password 密码 * @return KeyStore 密钥库 * @throws Exception */ private static KeyStore getKeyStore(String keyStorePath, String password) throws Exception { // 实例化密钥库 KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); // 获得密钥库文件流 FileInputStream is = new FileInputStream(keyStorePath); // 加载密钥库 ks.load(is, password.toCharArray()); // 关闭密钥库文件流 is.close(); return ks; }
protected RestClient buildClient(Settings settings, HttpHost[] hosts) throws IOException { RestClientBuilder builder = RestClient.builder(hosts); 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(); SSLIOSessionStrategy sessionStrategy = new SSLIOSessionStrategy(sslcontext); builder.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLStrategy(sessionStrategy)); } catch (KeyStoreException|NoSuchAlgorithmException|KeyManagementException|CertificateException e) { throw new RuntimeException("Error setting up ssl", 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(); }
public static KeyStore getKeyStore(String storeType) throws KeyStoreException, NoSuchProviderException { ParamUtil.requireNonBlank("storeType", storeType); if ("JKS".equalsIgnoreCase(storeType) || "JCEKS".equalsIgnoreCase(storeType)) { return KeyStore.getInstance(storeType); } else { try { return KeyStore.getInstance(storeType, "BC"); } catch (KeyStoreException | NoSuchProviderException ex) { return KeyStore.getInstance(storeType); } } }
/** * 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; }
private X509TrustManager systemDefaultTrustManager() { try { TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance( TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init((KeyStore) null); TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) { throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers)); } return (X509TrustManager) trustManagers[0]; } catch (GeneralSecurityException e) { throw new AssertionError(); // The system has no TLS. Just give up. } }
protected KeyStore getKeystore(String type, String provider, String pass) throws IOException { String keystoreFile = endpoint.getKeystoreFile(); if (keystoreFile == null) keystoreFile = defaultKeystoreFile; return getStore(type, provider, keystoreFile, pass); }
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); } }
public static void main(String[] args) throws Exception { String keyFilename = System.getProperty("test.src", "./") + "/" + pathToStores + "/" + keyStoreFile; String trustFilename = System.getProperty("test.src", "./") + "/" + pathToStores + "/" + trustStoreFile; System.setProperty("javax.net.ssl.keyStore", keyFilename); System.setProperty("javax.net.ssl.keyStorePassword", passwd); System.setProperty("javax.net.ssl.trustStore", trustFilename); System.setProperty("javax.net.ssl.trustStorePassword", passwd); sslctx = SSLContext.getInstance("TLS"); KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); KeyStore ks = KeyStore.getInstance("JKS"); ks.load(new FileInputStream(keyFilename), passwd.toCharArray()); kmf.init(ks, passwd.toCharArray()); sslctx.init(kmf.getKeyManagers(), null, null); sslssf = (SSLServerSocketFactory) sslctx.getServerSocketFactory(); sslsf = (SSLSocketFactory) sslctx.getSocketFactory(); if (debug) System.setProperty("javax.net.debug", "all"); /* * Start the tests. */ new SSLCtxAccessToSessCtx(); }
private X509TrustManager systemDefaultTrustManager() { try { TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance( TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init((KeyStore) null); TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) { throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers)); } return (X509TrustManager) trustManagers[0]; } catch (GeneralSecurityException e) { throw assertionError("No System TLS", e); // The system has no TLS. Just give up. } }
public static void main (String[] args) throws Exception { SecretKey key = new SecretKeySpec(new byte[8], "DES"); KeyStore ks = KeyStore.getInstance("JKS"); ks.load(null, passwd); try { // store the SecretKey ks.setKeyEntry("test_encrypt_key", key, passwd, null); throw new Exception("Should throw KeyStoreException when " + "storing SecretKey into JKS keystores"); } catch (KeyStoreException kse) { // expected exception thrown; swallow } }
private static KeyManager[] prepareKeyManager(InputStream bksFile, String password) { try { if (bksFile == null || password == null) { return null; } KeyStore clientKeyStore = KeyStore.getInstance("BKS"); clientKeyStore.load(bksFile, password.toCharArray()); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(clientKeyStore, password.toCharArray()); return kmf.getKeyManagers(); } catch (Exception e) { OkLogger.printStackTrace(e); } return null; }