public static SSLContext createSSLContext( boolean clientMode, String keystore, String password, String trustStore, String trustPassword) throws Exception { // Create/initialize the SSLContext with key material char[] passphrase = password.toCharArray(); // First initialize the key and trust material. KeyStore ks = KeyStore.getInstance("JKS"); ks.load(new FileInputStream(keystore), passphrase); SSLContext sslContext = SSLContext.getInstance("TLS"); if (clientMode) { // TrustManager's decide whether to allow connections. TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); sslContext.init(null, tmf.getTrustManagers(), null); } else { // KeyManager's decide which key material to use. KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(ks, passphrase); if (trustStore != null) { KeyStore ts = KeyStore.getInstance("JKS"); ts.load(new FileInputStream(trustStore), trustPassword.toCharArray()); TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); tmf.init(ts); System.out.println("Using the trust store for client auth"); sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); } else sslContext.init(kmf.getKeyManagers(), null, null); } return sslContext; }
private SSLSocketFactory newSslSocketFactory() { try { // Get an instance of the Bouncy Castle KeyStore format KeyStore trusted = KeyStore.getInstance("BKS"); // Get the raw resource, which contains the keystore with // your trusted certificates (root and any intermediate certs) InputStream in = context.getResources().openRawResource(tracker.springversion1.R.raw.mykeystore); try { // Initialize the keystore with the provided trusted // certificates // Also provide the password of the keystore trusted.load(in, "mysecret".toCharArray()); } finally { in.close(); } // Pass the keystore to the SSLSocketFactory. The factory is // responsible // for the verification of the server certificate. SSLSocketFactory sf = new SSLSocketFactory(trusted); // Hostname verification from certificate // http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d4e506 sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); // ALLOW_ALL_HOSTNAME_VERIFIER return sf; } catch (Exception e) { throw new AssertionError(e); } }
private SSLContext createSSLContext(final SSLContextService service) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException, UnrecoverableKeyException { SSLContextBuilder builder = SSLContexts.custom(); final String trustFilename = service.getTrustStoreFile(); if (trustFilename != null) { final KeyStore truststore = KeyStore.getInstance(service.getTrustStoreType()); try (final InputStream in = new FileInputStream(new File(service.getTrustStoreFile()))) { truststore.load(in, service.getTrustStorePassword().toCharArray()); } builder = builder.loadTrustMaterial(truststore, new TrustSelfSignedStrategy()); } final String keyFilename = service.getKeyStoreFile(); if (keyFilename != null) { final KeyStore keystore = KeyStore.getInstance(service.getKeyStoreType()); try (final InputStream in = new FileInputStream(new File(service.getKeyStoreFile()))) { keystore.load(in, service.getKeyStorePassword().toCharArray()); } builder = builder.loadKeyMaterial(keystore, service.getKeyStorePassword().toCharArray()); } SSLContext sslContext = builder.build(); return sslContext; }
public void init(Properties properties) throws Exception { KeyStore ks = KeyStore.getInstance("JKS"); KeyStore ts = KeyStore.getInstance("JKS"); String keyStorePassword = properties.getProperty("keyStorePassword"); if (keyStorePassword == null) { keyStorePassword = System.getProperty("javax.net.ssl.keyStorePassword"); } String keyStore = properties.getProperty("keyStore"); if (keyStore == null) { keyStore = System.getProperty("javax.net.ssl.keyStore"); } if (keyStore == null || keyStorePassword == null) { throw new RuntimeException("SSL is enabled but keyStore[Password] properties aren't set!"); } String keyManagerAlgorithm = getProperty(properties, "keyManagerAlgorithm", "SunX509"); String trustManagerAlgorithm = getProperty(properties, "trustManagerAlgorithm", "SunX509"); String protocol = getProperty(properties, "protocol", "TLS"); final char[] passPhrase = keyStorePassword.toCharArray(); final String keyStoreFile = keyStore; ks.load(new FileInputStream(keyStoreFile), passPhrase); ts.load(new FileInputStream(keyStoreFile), passPhrase); KeyManagerFactory kmf = KeyManagerFactory.getInstance(keyManagerAlgorithm); kmf.init(ks, passPhrase); TrustManagerFactory tmf = TrustManagerFactory.getInstance(trustManagerAlgorithm); tmf.init(ts); sslContext = SSLContext.getInstance(protocol); sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); }
/** * Returns SSLContext with TESTED_SECURITY_PROTOCOL protocol and sets up keys. * * @return - SSLContext with a protocol specified by TESTED_SECURITY_PROTOCOL. */ public static SSLContext getContext() { try { java.security.Security.setProperty("jdk.tls.disabledAlgorithms", ""); java.security.Security.setProperty("jdk.certpath.disabledAlgorithms", ""); KeyStore ks = KeyStore.getInstance("JKS"); KeyStore ts = KeyStore.getInstance("JKS"); char[] passphrase = PASSWD.toCharArray(); try (FileInputStream keyFileStream = new FileInputStream(KEY_FILE_NAME)) { ks.load(keyFileStream, passphrase); } try (FileInputStream trustFileStream = new FileInputStream(TRUST_FILE_NAME)) { ts.load(trustFileStream, passphrase); } KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); kmf.init(ks, passphrase); TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); tmf.init(ts); SSLContext sslCtx = SSLContext.getInstance(TESTED_SECURITY_PROTOCOL); sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); return sslCtx; } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException | UnrecoverableKeyException | KeyManagementException ex) { throw new Error("Unexpected exception", ex); } }
/** Loads the system trust store. */ private static KeyStore loadSystemTrustStore() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException { KeyStore ks; if (Build.VERSION.SDK_INT >= 14) { ks = KeyStore.getInstance("AndroidCAStore"); ks.load(null, null); } else { ks = KeyStore.getInstance("BKS"); String path = System.getProperty("javax.net.ssl.trustStore"); if (path == null) path = System.getProperty("java.home") + File.separator + "etc" + File.separator + "security" + File.separator + "cacerts.bks"; ks.load(new FileInputStream(path), null); } return ks; }
/** connection with SSL */ public void sslConnection() { String keyStoreLocation = properties.getProperty(IbmMqConstants.SSL_KEYSTORE_LOCATION); String keyStoreType = properties.getProperty(IbmMqConstants.SSL_KEYSTORE_TYPE); String keyStorePassword = properties.getProperty(IbmMqConstants.SSL_KEYSTORE_PASSWORD); String trustStoreLocation = properties.getProperty(IbmMqConstants.SSL_TRUSTSTORE_LOCATION); String trustStoreType = properties.getProperty(IbmMqConstants.SSL_TRUSTSTORE_TYPE); String sslVersion = properties.getProperty(IbmMqConstants.SSL_VERSION); String sslFipsRequired = properties.getProperty(IbmMqConstants.SSL_FIPS); String sslCipherSuite = properties.getProperty(IbmMqConstants.SSL_CIPHERSUITE); boolean sslFips = Boolean.parseBoolean(sslFipsRequired); try { char[] keyPassphrase = keyStorePassword.toCharArray(); KeyStore ks = KeyStore.getInstance(keyStoreType); ks.load(new FileInputStream(keyStoreLocation), keyPassphrase); KeyStore trustStore = KeyStore.getInstance(trustStoreType); trustStore.load(new FileInputStream(trustStoreLocation), null); TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(trustStore); keyManagerFactory.init(ks, keyPassphrase); SSLContext sslContext = SSLContext.getInstance(sslVersion); sslContext.init( keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null); mqProperties.put(MQConstants.SSL_SOCKET_FACTORY_PROPERTY, sslContext); mqProperties.put(MQConstants.SSL_FIPS_REQUIRED_PROPERTY, sslFips); mqProperties.put(MQConstants.SSL_CIPHER_SUITE_PROPERTY, sslCipherSuite); } catch (Exception ex) { handleException(ex.getMessage()); } }
static { String algorithm = JiveGlobals.getProperty("xmpp.socket.ssl.algorithm", "TLS"); String storeType = JiveGlobals.getProperty("xmpp.socket.ssl.storeType", "jks"); // Get the keystore location. The default location is security/keystore keyStoreLocation = JiveGlobals.getProperty( "xmpp.socket.ssl.keystore", "resources" + File.separator + "security" + File.separator + "keystore"); keyStoreLocation = JiveGlobals.getHomeDirectory() + File.separator + keyStoreLocation; // Get the keystore password. The default password is "changeit". keypass = JiveGlobals.getProperty("xmpp.socket.ssl.keypass", "changeit"); keypass = keypass.trim(); // Get the truststore location; default at security/truststore trustStoreLocation = JiveGlobals.getProperty( "xmpp.socket.ssl.truststore", "resources" + File.separator + "security" + File.separator + "truststore"); trustStoreLocation = JiveGlobals.getHomeDirectory() + File.separator + trustStoreLocation; // Get the truststore passwprd; default is "changeit". trustpass = JiveGlobals.getProperty("xmpp.socket.ssl.trustpass", "changeit"); trustpass = trustpass.trim(); try { keyStore = KeyStore.getInstance(storeType); keyStore.load(new FileInputStream(keyStoreLocation), keypass.toCharArray()); trustStore = KeyStore.getInstance(storeType); trustStore.load(new FileInputStream(trustStoreLocation), trustpass.toCharArray()); sslFactory = (SSLJiveServerSocketFactory) SSLJiveServerSocketFactory.getInstance(algorithm, keyStore, trustStore); } catch (Exception e) { Log.error( "SSLConfig startup problem.\n" + " storeType: [" + storeType + "]\n" + " keyStoreLocation: [" + keyStoreLocation + "]\n" + " keypass: [" + keypass + "]\n" + " trustStoreLocation: [" + trustStoreLocation + "]\n" + " trustpass: [" + trustpass + "]", e); keyStore = null; trustStore = null; sslFactory = null; } }
public static void createPublicCert( String targetKeystoreFile, String keyName, String rootKeystorePath, char[] rootKeystorePassword, char[] truststorePassword) throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException { KeyStore signerKeystore = KeyStore.getInstance(keystoreType); char[] signerPasswordArray = rootKeystorePassword; FileInputStream rootKeystoreInputStream = null; try { rootKeystoreInputStream = new FileInputStream(rootKeystorePath); signerKeystore.load(rootKeystoreInputStream, signerPasswordArray); } finally { if (rootKeystoreInputStream != null) { rootKeystoreInputStream.close(); } } Certificate rootCert = findCert(signerKeystore); KeyStore keystore = KeyStore.getInstance(keystoreType); keystore.load(null, null); keystore.setCertificateEntry(keyName + "Cert", rootCert); FileOutputStream targetKeystoreOutputStream = null; try { targetKeystoreOutputStream = new FileOutputStream(targetKeystoreFile); keystore.store(targetKeystoreOutputStream, truststorePassword); } finally { if (targetKeystoreOutputStream != null) { targetKeystoreOutputStream.close(); } } }
/** * Load all X509 Certs from a key store File into a KeyStore Note that each call reinitializes the * KeyStore * * @return success * @since 0.8.2, moved from SSLEepGet in 0.9.9 */ private static boolean loadCerts(File file, KeyStore ks) { if (!file.exists()) return false; InputStream fis = null; try { fis = new FileInputStream(file); // "changeit" is the default password ks.load(fis, DEFAULT_KEYSTORE_PASSWORD.toCharArray()); info("Certs loaded from " + file); } catch (GeneralSecurityException gse) { error("KeyStore load error, no default keys: " + file.getAbsolutePath(), gse); try { // not clear if null is allowed for password ks.load(null, DEFAULT_KEYSTORE_PASSWORD.toCharArray()); } catch (Exception foo) { } return false; } catch (IOException ioe) { error("KeyStore load error, no default keys: " + file.getAbsolutePath(), ioe); try { ks.load(null, DEFAULT_KEYSTORE_PASSWORD.toCharArray()); } catch (Exception foo) { } return false; } finally { try { if (fis != null) fis.close(); } catch (IOException foo) { } } return true; }
private static KeyStore loadKeyStore() throws GeneralSecurityException { KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); boolean isKeyStoreInitialized = false; InputStream in = null; try { in = new FileInputStream(LC.mailboxd_keystore.value()); try { keyStore.load(in, LC.mailboxd_keystore_password.value().toCharArray()); isKeyStoreInitialized = true; } catch (CertificateException x) { ZimbraLog.security.warn("failed to load certificates", x); } catch (IOException x) { ZimbraLog.security.warn("failed to read keystore file", x); } } catch (FileNotFoundException x) { ZimbraLog.security.info("keystore not present"); } finally { if (in != null) try { in.close(); } catch (IOException x) { ZimbraLog.security.warn("keystore file can't be closed after reading", x); } } if (!isKeyStoreInitialized) { try { in = new FileInputStream(LC.mailboxd_keystore_base.value()); try { keyStore.load(in, LC.mailboxd_keystore_base_password.value().toCharArray()); isKeyStoreInitialized = true; } catch (CertificateException x) { ZimbraLog.security.warn("failed to load backup certificates", x); } catch (IOException x) { ZimbraLog.security.warn("failed to read backup keystore file", x); } } catch (FileNotFoundException x) { ZimbraLog.security.warn("backup keystore not found"); } finally { if (in != null) try { in.close(); } catch (IOException x) { ZimbraLog.security.warn("backup keystore file can't be closed after reading", x); } } } if (!isKeyStoreInitialized) { keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); try { keyStore.load(null, new char[0]); } catch (IOException x) { throw new KeyStoreException(x); } } return keyStore; }
public static SSLSocketFactory getSocketFactory( String caCrtFile, String crtFile, String keyFile, String password) throws Exception { char[] passwordCharArray = password == null ? new char[0] : password.toCharArray(); Security.addProvider(new BouncyCastleProvider()); CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate caCert = (X509Certificate) cf.generateCertificate( new ByteArrayInputStream(Files.readAllBytes(Paths.get(caCrtFile)))); X509Certificate cert = (X509Certificate) cf.generateCertificate( new ByteArrayInputStream(Files.readAllBytes(Paths.get(crtFile)))); File privateKeyFile = new File(keyFile); PEMParser pemParser = new PEMParser(new FileReader(privateKeyFile)); PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build(passwordCharArray); JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC"); Object object = pemParser.readObject(); KeyPair kp; if (object instanceof PEMEncryptedKeyPair) { kp = converter.getKeyPair(((PEMEncryptedKeyPair) object).decryptKeyPair(decProv)); } else { kp = converter.getKeyPair((PEMKeyPair) object); } pemParser.close(); KeyStore caKeyStore = KeyStore.getInstance(KeyStore.getDefaultType()); caKeyStore.load(null, null); caKeyStore.setCertificateEntry("ca-certificate", caCert); TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(caKeyStore); KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, null); keyStore.setCertificateEntry("certificate", cert); keyStore.setKeyEntry( "private-key", kp.getPrivate(), passwordCharArray, new java.security.cert.Certificate[] {cert}); KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keyStore, passwordCharArray); SSLContext context = SSLContext.getInstance("TLSv1"); context.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null); return context.getSocketFactory(); }
private KeyStore createKeyStore(@Nullable String path) throws IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException { String keyStoreType = KeyStore.getDefaultType(); char[] defaultPassword = "******".toCharArray(); if (path != null) { // If the user provided path, only try to load the keystore at that path. KeyStore keyStore = KeyStore.getInstance(keyStoreType); FileInputStream is = new FileInputStream(path); keyStore.load(is, defaultPassword); return keyStore; } try { // Check if we are on Android. Class version = Class.forName("android.os.Build$VERSION"); // Build.VERSION_CODES.ICE_CREAM_SANDWICH is 14. if (version.getDeclaredField("SDK_INT").getInt(version) >= 14) { // After ICS, Android provided this nice method for loading the keystore, // so we don't have to specify the location explicitly. KeyStore keystore = KeyStore.getInstance("AndroidCAStore"); keystore.load(null, null); return keystore; } else { keyStoreType = "BKS"; path = System.getProperty("java.home") + "/etc/security/cacerts.bks".replace('/', File.separatorChar); } } catch (ClassNotFoundException e) { // NOP. android.os.Build is not present, so we are not on Android. Fall through. } catch (NoSuchFieldException e) { throw new RuntimeException(e); // Should never happen. } catch (IllegalAccessException e) { throw new RuntimeException(e); // Should never happen. } if (path == null) { path = System.getProperty("javax.net.ssl.trustStore"); } if (path == null) { // Try this default system location for Linux/Windows/OSX. path = System.getProperty("java.home") + "/lib/security/cacerts".replace('/', File.separatorChar); } try { KeyStore keyStore = KeyStore.getInstance(keyStoreType); FileInputStream is = new FileInputStream(path); keyStore.load(is, defaultPassword); return keyStore; } catch (FileNotFoundException e) { // If we failed to find a system trust store, load our own fallback trust store. This can fail // on Android // but we should never reach it there. KeyStore keyStore = KeyStore.getInstance("JKS"); InputStream is = getClass().getResourceAsStream("cacerts"); keyStore.load(is, defaultPassword); return keyStore; } }
public static void main(String[] args) throws Exception { if (args.length < 1) { System.err.println("usage: java PKCS12Import {pkcs12file} [newjksfile]"); System.exit(1); } File fileIn = new File(args[0]); File fileOut; if (args.length > 1) { fileOut = new File(args[1]); } else { fileOut = new File("newstore.jks"); } if (!fileIn.canRead()) { System.err.println("Unable to access input keystore: " + fileIn.getPath()); System.exit(2); } if (fileOut.exists() && !fileOut.canWrite()) { System.err.println("Output file is not writable: " + fileOut.getPath()); System.exit(2); } KeyStore kspkcs12 = KeyStore.getInstance("pkcs12"); KeyStore ksjks = KeyStore.getInstance("jks"); LineNumberReader in = new LineNumberReader(new InputStreamReader(System.in)); System.out.print("Enter input keystore passphrase: "); char[] inphrase = in.readLine().toCharArray(); System.out.print("Enter output keystore passphrase: "); char[] outphrase = in.readLine().toCharArray(); kspkcs12.load(new FileInputStream(fileIn), inphrase); ksjks.load((fileOut.exists()) ? new FileInputStream(fileOut) : null, outphrase); Enumeration eAliases = kspkcs12.aliases(); int n = 0; while (eAliases.hasMoreElements()) { String strAlias = (String) eAliases.nextElement(); System.err.println("Alias " + n++ + ": " + strAlias); if (kspkcs12.isKeyEntry(strAlias)) { System.err.println("Adding key for alias " + strAlias); Key key = kspkcs12.getKey(strAlias, inphrase); Certificate[] chain = kspkcs12.getCertificateChain(strAlias); ksjks.setKeyEntry(strAlias, key, outphrase, chain); } } OutputStream out = new FileOutputStream(fileOut); ksjks.store(out, outphrase); out.close(); }
public void configureService( String address, String pksFilename, String pksPassword, String trustPksFilename, String trustPksPassword) throws Exception { if (pksFilename != null && pksPassword != null && trustPksFilename != null && trustPksPassword != null) { System.setProperty("javax.net.ssl.keyStore", pksFilename); System.setProperty("javax.net.ssl.keyStorePassword", pksPassword); System.setProperty("javax.net.ssl.trustStore", trustPksFilename); System.setProperty("javax.net.ssl.trustStorePassword", trustPksPassword); } URL wsdlUrl = new URL(address + "?wsdl"); IoTaService service = new IoTaService(wsdlUrl); port = service.getPort(IoTaServicePortType.class); // turn off chunked transfer encoding Client client = ClientProxy.getClient(port); HTTPConduit httpConduit = (HTTPConduit) client.getConduit(); HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy(); httpClientPolicy.setAllowChunking(false); httpConduit.setClient(httpClientPolicy); if (pksFilename != null) { log.debug("Authenticating with certificate in file: " + pksFilename); if (!wsdlUrl.getProtocol().equalsIgnoreCase("https")) { throw new Exception("Authentication method requires the use of HTTPS"); } KeyStore keyStore = KeyStore.getInstance(pksFilename.endsWith(".p12") ? "PKCS12" : "JKS"); keyStore.load(new FileInputStream(new File(pksFilename)), pksPassword.toCharArray()); KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509"); keyManagerFactory.init(keyStore, pksPassword.toCharArray()); KeyStore trustStore = KeyStore.getInstance(trustPksFilename.endsWith(".p12") ? "PKCS12" : "JKS"); trustStore.load( new FileInputStream(new File(trustPksFilename)), trustPksPassword.toCharArray()); TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509"); trustManagerFactory.init(trustStore); TLSClientParameters tlscp = new TLSClientParameters(); tlscp.setSecureRandom(new SecureRandom()); tlscp.setKeyManagers(keyManagerFactory.getKeyManagers()); tlscp.setTrustManagers(trustManagerFactory.getTrustManagers()); httpConduit.setTlsClientParameters(tlscp); } }
/* * In case of self signed certificates on Server. Two things needs to be taken care * 1)Authenticate to the HTTPS server using a private key. * 2)Validate the identity of the HTTPS server against a list of trusted certificates * * Ref - http://developer.android.com/reference/org/apache/http/conn/ssl/SSLSocketFactory.html */ private static SSLContext createEasySSLContext() throws IOException { try { // Client should authenticate itself with the valid certificate to Server. InputStream clientStream = VolleySampleApplication.getContext() .getResources() .openRawResource(R.raw.production_test_client); char[] password = "******".toCharArray(); KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load(clientStream, password); KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keyStore, password); // Client should also add the CA certificate obtained from server and create TrustManager from // it for the client to validate the // identity of the server. KeyStore trustStore = KeyStore.getInstance("BKS"); InputStream instream = null; instream = VolleySampleApplication.getContext() .getResources() .openRawResource(R.raw.production_test_ca); try { trustStore.load(instream, "XXXXXXXX".toCharArray()); } catch (Exception e) { e.printStackTrace(); } finally { try { instream.close(); } catch (Exception ignore) { } } String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(trustStore); // Create an SSLContext that uses our TrustManager & Keystore SSLContext context = SSLContext.getInstance("TLS"); context.init(keyManagerFactory.getKeyManagers(), tmf.getTrustManagers(), null); return context; } catch (Exception e) { e.printStackTrace(); throw new IOException(e.getMessage()); } }
private DockerCertificates(final Builder builder) throws DockerCertificateException { if ((builder.caCertPath == null) || (builder.clientCertPath == null) || (builder.clientKeyPath == null)) { throw new DockerCertificateException( "caCertPath, clientCertPath, and clientKeyPath must all be specified"); } try { final CertificateFactory cf = CertificateFactory.getInstance("X.509"); final Certificate caCert = cf.generateCertificate(Files.newInputStream(builder.caCertPath)); final Certificate clientCert = cf.generateCertificate(Files.newInputStream(builder.clientCertPath)); final PEMKeyPair clientKeyPair = (PEMKeyPair) new PEMParser( Files.newBufferedReader(builder.clientKeyPath, Charset.defaultCharset())) .readObject(); final PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(clientKeyPair.getPrivateKeyInfo().getEncoded()); final KeyFactory kf = KeyFactory.getInstance("RSA"); final PrivateKey clientKey = kf.generatePrivate(spec); final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); trustStore.setEntry("ca", new KeyStore.TrustedCertificateEntry(caCert), null); final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, null); keyStore.setCertificateEntry("client", clientCert); keyStore.setKeyEntry("key", clientKey, KEY_STORE_PASSWORD, new Certificate[] {clientCert}); this.sslContext = SSLContexts.custom() .loadTrustMaterial(trustStore) .loadKeyMaterial(keyStore, KEY_STORE_PASSWORD) .useTLS() .build(); } catch (CertificateException | IOException | NoSuchAlgorithmException | InvalidKeySpecException | KeyStoreException | UnrecoverableKeyException | KeyManagementException e) { throw new DockerCertificateException(e); } }
private static SSLContext createBougusServerSslContext() throws GeneralSecurityException, IOException { // Create keystore KeyStore ks = KeyStore.getInstance("JKS"); InputStream in = null; try { in = BogusSslContextFactory.class.getResourceAsStream(BOGUS_KEYSTORE); ks.load(in, BOGUS_PW); } finally { if (in != null) { try { in.close(); } catch (IOException ignored) { } } } // Set up key manager factory to use our key store KeyManagerFactory kmf = KeyManagerFactory.getInstance(KEY_MANAGER_FACTORY_ALGORITHM); kmf.init(ks, BOGUS_PW); // Initialize the SSLContext to work with our key managers. SSLContext sslContext = SSLContext.getInstance(PROTOCOL); sslContext.init(kmf.getKeyManagers(), BogusTrustManagerFactory.X509_MANAGERS, null); return sslContext; }
/** * Loads key store from storage, or creates new one if storage is missing key store or corrupted. */ private KeyStore load() { KeyStore keyStore; try { keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); } catch (KeyStoreException e) { throw new IllegalStateException("Unable to get default instance of KeyStore", e); } try { FileInputStream fis = mContext.openFileInput(KEYSTORE_FILENAME); keyStore.load(fis, KEYSTORE_PASSWORD); } catch (IOException e) { LogUtils.v("Unable open keystore file", e); keyStore = null; } catch (GeneralSecurityException e) { LogUtils.v("Unable open keystore file", e); keyStore = null; } if (keyStore != null) { // KeyStore loaded return keyStore; } try { keyStore = createKeyStore(); } catch (GeneralSecurityException e) { throw new IllegalStateException("Unable to create identity KeyStore", e); } store(keyStore); return keyStore; }
private KeyManager[] getKeyManagers(InputStream certificate, String passphrase) throws IOException { if (key_managers == null) { KeyStore ks; try { ks = KeyStore.getInstance("PKCS12"); } catch (KeyStoreException e) { throw new RuntimeException("Unable to create key store."); } char certphrase[] = passphrase.toCharArray(); try { ks.load(certificate, certphrase); } catch (GeneralSecurityException e) { throw new RuntimeException("Bad certificate or unknown type."); } finally { closeQuietly(certificate); } KeyManagerFactory kmf; try { kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(ks, certphrase); } catch (GeneralSecurityException e) { throw new RuntimeException(e.getMessage()); } key_managers = kmf.getKeyManagers(); } return key_managers; }
/** * HttpUrlConnection 方式,支持指定load-der.crt证书验证,此种方式Android官方建议 * * @throws CertificateException * @throws IOException * @throws KeyStoreException * @throws NoSuchAlgorithmException * @throws KeyManagementException */ public void initSSL() throws CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException { CertificateFactory cf = CertificateFactory.getInstance("X.509"); InputStream in = getAssets().open("load-der.crt"); Certificate ca = cf.generateCertificate(in); KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); keystore.load(null, null); keystore.setCertificateEntry("ca", ca); String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keystore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); URL url = new URL("https://trade3.guosen.com.cn/mtrade/check_version"); HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection(); urlConnection.setSSLSocketFactory(context.getSocketFactory()); InputStream input = urlConnection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8")); StringBuffer result = new StringBuffer(); String line = ""; while ((line = reader.readLine()) != null) { result.append(line); } Log.e("TTTT", result.toString()); }
static { String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm"); if (algorithm == null) { algorithm = "SunX509"; } SSLContext serverContext; SSLContext clientContext; try { KeyStore ks = KeyStore.getInstance("JKS"); ks.load(BogusKeyStore.asInputStream(), BogusKeyStore.getKeyStorePassword()); // Set up key manager factory to use our key store KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm); kmf.init(ks, BogusKeyStore.getCertificatePassword()); // Initialize the SSLContext to work with our key managers. serverContext = SSLContext.getInstance(PROTOCOL); serverContext.init(kmf.getKeyManagers(), null, null); } catch (Exception e) { throw new Error("Failed to initialize the server-side SSLContext", e); } try { clientContext = SSLContext.getInstance(PROTOCOL); clientContext.init(null, BogusTrustManagerFactory.getTrustManagers(), null); } catch (Exception e) { throw new Error("Failed to initialize the client-side SSLContext", e); } SERVER_CONTEXT = serverContext; CLIENT_CONTEXT = clientContext; }
static KeyStore getKeyStore() throws Exception { InputStream in = new FileInputStream(new File(BASE, "rsakeys.ks")); KeyStore ks = KeyStore.getInstance("JKS"); ks.load(in, password); in.close(); return ks; }
/** {@inheritDoc} */ public void createKeyStore(char[] store_password) throws KeyStoreException, IOException { try { KeyStore store; if (null == keystore_provider) { store = KeyStore.getInstance(keystore_type); } else { store = KeyStore.getInstance(keystore_type, keystore_provider); } store.load(null, store_password); saveKeyStore(store, store_password); } catch (NoSuchProviderException failed) { KeyStoreException failure = new KeyStoreException("NoSuchProviderException during keystore processing"); failure.initCause(failed); throw failure; } catch (NoSuchAlgorithmException failed) { KeyStoreException failure = new KeyStoreException("NoSuchAlgorithmException during keystore processing"); failure.initCause(failed); throw failure; } catch (CertificateException failed) { KeyStoreException failure = new KeyStoreException("CertificateException during keystore processing"); failure.initCause(failed); throw failure; } }
public void signZip( URL keystoreURL, String keystoreType, String keystorePw, String certAlias, String certPw, String inputZipFilename, String outputZipFilename) throws ClassNotFoundException, IllegalAccessException, InstantiationException, IOException, GeneralSecurityException { InputStream keystoreStream = null; try { KeyStore keystore = null; if (keystoreType == null) keystoreType = KeyStore.getDefaultType(); keystore = KeyStore.getInstance(keystoreType); keystoreStream = keystoreURL.openStream(); keystore.load(keystoreStream, keystorePw.toCharArray()); Certificate cert = keystore.getCertificate(certAlias); X509Certificate publicKey = (X509Certificate) cert; Key key = keystore.getKey(certAlias, certPw.toCharArray()); PrivateKey privateKey = (PrivateKey) key; setKeys("custom", publicKey, privateKey, null); signZip(inputZipFilename, outputZipFilename); } finally { if (keystoreStream != null) keystoreStream.close(); } }
public CertificateInstaller(Resource source, String host, int port, char[] passphrase) throws IOException, KeyStoreException, GeneralSecurityException { this.source = source; this.host = host; this.port = port; this.passphrase = passphrase; ks = null; InputStream in = source.getInputStream(); try { ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(in, passphrase); } finally { IOUtil.closeEL(in); } context = SSLContext.getInstance("TLS"); tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0]; tm = new SavingTrustManager(defaultTrustManager); context.init(null, new TrustManager[] {tm}, null); checkCertificate(); if (tm.chain == null) throw new IOException("Could not obtain server certificate chain"); }
KeyStore.PrivateKeyEntry getKey() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableEntryException { KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore"); keyStore.load(null); return (PrivateKeyEntry) keyStore.getEntry(alias, null); }
@BeforeClass public static void setUp() throws Exception { KEY = MessageDigest.getInstance("SHA-256").digest(ALIAS.getBytes()); // Create a JKECS store containing a test secret key KeyStore store = KeyStore.getInstance("JCEKS"); store.load(null, PASSWORD.toCharArray()); store.setEntry( ALIAS, new KeyStore.SecretKeyEntry(new SecretKeySpec(KEY, "AES")), new KeyStore.PasswordProtection(PASSWORD.toCharArray())); // Create the test directory String dataDir = TEST_UTIL.getDataTestDir().toString(); new File(dataDir).mkdirs(); // Write the keystore file storeFile = new File(dataDir, "keystore.jks"); FileOutputStream os = new FileOutputStream(storeFile); try { store.store(os, PASSWORD.toCharArray()); } finally { os.close(); } // Write the password file Properties p = new Properties(); p.setProperty(ALIAS, PASSWORD); passwordFile = new File(dataDir, "keystore.pw"); os = new FileOutputStream(passwordFile); try { p.store(os, ""); } finally { os.close(); } }
/** * Method creating a connection to the webservice using the information stored in the property * files. * * @throws IOException * @throws FileNotFoundException */ protected XKMSInvoker getXKMSInvoker() throws FileNotFoundException, IOException { if (xkms == null) { if (getKeyStorePath() != null) { try { KeyStore clientKeyStore = KeyStore.getInstance("JKS"); clientKeyStore.load( new FileInputStream(getKeyStorePath()), getKeyStorePassword().toCharArray()); if (getKeyStoreAlias() == null) { throw new IOException("Error no alias specified in the property file"); } String alias = getKeyStoreAlias(); clientCert = (java.security.cert.X509Certificate) clientKeyStore.getCertificate(alias); privateKey = clientKeyStore.getKey(alias, getKeyStorePassword().toCharArray()); Certificate[] trustedcerts = clientKeyStore.getCertificateChain(alias); catrustlist = new ArrayList<Certificate>(); for (int i = 0; i < trustedcerts.length; i++) { if (((X509Certificate) trustedcerts[i]).getBasicConstraints() != -1) { catrustlist.add(trustedcerts[i]); } } } catch (Exception e) { throw new IOException("Error reading client keystore " + e.getMessage()); } } xkms = new XKMSInvoker(getWebServiceURL(), catrustlist); } return xkms; }
/** * Used to get the base ssl context in which to create the server socket. This is basically just * so we can have a custom location for key stores. */ public SSLContext getSSLContext(String keyStoreName, String password) throws IOException { try { // Check the key manager factory KeyManagerFactory kmf = KeyManagerFactory.getInstance(this.keyManagerType); File ksFile = new File(keyStoreName); if (!ksFile.exists() || !ksFile.isFile()) throw new WinstoneException( SSL_RESOURCES.getString("HttpsListener.KeyStoreNotFound", ksFile.getPath())); InputStream in = new FileInputStream(ksFile); char[] passwordChars = password == null ? null : password.toCharArray(); KeyStore ks = KeyStore.getInstance("JKS"); ks.load(in, passwordChars); kmf.init(ks, passwordChars); Logger.log(Logger.FULL_DEBUG, SSL_RESOURCES, "HttpsListener.KeyCount", ks.size() + ""); for (Enumeration e = ks.aliases(); e.hasMoreElements(); ) { String alias = (String) e.nextElement(); Logger.log( Logger.FULL_DEBUG, SSL_RESOURCES, "HttpsListener.KeyFound", new String[] {alias, ks.getCertificate(alias) + ""}); } SSLContext context = SSLContext.getInstance("SSL"); context.init(kmf.getKeyManagers(), null, null); Arrays.fill(passwordChars, 'x'); return context; } catch (IOException err) { throw err; } catch (Throwable err) { throw new WinstoneException( SSL_RESOURCES.getString("HttpsListener.ErrorGettingContext"), err); } }