Java Examples for javax.net.ssl.KeyManagerFactory
The following java examples will help you to understand the usage of javax.net.ssl.KeyManagerFactory. These source code samples are taken from different open source projects.
Example 1
| Project: Android-tcp-long-connection-based-on-Apache-mina-master File: BogusSslContextFactory.java View source code |
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;
}Example 2
| Project: simpleframework-master File: KeyStoreManager.java View source code |
public KeyManager[] getKeyManagers(InputStream keyStoreSource, String keyStorePassword, String keyManagerPassword) throws Exception {
KeyStore keyStore = keyStoreType.getKeyStore();
KeyManagerFactory keyManagerFactory = keyStoreType.getKeyManagerFactory();
keyStore.load(keyStoreSource, keyManagerPassword.toCharArray());
keyManagerFactory.init(keyStore, keyManagerPassword.toCharArray());
return keyManagerFactory.getKeyManagers();
}Example 3
| Project: javardices-master File: HttpSslContext.java View source code |
public javax.net.ssl.SSLContext getSSLContext() throws Exception {
KeyStore keyStore = KeyStore.getInstance("JKS");
char[] KEYSTOREPW = keyStorePasswordStr.toCharArray();
char[] KEYPW = keyPasswordStr.toCharArray();
keyStore.load(new FileInputStream(keyStoreLocation), KEYSTOREPW);
javax.net.ssl.KeyManagerFactory kmf = javax.net.ssl.KeyManagerFactory.getInstance("SunX509");
kmf.init(keyStore, KEYPW);
//javax.net.ssl.SSLContext sslContext = javax.net.ssl.SSLContext.getInstance("SSLv3");
javax.net.ssl.SSLContext sslContext = javax.net.ssl.SSLContext.getInstance("TLS");
sslContext.init(kmf.getKeyManagers(), null, null);
return sslContext;
}Example 4
| Project: coprhd-controller-master File: PermissiveX509KeyManager.java View source code |
public KeyManager[] getPermissiveX509KeyManager() throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException, GeneralSecurityException {
KeyStore keyStore;
keyStore = KeyStore.getInstance(System.getProperty("javax.net.ssl.keyStoreType"));
FileInputStream ksfis = new FileInputStream(System.getProperty("javax.net.ssl.keyStore"));
char[] kspasswd = System.getProperty("javax.net.ssl.keyStorePassword").toCharArray();
keyStore.load(ksfis, kspasswd);
KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
kmf.init(keyStore, kspasswd);
return kmf.getKeyManagers();
}Example 5
| Project: ForgeEssentials-master File: SSLContextHelper.java View source code |
public void loadSSLCertificate(InputStream keystore, String storepass, String keypass) throws IOException, GeneralSecurityException {
if (keystore == null)
throw new IOException("Invalid keystore");
// Load KeyStore
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(keystore, storepass.toCharArray());
// Init KeyManager
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks, keypass.toCharArray());
// Init TrustManager
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
// Init SSLContext
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
sslCtx = ctx;
}Example 6
| Project: ssl_npn-master File: SSLContextCreator.java View source code |
public static SSLContext newContext() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, CertificateException, FileNotFoundException, IOException, UnrecoverableKeyException {
KeyStore store = KeyStore.getInstance("PKCS12");
FileInputStream stream = new FileInputStream("server.pkcs12");
try {
store.load(stream, "test123".toCharArray());
} finally {
stream.close();
}
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(store, "test123".toCharArray());
SSLContext context = SSLContext.getInstance("TLSv1.2", new sslnpn.net.ssl.internal.ssl.Provider());
context.init(kmf.getKeyManagers(), new TrustManager[] { new NaiveTrustManager() }, new SecureRandom());
return context;
}Example 7
| Project: webpie-master File: SelfSignedSSLEngineFactory.java View source code |
@Override
public SSLEngine createSslEngine(String host) {
try {
this.cachedHost = host;
// 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(serverKeystore), passphrase);
SSLContext sslContext = SSLContext.getInstance("TLS");
//****************Server side specific*********************
// KeyManager's decide which key material to use.
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, passphrase);
sslContext.init(kmf.getKeyManagers(), null, null);
//****************Server side specific*********************
SSLEngine engine = sslContext.createSSLEngine();
engine.setUseClientMode(false);
return engine;
} catch (Exception e) {
throw new RuntimeException(e);
}
}Example 8
| Project: hk-master File: CryptoHooker.java View source code |
/** * Attach on KeyManagerFactory class */ private void attachOnKeyManagerFactoryClass() { Map<String, Integer> methodsToHook = new HashMap<String, Integer>(); methodsToHook.put("getAlgorithm", 0); methodsToHook.put("getInstance", 0); methodsToHook.put("init", 0); try { hookMethods(null, "javax.net.ssl.KeyManagerFactory", methodsToHook); SubstrateMain.log("hooking javax.net.ssl.KeyManagerFactory methods sucessful"); } catch (HookerInitializationException e) { SubstrateMain.log("hooking javax.net.ssl.KeyManagerFactory methods has failed", e); } }
Example 9
| Project: JBossAS51-master File: Context.java View source code |
/*
* Returns an initialized JSSE SSLContext that uses the KeyManagerFactory
* and TrustManagerFactory objects encapsulated by a given JBossSX
* SecurityDomain.
*/
static SSLContext forDomain(SecurityDomain securityDomain) throws IOException {
SSLContext sslCtx = null;
try {
sslCtx = SSLContext.getInstance("TLS");
KeyManagerFactory keyMgr = securityDomain.getKeyManagerFactory();
if (keyMgr == null)
throw new IOException("KeyManagerFactory is null for security domain: " + securityDomain.getSecurityDomain());
TrustManagerFactory trustMgr = securityDomain.getTrustManagerFactory();
TrustManager[] trustMgrs = null;
if (trustMgr != null)
trustMgrs = trustMgr.getTrustManagers();
sslCtx.init(keyMgr.getKeyManagers(), trustMgrs, null);
return sslCtx;
} catch (NoSuchAlgorithmException e) {
log.error("Failed to get SSLContext for TLS algorithm", e);
throw new IOException("Failed to get SSLContext for TLS algorithm");
} catch (KeyManagementException e) {
log.error("Failed to init SSLContext", e);
throw new IOException("Failed to init SSLContext");
} catch (SecurityException e) {
log.error("Failed to init SSLContext", e);
throw new IOException("Failed to init SSLContext");
}
}Example 10
| Project: JBossAS_5_1_EDG-master File: Context.java View source code |
/*
* Returns an initialized JSSE SSLContext that uses the KeyManagerFactory
* and TrustManagerFactory objects encapsulated by a given JBossSX
* SecurityDomain.
*/
static SSLContext forDomain(SecurityDomain securityDomain) throws IOException {
SSLContext sslCtx = null;
try {
sslCtx = SSLContext.getInstance("TLS");
KeyManagerFactory keyMgr = securityDomain.getKeyManagerFactory();
if (keyMgr == null)
throw new IOException("KeyManagerFactory is null for security domain: " + securityDomain.getSecurityDomain());
TrustManagerFactory trustMgr = securityDomain.getTrustManagerFactory();
TrustManager[] trustMgrs = null;
if (trustMgr != null)
trustMgrs = trustMgr.getTrustManagers();
sslCtx.init(keyMgr.getKeyManagers(), trustMgrs, null);
return sslCtx;
} catch (NoSuchAlgorithmException e) {
log.error("Failed to get SSLContext for TLS algorithm", e);
throw new IOException("Failed to get SSLContext for TLS algorithm");
} catch (KeyManagementException e) {
log.error("Failed to init SSLContext", e);
throw new IOException("Failed to init SSLContext");
} catch (SecurityException e) {
log.error("Failed to init SSLContext", e);
throw new IOException("Failed to init SSLContext");
}
}Example 11
| Project: Android-Templates-And-Utilities-master File: SelfSignedSSLUtility.java View source code |
public static SSLContext createSSLContext() throws GeneralSecurityException {
KeyStore keyStore = loadKeyStore();
SelfSignedTrustManager selfSignedTrustManager = new SelfSignedTrustManager(keyStore);
TrustManager[] tms = new TrustManager[] { selfSignedTrustManager };
KeyManager[] kms = null;
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(keyStore, ExampleConfig.SSL_KEYSTORE_PASSWORD.toCharArray());
kms = kmf.getKeyManagers();
SSLContext context = SSLContext.getInstance("TLS");
context.init(kms, tms, new SecureRandom());
return context;
}Example 12
| Project: AndroidAsync-master File: SSLTests.java View source code |
public void testKeys() throws Exception {
KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(getContext().getResources().openRawResource(R.raw.keystore), "storepass".toCharArray());
kmf.init(ks, "storepass".toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
KeyStore ts = KeyStore.getInstance(KeyStore.getDefaultType());
ts.load(getContext().getResources().openRawResource(R.raw.keystore), "storepass".toCharArray());
tmf.init(ts);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
AsyncHttpServer httpServer = new AsyncHttpServer();
httpServer.listenSecure(8888, sslContext);
httpServer.get("/", new HttpServerRequestCallback() {
@Override
public void onRequest(AsyncHttpServerRequest request, AsyncHttpServerResponse response) {
response.send("hello");
}
});
Thread.sleep(1000);
AsyncHttpClient.getDefaultInstance().getSSLSocketMiddleware().setSSLContext(sslContext);
AsyncHttpClient.getDefaultInstance().getSSLSocketMiddleware().setTrustManagers(tmf.getTrustManagers());
AsyncHttpClient.getDefaultInstance().executeString(new AsyncHttpGet("https://localhost:8888/"), null).get();
}Example 13
| Project: Bingo-master File: HttpsCoder.java View source code |
private static SSLSocketFactory getSSLSocketFactory(InputStream keyStoreInputStream, String password) throws Exception {
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
KeyStore keyStore = getKeyStore(keyStoreInputStream, password);
keyManagerFactory.init(keyStore, password.toCharArray());
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
SSLContext context = SSLContext.getInstance(PROTOCOL);
context.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
keyStoreInputStream.close();
return context.getSocketFactory();
}Example 14
| Project: channelmanager2-master File: MockSSLEngineFactory.java View source code |
public SSLEngine createEngineForServerSocket() throws GeneralSecurityException, IOException {
// 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(serverKeystore), passphrase);
SSLContext sslContext = SSLContext.getInstance("TLS");
//****************Server side specific*********************
// KeyManager's decide which key material to use.
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, passphrase);
sslContext.init(kmf.getKeyManagers(), null, null);
//****************Server side specific*********************
SSLEngine engine = sslContext.createSSLEngine();
engine.setUseClientMode(false);
return engine;
}Example 15
| Project: commons-eid-master File: BeIDSocketFactory.java View source code |
public static SSLSocketFactory getSSLSocketFactory() throws NoSuchAlgorithmException, KeyManagementException {
if (BeIDSocketFactory.socketFactorSingleton == null) {
final SSLContext sslContext = SSLContext.getInstance("TLS");
final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("BeID");
sslContext.init(keyManagerFactory.getKeyManagers(), null, SecureRandom.getInstance("BeID"));
socketFactorSingleton = sslContext.getSocketFactory();
}
return socketFactorSingleton;
}Example 16
| Project: cpush-apns-master File: SecureSslContextFactory.java View source code |
public static SSLContext getSSLContext(Credentials conf) {
SSLContext clientContext = CLIENT_CONTEXT.get(conf);
if (clientContext == null) {
try {
String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
if (algorithm == null) {
algorithm = "SunX509";
}
KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(new ByteArrayInputStream(conf.getCertification()), conf.getPassword().toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
kmf.init(keyStore, conf.getPassword().toCharArray());
clientContext = SSLContext.getInstance(PROTOCOL);
clientContext.init(kmf.getKeyManagers(), new TrustManager[] { new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
throw new CertificateException("Client is not trusted.");
}
} }, null);
CLIENT_CONTEXT.putIfAbsent(conf, clientContext);
} catch (Exception e) {
e.printStackTrace();
}
}
return clientContext;
}Example 17
| Project: dse_driver_examples-master File: TestSSL.java View source code |
private static SSLContext getSSLContext(String truststorePath, String truststorePassword, String keystorePath, String keystorePassword) throws Exception {
FileInputStream tsf = new FileInputStream(truststorePath);
FileInputStream ksf = new FileInputStream(keystorePath);
SSLContext ctx = SSLContext.getInstance("SSL");
KeyStore ts = KeyStore.getInstance("JKS");
ts.load(tsf, truststorePassword.toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ts);
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(ksf, keystorePassword.toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks, keystorePassword.toCharArray());
ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
return ctx;
}Example 18
| Project: flashback-master File: SSLContextGenerator.java View source code |
/**
* Create client side SSLContext {@link javax.net.ssl.SSLContext}
*
* */
public static SSLContext createClientContext(KeyStore keyStore, char[] passphrase) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
String keyManAlg = KeyManagerFactory.getDefaultAlgorithm();
KeyManagerFactory kmf = KeyManagerFactory.getInstance(keyManAlg);
kmf.init(keyStore, passphrase);
KeyManager[] keyManagers = kmf.getKeyManagers();
return create(keyManagers, InsecureTrustManagerFactory.INSTANCE.getTrustManagers(), RandomNumberGenerator.getInstance().getSecureRandom());
}Example 19
| Project: ion-master File: SelfSignedCertificateTests.java View source code |
public void testKeys() throws Exception {
KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(getContext().getResources().openRawResource(R.raw.keystore), "storepass".toCharArray());
kmf.init(ks, "storepass".toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
KeyStore ts = KeyStore.getInstance(KeyStore.getDefaultType());
ts.load(getContext().getResources().openRawResource(R.raw.keystore), "storepass".toCharArray());
tmf.init(ts);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
AsyncHttpServer httpServer = new AsyncHttpServer();
httpServer.listenSecure(8888, sslContext);
httpServer.get("/", new HttpServerRequestCallback() {
@Override
public void onRequest(AsyncHttpServerRequest request, AsyncHttpServerResponse response) {
response.send("hello");
}
});
Thread.sleep(1000);
Ion ion = Ion.getInstance(getContext(), "CustomSSL");
ion.getHttpClient().getSSLSocketMiddleware().setSSLContext(sslContext);
ion.getHttpClient().getSSLSocketMiddleware().setTrustManagers(tmf.getTrustManagers());
ion.build(getContext()).load("https://localhost:8888/").asString().get();
}Example 20
| Project: JAVA_ISDS-master File: ClientCertAuthentication.java View source code |
@Override
protected SSLSocketFactory createSSLSocketFactory() throws DataBoxException {
try {
// System.setProperty("https.protocols", "SSLv3");
// System.setProperty("javax.net.debug", "all");
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
KeyStore keyStore = KeyStore.getInstance("PKCS12");
// KeyStore keyStore = Utils.createTrustStore();
InputStream keyInput = new FileInputStream(certFile);
keyStore.load(keyInput, certPassword.toCharArray());
keyInput.close();
keyManagerFactory.init(keyStore, certPassword.toCharArray());
SSLContext context = SSLContext.getInstance("TLS");
context.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom());
return context.getSocketFactory();
} catch (Exception ex) {
if (ex instanceof RuntimeException) {
throw (RuntimeException) ex;
} else {
throw new DataBoxException("Can't create SSLSocketFactory.", ex);
}
}
}Example 21
| Project: keycloak-master File: SslUtil.java View source code |
public static SSLContext createSSLContext(final KeyStore keyStore, String password, final KeyStore trustStore) throws Exception {
KeyManager[] keyManagers;
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, password.toCharArray());
keyManagers = keyManagerFactory.getKeyManagers();
TrustManager[] trustManagers = null;
if (trustStore != null) {
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(trustStore);
trustManagers = trustManagerFactory.getTrustManagers();
}
SSLContext sslContext;
sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagers, trustManagers, null);
return sslContext;
}Example 22
| Project: Pin-Fever-Android-master File: SelfSignedCertificateTests.java View source code |
public void testKeys() throws Exception {
KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(getContext().getResources().openRawResource(R.raw.keystore), "storepass".toCharArray());
kmf.init(ks, "storepass".toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
KeyStore ts = KeyStore.getInstance(KeyStore.getDefaultType());
ts.load(getContext().getResources().openRawResource(R.raw.keystore), "storepass".toCharArray());
tmf.init(ts);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
AsyncHttpServer httpServer = new AsyncHttpServer();
httpServer.listenSecure(8888, sslContext);
httpServer.get("/", new HttpServerRequestCallback() {
@Override
public void onRequest(AsyncHttpServerRequest request, AsyncHttpServerResponse response) {
response.send("hello");
}
});
Thread.sleep(1000);
Ion ion = Ion.getInstance(getContext(), "CustomSSL");
ion.getHttpClient().getSSLSocketMiddleware().setSSLContext(sslContext);
ion.getHttpClient().getSSLSocketMiddleware().setTrustManagers(tmf.getTrustManagers());
ion.build(getContext()).load("https://localhost:8888/").asString().get();
}Example 23
| Project: polly-master File: SSLServerFactory.java View source code |
@Override
public com.sun.net.httpserver.HttpServer create() throws IOException {
SSLContext context;
KeyManagerFactory kmf;
KeyStore ks;
try {
//$NON-NLS-1$
context = SSLContext.getInstance("SSLv3");
//$NON-NLS-1$
kmf = KeyManagerFactory.getInstance("SunX509");
//$NON-NLS-1$
ks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream(this.keyStore), this.keyStorePw.toCharArray());
kmf.init(ks, this.keyPw.toCharArray());
context.init(kmf.getKeyManagers(), null, null);
} catch (Exception e) {
throw new IOException(e);
}
final HttpsServer server = HttpsServer.create(new InetSocketAddress(this.port), 5);
final HttpsConfigurator configurator = new HttpsConfigurator(context) {
@Override
public void configure(HttpsParameters params) {
final SSLContext context = this.getSSLContext();
params.setSSLParameters(context.getDefaultSSLParameters());
}
};
server.setHttpsConfigurator(configurator);
server.setExecutor(this.executor);
return server;
}Example 24
| Project: rtmp-rtsp-stream-client-java-master File: CreateSSLSocket.java View source code |
/**
*
* @param keyStore created with createKeyStore()
* @param host variable from RtspClient
* @param port variable from RtspClient
* @return
*/
public static Socket createSSlSocket(KeyStore keyStore, String host, int port) {
try {
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
return sslContext.getSocketFactory().createSocket(host, port);
} catch (KeyStoreException e) {
e.printStackTrace();
return null;
} catch (NoSuchAlgorithmExceptionIOException | e) {
e.printStackTrace();
return null;
} catch (KeyManagementException e) {
e.printStackTrace();
}
return null;
}Example 25
| Project: sissi-master File: CertificateContextBuilder.java View source code |
private KeyManager[] getKeyManagers(Certificate key) throws Exception {
KeyManagerFactory factory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
InputStream certificate = key.getFile().openStream();
try {
KeyStore ks = KeyStore.getInstance(this.keystore);
ks.load(certificate, key.getPassword());
factory.init(ks, key.getPassword());
} finally {
IOUtil.closeQuietly(certificate);
}
return factory.getKeyManagers();
}Example 26
| Project: tinify-java-master File: SSLContext.java View source code |
public static SSLSocketFactory getSocketFactory() {
try {
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(certificateStream());
KeyStore keyStore = newEmptyKeyStore();
int index = 0;
for (Certificate certificate : certificates) {
String certificateAlias = Integer.toString(index++);
keyStore.setCertificateEntry(certificateAlias, certificate);
}
if (keyStore.size() == 0) {
/* The resource stream was empty, no certificates were found. */
throw new ConnectionException("Unable to load any CA certificates.", null);
}
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, null);
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
javax.net.ssl.SSLContext sslContext = javax.net.ssl.SSLContext.getInstance("TLS");
sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
return sslContext.getSocketFactory();
} catch (GeneralSecurityExceptionIOException | e) {
throw new ConnectionException("Error while loading trusted CA certificates.", e);
}
}Example 27
| Project: TLSDemo-master File: TLSApplicaton.java View source code |
@Override
public void onCreate() {
super.onCreate();
try {
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
Log.e(TAG, "TrustManagerFacotry default algorithm: " + tmfAlgorithm);
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init((KeyStore) null);
TrustManager[] tms = tmf.getTrustManagers();
for (TrustManager tm : tms) {
if (tm instanceof X509TrustManager) {
X509Certificate[] certs = ((X509TrustManager) tm).getAcceptedIssuers();
/*for (X509Certificate cert : certs) {
Log.e(TAG, "--------------");
Log.e(TAG, cert.toString());
Log.e(TAG, "--------------");
}*/
}
}
String kmfAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
Log.e(TAG, "KeyManagerFactory default algorithm: " + kmfAlgorithm);
KeyManagerFactory kmf = KeyManagerFactory.getInstance(kmfAlgorithm);
kmf.init(null, null);
KeyManager[] kms = kmf.getKeyManagers();
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tms, null);
Log.e(TAG, "Keystore algorithm: " + KeyStore.getDefaultType());
mDefaultSSF = sslContext.getSocketFactory();
if (mDefaultSSF == null) {
Log.e(TAG, "SSLContext getSocketFactory is null");
}
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (UnrecoverableKeyException e) {
e.printStackTrace();
}
sApplication = this;
}Example 28
| Project: usercenter-master File: KeyStoreKeyManager.java View source code |
private static KeyManager[] getKeyManagers(final String keyStoreFile, final char[] keyStorePIN, final String keyStoreFormat) throws KeyStoreException {
ensureNotNull(keyStoreFile);
String type = keyStoreFormat;
if (type == null) {
type = KeyStore.getDefaultType();
}
final File f = new File(keyStoreFile);
if (!f.exists()) {
throw new KeyStoreException(ERR_KEYSTORE_NO_SUCH_FILE.get(keyStoreFile));
}
final KeyStore ks = KeyStore.getInstance(type);
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(f);
ks.load(inputStream, keyStorePIN);
} catch (Exception e) {
debugException(e);
throw new KeyStoreException(ERR_KEYSTORE_CANNOT_LOAD.get(keyStoreFile, type, String.valueOf(e)), e);
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (Exception e) {
debugException(e);
}
}
}
try {
final KeyManagerFactory factory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
factory.init(ks, keyStorePIN);
return factory.getKeyManagers();
} catch (Exception e) {
debugException(e);
throw new KeyStoreException(ERR_KEYSTORE_CANNOT_GET_KEY_MANAGERS.get(keyStoreFile, keyStoreFormat, String.valueOf(e)), e);
}
}Example 29
| Project: webbit-master File: SslFactory.java View source code |
public SSLContext getServerContext(String keyPass) throws WebbitException {
try {
// Set up key manager factory to use our key store
String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
if (algorithm == null)
algorithm = "SunX509";
KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
kmf.init(ks, keyPass.toCharArray());
// Initialize the SSLContext to work with our key managers.
SSLContext sslContext = SSLContext.getInstance(PROTOCOL);
sslContext.init(kmf.getKeyManagers(), null, null);
return sslContext;
} catch (Exception e) {
throw new WebbitException(e);
}
}Example 30
| Project: wso2-synapse-master File: IdentityKeyStoreInformation.java View source code |
/**
* Returns the IdentityKeyManagerFactory instance
*
* @return IdentityKeyManagerFactory instance
*/
public KeyManagerFactory getIdentityKeyManagerFactoryInstance() {
try {
if (log.isDebugEnabled()) {
log.debug("Creating a IdentityKeyManagerFactory instance");
}
KeyStore keyStore = this.getIdentityKeyStore();
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, keyPasswordProvider.getResolvedSecret().toCharArray());
return keyManagerFactory;
} catch (Exception e) {
handleException("Error getting KeyManagerFactory: ", e);
}
return null;
}Example 31
| Project: androidpn-master File: SSLKeyManagerFactory.java View source code |
public static KeyManager[] getKeyManagers(String storeType, String keystore, String keypass) throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException, UnrecoverableKeyException {
KeyManager[] keyManagers;
if (keystore == null) {
keyManagers = null;
} else {
if (keypass == null) {
keypass = "";
}
KeyStore keyStore = KeyStore.getInstance(storeType);
keyStore.load(new FileInputStream(keystore), keypass.toCharArray());
KeyManagerFactory keyFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyFactory.init(keyStore, keypass.toCharArray());
keyManagers = keyFactory.getKeyManagers();
}
return keyManagers;
}Example 32
| Project: androidpn-server-app-master File: SSLKeyManagerFactory.java View source code |
public static KeyManager[] getKeyManagers(String storeType, String keystore, String keypass) throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException, UnrecoverableKeyException {
KeyManager[] keyManagers;
if (keystore == null) {
keyManagers = null;
} else {
if (keypass == null) {
keypass = "";
}
KeyStore keyStore = KeyStore.getInstance(storeType);
keyStore.load(new FileInputStream(keystore), keypass.toCharArray());
KeyManagerFactory keyFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyFactory.init(keyStore, keypass.toCharArray());
keyManagers = keyFactory.getKeyManagers();
}
return keyManagers;
}Example 33
| Project: apiman-master File: KeyStoreUtil.java View source code |
/**
* Gets the array of key managers for a given info store+info.
*
* @param pathInfo
* @throws Exception
*/
public static KeyManager[] getKeyManagers(Info pathInfo) throws Exception {
if (pathInfo.store == null) {
return null;
}
File clientKeyStoreFile = new File(pathInfo.store);
if (!clientKeyStoreFile.isFile()) {
throw new Exception("No KeyManager: " + pathInfo.store + " does not exist or is not a file.");
}
String clientKeyStorePassword = pathInfo.password;
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
KeyStore keyStore = KeyStore.getInstance("JKS");
FileInputStream clientFis = new FileInputStream(pathInfo.store);
keyStore.load(clientFis, clientKeyStorePassword.toCharArray());
clientFis.close();
kmf.init(keyStore, clientKeyStorePassword.toCharArray());
return kmf.getKeyManagers();
}Example 34
| Project: arangodb-java-driver-master File: ArangoSslTest.java View source code |
@Test
@Ignore
public void connect() throws Exception {
final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(this.getClass().getResourceAsStream(SSL_TRUSTSTORE), SSL_TRUSTSTORE_PASSWORD.toCharArray());
final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks, SSL_TRUSTSTORE_PASSWORD.toCharArray());
final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
final SSLContext sc = SSLContext.getInstance("TLS");
sc.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
final ArangoDB arangoDB = new ArangoDB.Builder().port(8530).useSsl(true).sslContext(sc).build();
final ArangoDBVersion version = arangoDB.getVersion();
assertThat(version, is(notNullValue()));
}Example 35
| Project: ARTPart-master File: X509KeyManagerTest.java View source code |
private void test_ChooseClientAlias_KeyType(String clientKeyType, String caKeyType, String selectedKeyType, boolean succeeds) throws Exception {
TestKeyStore ca = new TestKeyStore.Builder().keyAlgorithms(caKeyType).build();
TestKeyStore client = new TestKeyStore.Builder().keyAlgorithms(clientKeyType).signer(ca.getPrivateKey(caKeyType, caKeyType)).build();
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(client.keyStore, client.keyPassword);
String[] keyTypes = new String[] { selectedKeyType };
KeyManager[] managers = kmf.getKeyManagers();
for (KeyManager manager : managers) {
if (manager instanceof X509KeyManager) {
String alias = ((X509KeyManager) manager).chooseClientAlias(keyTypes, null, null);
if (succeeds) {
assertNotNull(alias);
} else {
assertNull(alias);
}
}
}
}Example 36
| Project: aws-sdk-android-master File: AWSIotSslUtility.java View source code |
/**
* Creates a socket factory given a keystore.
*
* @param keyStore keystore containing a certificate and private key for
* used in creating a secured socket.
* @return a socket factory for use in creating a secured socket.
* @throws NoSuchAlgorithmException when TLS 1.2 is not available.
* @throws UnrecoverableKeyException when the private key cannot be
* recovered. Ususally a bad keystore password.
* @throws KeyStoreException when keystore cannot be created.
* @throws KeyManagementException when SSL context cannot be created by key
* manager.
*/
public static SSLSocketFactory getSocketFactoryWithKeyStore(KeyStore keyStore) throws NoSuchAlgorithmException, UnrecoverableKeyException, KeyStoreException, KeyManagementException {
SSLContext context = SSLContext.getInstance("TLSv1.2");
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(keyStore, AWSIotKeystoreHelper.AWS_IOT_INTERNAL_KEYSTORE_PASSWORD.toCharArray());
KeyManager[] km = kmf.getKeyManagers();
context.init(km, null, new SecureRandom());
return new AWSIotTLSSocketFactory(context.getSocketFactory());
}Example 37
| Project: BansheeCore-master File: SSLSocketFactoryGenerator.java View source code |
private KeyManager[] getKeyManagers(InputStream keyStoreStream, String keyStorePassword) throws GeneralSecurityException, IOException {
try {
KeyManagerFactory factory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(keyStoreStream, keyStorePassword.toCharArray());
factory.init(keyStore, keyStorePassword.toCharArray());
KeyManager[] managers = factory.getKeyManagers();
return managers;
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}Example 38
| Project: bc-java-master File: CipherSuitesTestCase.java View source code |
public Exception call() throws Exception {
try {
KeyManagerFactory keyMgrFact = KeyManagerFactory.getInstance("PKIX", BouncyCastleJsseProvider.PROVIDER_NAME);
keyMgrFact.init(config.serverKeyStore, config.serverPassword);
SSLContext serverContext = SSLContext.getInstance("TLS", BouncyCastleJsseProvider.PROVIDER_NAME);
serverContext.init(keyMgrFact.getKeyManagers(), null, SecureRandom.getInstance("DEFAULT", BouncyCastleProvider.PROVIDER_NAME));
SSLServerSocketFactory fact = serverContext.getServerSocketFactory();
SSLServerSocket sSock = (SSLServerSocket) fact.createServerSocket(port);
sSock.setEnabledCipherSuites(new String[] { config.cipherSuite });
latch.countDown();
SSLSocket sslSock = (SSLSocket) sSock.accept();
sslSock.setUseClientMode(false);
this.tlsUnique = TestUtils.getChannelBinding(sslSock, "tls-unique");
TestProtocolUtil.doServerProtocol(sslSock, "World");
sslSock.close();
sSock.close();
} finally {
latch.countDown();
}
return null;
}Example 39
| Project: camel-master File: AbstractJsseParametersTest.java View source code |
protected CamelContext createPropertiesPlaceholderAwareContext() throws Exception {
Properties supplementalProperties = new Properties();
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
SecureRandom sr = null;
try {
sr = SecureRandom.getInstance("SHA1PRNG");
} catch (NoSuchAlgorithmException e) {
}
SSLContext sslc = SSLContext.getInstance("TLS");
sslc.init(null, null, null);
SSLSocket socket = (SSLSocket) sslc.getSocketFactory().createSocket();
supplementalProperties.setProperty("keyStoreParameters.type", KeyStore.getDefaultType());
supplementalProperties.setProperty("keyStoreParameters.provider", ks.getProvider().getName());
supplementalProperties.setProperty("keyManagersParameters.algorithm", KeyManagerFactory.getDefaultAlgorithm());
supplementalProperties.setProperty("keyManagersParameters.provider", kmf.getProvider().getName());
supplementalProperties.setProperty("trustManagersParameters.algorithm", TrustManagerFactory.getDefaultAlgorithm());
supplementalProperties.setProperty("trustManagersParameters.provider", tmf.getProvider().getName());
if (sr != null) {
supplementalProperties.setProperty("secureRandomParameters.algorithm", "SHA1PRNG");
supplementalProperties.setProperty("secureRandomParameters.provider", sr.getProvider().getName());
}
supplementalProperties.setProperty("sslContextParameters.provider", sslc.getProvider().getName());
supplementalProperties.setProperty("cipherSuite.0", socket.getSupportedCipherSuites()[0]);
// Have to skip this guy because he doesn't work with TLS as the SSLContext protocol
String ssp = "";
for (String protocol : socket.getSupportedProtocols()) {
if (!"SSLv2Hello".equals(protocol)) {
ssp = protocol;
break;
}
}
supplementalProperties.setProperty("secureSocketProtocol.0", ssp);
return this.createPropertiesPlaceholderAwareContext(supplementalProperties);
}Example 40
| Project: cloudify-master File: MicrosoftAzureSSLHelper.java View source code |
/**
*
* @return .
* @throws NoSuchAlgorithmException .
* @throws KeyStoreException .
* @throws CertificateException .
* @throws IOException .
* @throws UnrecoverableKeyException .
* @throws KeyManagementException .
*/
public SSLContext createSSLContext() throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException, UnrecoverableKeyException, KeyManagementException {
InputStream pfxFile = null;
SSLContext context = null;
try {
pfxFile = new FileInputStream(new File(pathToPfxFile));
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(SUN_X_509_ALGORITHM);
KeyStore keyStore = KeyStore.getInstance(KEY_STORE_CONTEXT);
keyStore.load(pfxFile, pfxPassword.toCharArray());
pfxFile.close();
keyManagerFactory.init(keyStore, pfxPassword.toCharArray());
context = SSLContext.getInstance("SSL");
context.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom());
return context;
} finally {
if (pfxFile != null) {
pfxFile.close();
}
}
}Example 41
| Project: couchbase-jvm-core-master File: SSLEngineFactory.java View source code |
/**
* Returns a new {@link SSLEngine} constructed from the config settings.
*
* @return a {@link SSLEngine} ready to be used.
*/
public SSLEngine get() {
try {
String pass = env.sslKeystorePassword();
char[] password = pass == null || pass.isEmpty() ? null : pass.toCharArray();
KeyStore ks = env.sslKeystore();
if (ks == null) {
ks = KeyStore.getInstance(KeyStore.getDefaultType());
String ksFile = env.sslKeystoreFile();
if (ksFile == null || ksFile.isEmpty()) {
throw new IllegalArgumentException("Path to Keystore File must not be null or empty.");
}
ks.load(new FileInputStream(ksFile), password);
}
String defaultAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
KeyManagerFactory kmf = KeyManagerFactory.getInstance(defaultAlgorithm);
TrustManagerFactory tmf = TrustManagerFactory.getInstance(defaultAlgorithm);
kmf.init(ks, password);
tmf.init(ks);
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
SSLEngine engine = ctx.createSSLEngine();
engine.setUseClientMode(true);
return engine;
} catch (Exception ex) {
throw new SSLException("Could not create SSLEngine.", ex);
}
}Example 42
| Project: cxf-master File: TrustServerNoSpring.java View source code |
protected void run() {
Bus busLocal = BusFactory.getDefaultBus(true);
setBus(busLocal);
String address = "https://localhost:" + TrustManagerTest.PORT3 + "/SoapContext/HttpsPort";
try {
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(ClassLoaderUtils.getResourceAsStream("keys/Bethal.jks", this.getClass()), "password".toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(keyStore, "password".toCharArray());
TLSServerParameters tlsParams = new TLSServerParameters();
tlsParams.setKeyManagers(kmf.getKeyManagers());
ClientAuthentication clientAuthentication = new ClientAuthentication();
clientAuthentication.setRequired(false);
clientAuthentication.setWant(true);
tlsParams.setClientAuthentication(clientAuthentication);
Map<String, TLSServerParameters> map = new HashMap<>();
map.put("tlsId", tlsParams);
JettyHTTPServerEngineFactory factory = busLocal.getExtension(JettyHTTPServerEngineFactory.class);
factory.setTlsServerParametersMap(map);
factory.createJettyHTTPServerEngine("localhost", Integer.parseInt(TrustManagerTest.PORT3), "https", "tlsId");
factory.initComplete();
} catch (Exception ex) {
ex.printStackTrace();
}
Endpoint.publish(address, new GreeterImpl());
}Example 43
| Project: dc---master File: HTTPSServerThread.java View source code |
SSLContext createSSLContext() throws Exception {
KeyManagerFactory mgrFact = KeyManagerFactory.getInstance("SunX509");
KeyStore serverStore = KeyStore.getInstance("JKS");
serverStore.load(new ByteArrayInputStream(KeyStores.server), SERVER_PASSWORD);
mgrFact.init(serverStore, SERVER_PASSWORD);
// set up a trust manager so we can recognize the server
TrustManagerFactory trustFact = TrustManagerFactory.getInstance("SunX509");
KeyStore trustStore = KeyStore.getInstance("JKS");
trustStore.load(new ByteArrayInputStream(KeyStores.trustStore), TRUST_STORE_PASSWORD);
trustFact.init(trustStore);
// create a context and set up a socket factory
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(mgrFact.getKeyManagers(), trustFact.getTrustManagers(), null);
return sslContext;
}Example 44
| Project: divconq-master File: SslContextFactory.java View source code |
public static void init(XElement config) {
if (config == null)
return;
BusTrustManager tm = new BusTrustManager();
tm.init(config);
TrustManager[] trustManagers = new TrustManager[] { tm };
XElement sslconfig = config.selectFirst("SslContext");
if (sslconfig != null) {
String algorithm = sslconfig.getAttribute("Algorithm", "SunX509");
String protocol = sslconfig.getAttribute("Protocol", "TLSv1.2");
String jksfile = sslconfig.getAttribute("File");
String jkspass = null;
ISettingsObfuscator ob = Hub.instance.getClock().getObfuscator();
if (ob != null)
jkspass = ob.decryptHexToString(sslconfig.getAttribute("Password"));
if (jkspass == null)
jkspass = sslconfig.getAttribute("Password");
if (StringUtil.isNotEmpty(jksfile))
try {
// load keystore
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream(jksfile), jkspass.toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
kmf.init(ks, jkspass.toCharArray());
// init server context
SSLContext serverContext = SSLContext.getInstance(protocol);
serverContext.init(kmf.getKeyManagers(), trustManagers, null);
SslContextFactory.ServerContext = serverContext;
// init client context
SSLContext clientContext = SSLContext.getInstance(protocol);
clientContext.init(kmf.getKeyManagers(), trustManagers, null);
SslContextFactory.ClientContext = clientContext;
} catch (Exception x) {
throw new Error("Failed to initialize the SSLContext", x);
}
}
}Example 45
| Project: drftpd-master File: SSLGetContext.java View source code |
public static SSLContext getSSLContext() throws GeneralSecurityException, IOException {
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
}
} };
if (ctx != null)
// reuse previous SSLContext
return ctx;
ctx = SSLContext.getInstance("TLS");
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
KeyStore ks = KeyStore.getInstance("JKS");
FileInputStream fis = null;
try {
fis = new FileInputStream("drftpd.key");
ks.load(fis, "drftpd".toCharArray());
} finally {
if (fis != null) {
fis.close();
}
}
kmf.init(ks, "drftpd".toCharArray());
ctx.init(kmf.getKeyManagers(), trustAllCerts, null);
String[] ciphers = ctx.createSSLEngine().getSupportedCipherSuites();
logger.info("Supported ciphers are as follows:");
for (int x = 0; x < ciphers.length; x++) {
logger.info(ciphers[x]);
}
/* for (String cipher : ciphers) {
logger.info(cipher);
}
*/
return ctx;
}Example 46
| Project: drftpd3-extended-master File: SSLGetContext.java View source code |
public static SSLContext getSSLContext() throws GeneralSecurityException, IOException {
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
}
} };
if (ctx != null)
// reuse previous SSLContext
return ctx;
ctx = SSLContext.getInstance("TLS");
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
KeyStore ks = KeyStore.getInstance("JKS");
FileInputStream fis = null;
try {
fis = new FileInputStream("drftpd.key");
ks.load(fis, "drftpd".toCharArray());
} finally {
if (fis != null) {
fis.close();
}
}
kmf.init(ks, "drftpd".toCharArray());
ctx.init(kmf.getKeyManagers(), trustAllCerts, null);
String[] ciphers = ctx.createSSLEngine().getSupportedCipherSuites();
logger.info("Supported ciphers are as follows:");
for (int x = 0; x < ciphers.length; x++) {
logger.info(ciphers[x]);
}
/* for (String cipher : ciphers) {
logger.info(cipher);
}
*/
return ctx;
}Example 47
| Project: dsys-snio-master File: DemoSSLContext.java View source code |
public static SSLContext getDemoContext() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException, KeyManagementException, IOException {
final char[] password = "password".toCharArray();
// First initialize the key and trust material.
final KeyStore ksKeys = KeyStore.getInstance("JKS");
try (final InputStream in = SSLEchoClient.class.getResourceAsStream("nodes.jks")) {
ksKeys.load(in, password);
}
final KeyStore ksTrust = KeyStore.getInstance("JKS");
try (final InputStream in = SSLEchoClient.class.getResourceAsStream("nodes.jks")) {
ksTrust.load(in, password);
}
// KeyManager's decide which key material to use.
final KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ksKeys, password);
// TrustManager's decide whether to allow connections.
final TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
tmf.init(ksTrust);
final SSLContext context = SSLContext.getInstance("TLS");
context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
return context;
}Example 48
| Project: dz-master File: SSLContextFactory.java View source code |
/**
* Create an SSL context object.
*
* @param protocol Secure protocol. Values that are known to work are:
* {@code SSLv3}, {@code TLS}.
* @param keyStoreName Keystore file name.
* @param password Keystore password.
* @return The SSL context.
* @throws SSLException If there was an SSL related problem.
*/
public static SSLContext createContext(String protocol, String keyStoreName, String password) throws SSLException {
try {
SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
SSLContext ctx = SSLContext.getInstance(protocol);
if (password == null) {
// Whatever...
password = "";
}
char[] passwordArray = new char[password.length()];
for (int idx = 0; idx < password.length(); idx++) {
passwordArray[idx] = password.charAt(idx);
}
FileInputStream keyStoreFile = new FileInputStream(keyStoreName);
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(keyStoreFile, null);
String keyManagementAlgorithm = "SunX509";
KeyManagerFactory km = KeyManagerFactory.getInstance(keyManagementAlgorithm);
km.init(ks, passwordArray);
KeyManager[] keyManagerSet = km.getKeyManagers();
for (int i = 0; i < keyManagerSet.length; i++) {
// System.err.println("KeyManager " + keyManagerSet[i]);
}
TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(keyManagementAlgorithm);
tmFactory.init(ks);
TrustManager[] trustManagerSet = tmFactory.getTrustManagers();
for (int i = 0; i < trustManagerSet.length; i++) {
// System.err.println("TrustManager " + trustManagerSet[i]);
}
ctx.init(keyManagerSet, trustManagerSet, random);
return ctx;
} catch (Throwable t) {
SSLException ex = new SSLException("Can't create secure connection (SSLContext)");
ex.initCause(t);
throw ex;
}
}Example 49
| Project: graylog2-input-lumberjack-master File: LumberjackServer.java View source code |
private SSLEngine getSSLEngine() throws GeneralSecurityException, IOException {
SSLContext context;
char[] storepass = configuration.getKeyStorePass().toCharArray();
char[] keypass = configuration.getKeyPass().toCharArray();
String storePath = configuration.getKeyStorePath();
try {
context = SSLContext.getInstance("TLS");
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
FileInputStream fin = new FileInputStream(storePath);
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(fin, storepass);
kmf.init(ks, keypass);
context.init(kmf.getKeyManagers(), null, null);
} catch (GeneralSecurityExceptionIOException | e) {
LOGGER.warn("Exception while creating channel pipeline", e);
throw e;
}
SSLEngine engine = context.createSSLEngine();
engine.setUseClientMode(false);
return engine;
}Example 50
| Project: hazelcast-archive-master File: BasicSSLContextFactory.java View source code |
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);
}Example 51
| Project: hello-pinnedcerts-master File: RetrofitClientBuilder.java View source code |
public RetrofitClientBuilder pinCertificates(InputStream resourceStream, char[] password) throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException, UnrecoverableKeyException, KeyManagementException {
KeyStore keyStore = KeyStore.getInstance(HttpClientBuilder.BOUNCY_CASTLE);
keyStore.load(resourceStream, password);
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
TrustManager[] trustManagers = { new CustomTrustManager(keyStore) };
kmf.init(keyStore, password);
SSLContext sslContext = SSLContext.getInstance(SSLSocketFactory.TLS);
sslContext.init(kmf.getKeyManagers(), trustManagers, null);
okHttpClient.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
okHttpClient.setSslSocketFactory(sslContext.getSocketFactory());
return this;
}Example 52
| Project: irma_future_id-master File: HTTPSServerThread.java View source code |
SSLContext createSSLContext() throws Exception {
KeyManagerFactory mgrFact = KeyManagerFactory.getInstance("SunX509");
KeyStore serverStore = KeyStore.getInstance("JKS");
serverStore.load(new ByteArrayInputStream(KeyStores.server), SERVER_PASSWORD);
mgrFact.init(serverStore, SERVER_PASSWORD);
// set up a trust manager so we can recognize the server
TrustManagerFactory trustFact = TrustManagerFactory.getInstance("SunX509");
KeyStore trustStore = KeyStore.getInstance("JKS");
trustStore.load(new ByteArrayInputStream(KeyStores.trustStore), TRUST_STORE_PASSWORD);
trustFact.init(trustStore);
// create a context and set up a socket factory
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(mgrFact.getKeyManagers(), trustFact.getTrustManagers(), null);
return sslContext;
}Example 53
| Project: jboss-polyglot-master File: SSLContextService.java View source code |
@Override
public void start(StartContext context) throws StartException {
Connector connector = connectorInjector.getValue();
ProtocolHandler handler = connector.getProtocolHandler();
String keystorePath = (String) handler.getAttribute("keystore");
String keystorePassword = (String) handler.getAttribute("keypass");
String keystoreType = (String) handler.getAttribute("keystoreType");
String protocols = (String) handler.getAttribute("protocols");
String algorithm = (String) handler.getAttribute("algorithm");
if (protocols == null) {
protocols = "TLS";
}
if (keystoreType == null) {
keystoreType = "JKS";
}
if (algorithm == null) {
algorithm = "SunX509";
}
try {
this.sslContext = SSLContext.getInstance(protocols);
KeyStore keyStore = KeyStore.getInstance(keystoreType);
InputStream stream = new FileInputStream(keystorePath);
try {
keyStore.load(stream, keystorePassword.toCharArray());
} finally {
stream.close();
}
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(algorithm);
keyManagerFactory.init(keyStore, keystorePassword.toCharArray());
this.sslContext.init(keyManagerFactory.getKeyManagers(), null, null);
} catch (NoSuchAlgorithmException e) {
throw new StartException(e);
} catch (KeyManagementException e) {
throw new StartException(e);
} catch (KeyStoreException e) {
throw new StartException(e);
} catch (UnrecoverableKeyException e) {
throw new StartException(e);
} catch (FileNotFoundException e) {
throw new StartException(e);
} catch (CertificateException e) {
throw new StartException(e);
} catch (IOException e) {
throw new StartException(e);
}
}Example 54
| Project: kolmafia-master File: DAVKeyManager.java View source code |
public static KeyManager[] getKeyManagers() {
if (ourIsInitialized) {
return ourKeyManagers;
}
ourIsInitialized = true;
String certFileName = System.getProperty(CERTIFICATE_FILE, System.getProperty(OLD_CERTIFICATE_FILE));
if (certFileName == null) {
return null;
}
char[] passphrase = null;
String pph = System.getProperty(CERTIFICATE_PASSPHRASE, System.getProperty(OLD_CERTIFICATE_PASSPHRASE));
if (pph != null) {
passphrase = pph.toCharArray();
}
KeyStore keyStore = null;
InputStream is = null;
try {
keyStore = KeyStore.getInstance("PKCS12");
if (keyStore != null) {
is = new FileInputStream(certFileName);
keyStore.load(is, passphrase);
}
} catch (Throwable th) {
SVNDebugLog.getDefaultLog().logFine(SVNLogType.DEFAULT, th);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
KeyManagerFactory kmf = null;
if (keyStore != null) {
try {
kmf = KeyManagerFactory.getInstance("SunX509");
if (kmf != null) {
kmf.init(keyStore, passphrase);
ourKeyManagers = kmf.getKeyManagers();
}
} catch (Throwable e) {
SVNDebugLog.getDefaultLog().logFine(SVNLogType.DEFAULT, e);
}
}
return ourKeyManagers;
}Example 55
| Project: lightnio-master File: SimpleSSLServer.java View source code |
protected SSLContext createSSLContext() throws Exception {
ClassLoader cl = getClass().getClassLoader();
URL url = cl.getResource("test.keystore");
KeyStore keystore = KeyStore.getInstance("jks");
keystore.load(url.openStream(), "nopassword".toCharArray());
KeyManagerFactory kmfactory = createKeyManagerFactory();
kmfactory.init(keystore, "nopassword".toCharArray());
KeyManager[] keymanagers = kmfactory.getKeyManagers();
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(keymanagers, null, null);
return sslcontext;
}Example 56
| Project: logstash-gelf-master File: GelfTCPSSLSenderIntegrationTests.java View source code |
@BeforeAll
public static void setupClass() throws Exception {
File file = new File("work/keystore.jks");
assumeTrue(file.exists());
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(new FileInputStream(file), "changeit".toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(keyStore, "changeit".toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(keyStore);
final SslContext sslContext = SslContextBuilder.forServer(kmf).build();
GelfTCPSSLSenderIntegrationTests.sslContext = SSLContext.getInstance("TLSv1");
GelfTCPSSLSenderIntegrationTests.sslContext.init(new KeyManager[0], tmf.getTrustManagers(), null);
server.run(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) throws Exception {
ch.pipeline().addLast(sslContext.newHandler(ch.alloc()));
ch.pipeline().addLast(server.getHandler());
}
});
}Example 57
| Project: mapfish-print-master File: CertificateStore.java View source code |
private SSLContext createSslContext() {
try {
SSLContext newSslContext = SSLContext.getInstance("TLS");
KeyStore ks = KeyStore.getInstance("JKS");
final byte[] bytes = this.configuration.loadFile(this.uri.toString());
ks.load(new ByteArrayInputStream(bytes), this.password);
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, this.password);
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
tmf.init(ks);
newSslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
return newSslContext;
} catch (Throwable t) {
throw ExceptionUtils.getRuntimeException(t);
}
}Example 58
| Project: MaritimeCloud-master File: TransportSecurityUtils.java View source code |
/**
* Loads the key-store from the given path
* @param keyStorePath the path to the key-store
* @param pwd the key store password
* @return the key-store managers
*/
public static KeyManager[] loadKeyStore(String keyStorePath, char[] pwd) throws Exception {
Objects.requireNonNull(keyStorePath, "Key-store path undefined");
Objects.requireNonNull(pwd, "Key-store password undefined");
String defaultAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
KeyManagerFactory instance = KeyManagerFactory.getInstance(defaultAlgorithm);
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
try (InputStream file = new FileInputStream(keyStorePath)) {
keyStore.load(file, pwd);
}
instance.init(keyStore, pwd);
return instance.getKeyManagers();
}Example 59
| Project: mina-ftpserver-master File: MinaClientAuthTest.java View source code |
@Override
protected FTPSClient createFTPClient() throws Exception {
FTPSClient client = new FTPSClient(useImplicit());
client.setNeedClientAuth(true);
KeyStore ks = KeyStore.getInstance("JKS");
FileInputStream fis = new FileInputStream(FTPCLIENT_KEYSTORE);
ks.load(fis, KEYSTORE_PASSWORD.toCharArray());
fis.close();
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks, KEYSTORE_PASSWORD.toCharArray());
client.setKeyManager(kmf.getKeyManagers()[0]);
return client;
}Example 60
| Project: minnal-master File: HttpsConnector.java View source code |
/**
* @return
*/
protected SSLEngine createSslEngine() {
logger.debug("Creating a SSL engine from the SSL context");
String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
if (algorithm == null) {
algorithm = "SunX509";
logger.trace("ssl.KeyManagerFactory.algorithm algorithm is not set. Defaulting to {}", algorithm);
}
SSLContext serverContext = null;
SSLConfiguration configuration = getConnectorConfiguration().getSslConfiguration();
InputStream stream = null;
try {
File file = new File(configuration.getKeyStoreFile());
stream = new FileInputStream(file);
KeyStore ks = KeyStore.getInstance(configuration.getKeystoreType());
ks.load(stream, configuration.getKeyStorePassword().toCharArray());
// Set up key manager factory to use our key store
KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
kmf.init(ks, configuration.getKeyPassword().toCharArray());
// Initialize the SSLContext to work with our key managers.
serverContext = SSLContext.getInstance(configuration.getProtocol());
serverContext.init(kmf.getKeyManagers(), null, null);
} catch (Exception e) {
logger.error("Failed while initializing the ssl context", e);
throw new MinnalException("Failed to initialize the ssl context", e);
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
logger.trace("Failed while closing the stream", e);
}
}
}
return serverContext.createSSLEngine();
}Example 61
| Project: MobilSecurity-master File: Client.java View source code |
public void init(Context context) {
try {
SSLContext sslContext = SSLContext.getInstance(CLIENT_AGREEMENT);
KeyManagerFactory keyManager = KeyManagerFactory.getInstance(CLIENT_KEY_MANAGER);
TrustManagerFactory trustManager = TrustManagerFactory.getInstance(CLIENT_TRUST_MANAGER);
KeyStore kks = KeyStore.getInstance(CLIENT_KEY_KEYSTORE);
KeyStore tks = KeyStore.getInstance(CLIENT_TRUST_KEYSTORE);
kks.load(context.getResources().openRawResource(R.raw.debug), CLIENT_KET_PASSWORD.toCharArray());
tks.load(context.getResources().openRawResource(R.raw.debug), CLIENT_TRUST_PASSWORD.toCharArray());
keyManager.init(kks, CLIENT_KET_PASSWORD.toCharArray());
trustManager.init(tks);
sslContext.init(keyManager.getKeyManagers(), trustManager.getTrustManagers(), null);
sslSocket = (SSLSocket) sslContext.getSocketFactory().createSocket(SERVER_IP, SERVER_PORT);
} catch (Exception e) {
Log.v("TAG", e.toString());
}
}Example 62
| Project: moco-master File: HttpsCertificate.java View source code |
private SSLContext createServerContext() {
InputStream is = this.getKeyStore();
try {
KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(is, this.getKeyStorePassword());
KeyManagerFactory factory = KeyManagerFactory.getInstance(getAlgorithm());
factory.init(keyStore, this.getCertPassword());
SSLContext serverContext = SSLContext.getInstance(PROTOCOL);
serverContext.init(factory.getKeyManagers(), null, null);
return serverContext;
} catch (Exception e) {
throw new MocoException("Failed to initialize the server-side SSLContext", e);
} finally {
Closeables.closeQuietly(is);
}
}Example 63
| Project: openflowjava-master File: SslContextFactory.java View source code |
/**
* @return servercontext
*/
public SSLContext getServerContext() {
String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
if (algorithm == null) {
algorithm = "SunX509";
}
SSLContext serverContext = null;
try {
KeyStore ks = KeyStore.getInstance(tlsConfig.getTlsKeystoreType().name());
ks.load(SslKeyStore.asInputStream(tlsConfig.getTlsKeystore(), tlsConfig.getTlsKeystorePathType()), tlsConfig.getKeystorePassword().toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
kmf.init(ks, tlsConfig.getCertificatePassword().toCharArray());
KeyStore ts = KeyStore.getInstance(tlsConfig.getTlsTruststoreType().name());
ts.load(SslKeyStore.asInputStream(tlsConfig.getTlsTruststore(), tlsConfig.getTlsTruststorePathType()), tlsConfig.getTruststorePassword().toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);
tmf.init(ts);
serverContext = SSLContext.getInstance(PROTOCOL);
serverContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
} catch (IOException e) {
LOG.warn("IOException - Failed to load keystore / truststore." + " Failed to initialize the server-side SSLContext", e);
} catch (NoSuchAlgorithmException e) {
LOG.warn("NoSuchAlgorithmException - Unsupported algorithm." + " Failed to initialize the server-side SSLContext", e);
} catch (CertificateException e) {
LOG.warn("CertificateException - Unable to access certificate (check password)." + " Failed to initialize the server-side SSLContext", e);
} catch (Exception e) {
LOG.warn("Exception - Failed to initialize the server-side SSLContext", e);
}
return serverContext;
}Example 64
| Project: pegadi-master File: RMISSLServerSocketFactory.java View source code |
public ServerSocket createServerSocket(int port) throws IOException {
log.info("createServerSocket: Port " + port);
log.info("createServerSocket: keystore is: " + keystore);
SSLServerSocketFactory ssf;
try {
// set up key manager to do server authentication
SSLContext ctx;
KeyManagerFactory kmf;
KeyStore ks;
ctx = SSLContext.getInstance("TLS");
kmf = KeyManagerFactory.getInstance("SunX509");
ks = KeyStore.getInstance("JKS");
//If in devmode, just generate a key.
if (inDeveloperMode) {
ks.load(getClass().getResourceAsStream("dummyssl.keys"), passphrase.toCharArray());
} else {
if (!keystore.exists()) {
throw new IllegalArgumentException("File " + keystore + " does not exist");
}
ks.load(new FileInputStream(keystore), passphrase.toCharArray());
}
kmf.init(ks, passphrase.toCharArray());
ctx.init(kmf.getKeyManagers(), null, null);
ssf = ctx.getServerSocketFactory();
} catch (Exception e) {
log.error("Error", e);
throw new IOException("Exceptinon getting socket factory " + e.getClass() + e.getMessage());
}
return ssf.createServerSocket(port);
}Example 65
| Project: Pitbull-master File: HttpServerBuilder.java View source code |
public T add() throws Exception {
HttpConnector connector = new HttpConnector();
connector.setPort(port);
if (enableHttps) {
KeyManagerFactory kmf = null;
if (keyStore == null) {
try {
keyStore = KeyTools.generateKeyStore();
kmf = KeyManagerFactory.getInstance("SunX509");
keyStore = KeyTools.generateKeyStore();
kmf.init(keyStore, new char[] { 'p', 'a', 's', 's', 'w', 'o', 'r', 'd' });
} catch (Exception e) {
throw new RuntimeException(e);
}
} else {
kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(keyStore, keyStorePassword.toCharArray());
}
// Initialize the SSLContext to work with our key managers.
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(kmf.getKeyManagers(), null, null);
// Initialize the SSLContext to work with our key managers.
SSLContext serverContext = SSLContext.getInstance("TLS");
serverContext.init(kmf.getKeyManagers(), null, null);
connector.setSslContext(serverContext);
}
server.getConnectors().add(connector);
return (T) HttpServerBuilder.this;
}Example 66
| Project: quickstarts-master File: TCPClient.java View source code |
public static void main(String[] args) throws Exception {
KeyStore keystore = KeyStore.getInstance("JKS");
keystore.load(new FileInputStream("users.jks"), "changeit".toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
tmf.init(keystore);
SSLContext context = SSLContext.getInstance("TLS");
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keystore, "changeit".toCharArray());
context.init(keyManagerFactory.getKeyManagers(), tmf.getTrustManagers(), null);
SSLSocketFactory sf = context.getSocketFactory();
Socket clientSocket = sf.createSocket("localhost", 3939);
DataOutputStream outputStream = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Message body to send over TCP: ");
outputStream.write(reader.readLine().getBytes());
Thread.sleep(50);
clientSocket.close();
}Example 67
| Project: ratpack-master File: NettySslContextDeserializer.java View source code |
@SuppressWarnings("Duplicates")
@Override
public SslContext deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
ObjectNode node = jp.readValueAsTree();
try {
String keyStoreFile = node.path("keystoreFile").asText();
String keyStorePassword = node.path("keystorePassword").asText();
String trustStoreFile = node.path("truststoreFile").asText();
String trustStorePassword = node.path("truststorePassword").asText();
if (keyStoreFile.isEmpty()) {
throw new IllegalStateException("keystoreFile must be set if any ssl properties are set");
} else if (keyStorePassword.isEmpty()) {
throw new IllegalStateException("keystorePassword must be set if any ssl properties are set");
} else if (!trustStoreFile.isEmpty() && trustStorePassword.isEmpty()) {
throw new IllegalStateException("truststorePassword must be specified when truststoreFile is specified");
}
KeyManagerFactory keyManagerFactory;
try (InputStream is = Files.newInputStream(Paths.get(keyStoreFile))) {
keyManagerFactory = SslContexts.keyManagerFactory(is, keyStorePassword.toCharArray());
}
SslContextBuilder builder = SslContextBuilder.forServer(keyManagerFactory);
if (!trustStoreFile.isEmpty()) {
try (InputStream is = Files.newInputStream(Paths.get(trustStoreFile))) {
builder.trustManager(SslContexts.trustManagerFactory(is, trustStorePassword.toCharArray()));
}
}
return builder.build();
} catch (GeneralSecurityException ex) {
throw Exceptions.uncheck(ex);
}
}Example 68
| Project: release-master File: CamelNettyBindingQuickstartTest.java View source code |
@Override
@Test
public void testDeployment() throws Exception {
KeyStore keystore = KeyStore.getInstance("JKS");
keystore.load(new FileInputStream(new File(SRC_DIR, "users.jks")), "changeit".toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
tmf.init(keystore);
SSLContext context = SSLContext.getInstance("TLS");
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keystore, "changeit".toCharArray());
context.init(keyManagerFactory.getKeyManagers(), tmf.getTrustManagers(), null);
SSLSocketFactory sf = context.getSocketFactory();
Socket clientSocket = sf.createSocket("localhost", 3939);
DataOutputStream outputStream = new DataOutputStream(clientSocket.getOutputStream());
outputStream.write(getClass().getName().getBytes());
outputStream.flush();
Thread.sleep(1000);
clientSocket.close();
}Example 69
| Project: Resteasy-master File: SSLCerts.java View source code |
public static SSLContext getContext(String keyStoreFileName, char[] keyStorePassword, String trustStoreFileName, char[] trustStorePassword) {
try {
KeyManager[] keyManagers = null;
if (keyStoreFileName != null) {
KeyStore ks = KeyStore.getInstance("JKS");
loadKeyStore(ks, keyStoreFileName, keyStorePassword);
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks, keyStorePassword);
keyManagers = kmf.getKeyManagers();
}
TrustManager[] trustManagers = null;
if (trustStoreFileName != null) {
KeyStore ks = KeyStore.getInstance("JKS");
loadKeyStore(ks, trustStoreFileName, trustStorePassword);
TrustManagerFactory tmf = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
trustManagers = tmf.getTrustManagers();
}
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagers, trustManagers, null);
return sslContext;
} catch (Exception e) {
throw new IllegalStateException(e);
}
}Example 70
| Project: robovm-master File: X509KeyManagerTest.java View source code |
private void test_ChooseClientAlias_KeyType(String clientKeyType, String caKeyType, String selectedKeyType, boolean succeeds) throws Exception {
TestKeyStore ca = new TestKeyStore.Builder().keyAlgorithms(caKeyType).build();
TestKeyStore client = new TestKeyStore.Builder().keyAlgorithms(clientKeyType).signer(ca.getPrivateKey(caKeyType, caKeyType)).build();
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(client.keyStore, client.keyPassword);
String[] keyTypes = new String[] { selectedKeyType };
KeyManager[] managers = kmf.getKeyManagers();
for (KeyManager manager : managers) {
if (manager instanceof X509KeyManager) {
String alias = ((X509KeyManager) manager).chooseClientAlias(keyTypes, null, null);
if (succeeds) {
assertNotNull(alias);
} else {
assertNull(alias);
}
}
}
}Example 71
| Project: simple-java-mail-master File: SSLConfiguration.java View source code |
public SSLSocketFactory getSSLSocketFactory() throws SocksException {
MiscUtil.checkNotNull(trustKeyStoreInfo, "trustKeyStoreInfo may not be null");
FileInputStream s1 = null;
FileInputStream s2 = null;
try {
final SSLContext context = SSLContext.getInstance("SSL");
final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
final KeyStore trustKeyStore = KeyStore.getInstance(trustKeyStoreInfo.getType());
trustKeyStore.load(s1 = new FileInputStream(trustKeyStoreInfo.getKeyStorePath()), trustKeyStoreInfo.getPassword().toCharArray());
trustManagerFactory.init(trustKeyStore);
KeyStore keyStore = null;
if (keyStoreInfo != null && keyStoreInfo.getKeyStorePath() != null) {
final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
keyStore = KeyStore.getInstance(keyStoreInfo.getType());
keyStore.load(s2 = new FileInputStream(keyStoreInfo.getKeyStorePath()), keyStoreInfo.getPassword().toCharArray());
keyManagerFactory.init(keyStore, keyStoreInfo.getPassword().toCharArray());
context.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
} else {
context.init(null, trustManagerFactory.getTrustManagers(), null);
}
if (keyStore != null) {
LOGGER.info("SSL: Key store:{}", keyStoreInfo.getKeyStorePath());
}
LOGGER.info("SSL: Trust key store:{}", trustKeyStoreInfo.getKeyStorePath());
return context.getSocketFactory();
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
throw new SocksException(e.getMessage());
} finally {
tryCloseStream(s1);
tryCloseStream(s2);
}
}Example 72
| Project: svnkit-master File: DAVKeyManager.java View source code |
public static KeyManager[] getKeyManagers() {
if (ourIsInitialized) {
return ourKeyManagers;
}
ourIsInitialized = true;
String certFileName = System.getProperty(CERTIFICATE_FILE, System.getProperty(OLD_CERTIFICATE_FILE));
if (certFileName == null) {
return null;
}
char[] passphrase = null;
String pph = System.getProperty(CERTIFICATE_PASSPHRASE, System.getProperty(OLD_CERTIFICATE_PASSPHRASE));
if (pph != null) {
passphrase = pph.toCharArray();
}
KeyStore keyStore = null;
InputStream is = null;
try {
keyStore = KeyStore.getInstance("PKCS12");
if (keyStore != null) {
is = new FileInputStream(certFileName);
keyStore.load(is, passphrase);
}
} catch (Throwable th) {
SVNDebugLog.getDefaultLog().logFine(SVNLogType.DEFAULT, th);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
KeyManagerFactory kmf = null;
if (keyStore != null) {
try {
kmf = KeyManagerFactory.getInstance("SunX509");
if (kmf != null) {
kmf.init(keyStore, passphrase);
ourKeyManagers = kmf.getKeyManagers();
}
} catch (Throwable e) {
SVNDebugLog.getDefaultLog().logFine(SVNLogType.DEFAULT, e);
}
}
return ourKeyManagers;
}Example 73
| Project: android-socket.io-demo-master File: SSLConnectionTest.java View source code |
SSLContext createSSLContext() throws GeneralSecurityException, IOException {
KeyStore ks = KeyStore.getInstance("JKS");
File file = new File("src/test/resources/keystore.jks");
ks.load(new FileInputStream(file), "password".toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, "password".toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
tmf.init(ks);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
return sslContext;
}Example 74
| Project: android-ssl-master File: SSLContextFactory.java View source code |
/**
* Creates an SSLContext with the client and server certificates
* @param clientCertFile A File containing the client certificate
* @param clientCertPassword Password for the client certificate
* @param caCertString A String containing the server certificate
* @return An initialized SSLContext
* @throws Exception
*/
public SSLContext makeContext(File clientCertFile, String clientCertPassword, String caCertString) throws Exception {
final KeyStore keyStore = loadPKCS12KeyStore(clientCertFile, clientCertPassword);
KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
kmf.init(keyStore, clientCertPassword.toCharArray());
KeyManager[] keyManagers = kmf.getKeyManagers();
final KeyStore trustStore = loadPEMTrustStore(caCertString);
TrustManager[] trustManagers = { new CustomTrustManager(trustStore) };
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagers, trustManagers, null);
return sslContext;
}Example 75
| Project: Android-ZBLibrary-master File: SSLUtil.java View source code |
/**
* 获得��认�所需的�数
* @param bks bks�书的输入�
* @param keystorePass 秘钥
* @return KeyManager[]对象
*/
public static KeyManager[] getKeyManagers(InputStream bks, String keystorePass) {
KeyStore clientKeyStore = null;
try {
clientKeyStore = KeyStore.getInstance("BKS");
clientKeyStore.load(bks, keystorePass.toCharArray());
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(clientKeyStore, keystorePass.toCharArray());
KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();
return keyManagers;
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (UnrecoverableKeyException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}Example 76
| Project: AndroidHttpCapture-master File: KeyStoreUtil.java View source code |
/**
* Retrieve the KeyManagers for the specified KeyStore.
*
* @param keyStore the KeyStore to retrieve KeyManagers from
* @param keyStorePassword the KeyStore password
* @param keyManagerAlgorithm key manager algorithm to use, or null to use the system default
* @param provider JCA provider to use, or null to use the system default
* @return KeyManagers for the specified KeyStore
*/
public static KeyManager[] getKeyManagers(KeyStore keyStore, String keyStorePassword, String keyManagerAlgorithm, String provider) {
if (keyManagerAlgorithm == null) {
keyManagerAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
}
try {
KeyManagerFactory kmf;
if (provider == null) {
kmf = KeyManagerFactory.getInstance(keyManagerAlgorithm);
} else {
kmf = KeyManagerFactory.getInstance(keyManagerAlgorithm, provider);
}
kmf.init(keyStore, keyStorePassword.toCharArray());
return kmf.getKeyManagers();
} catch (NoSuchAlgorithmExceptionUnrecoverableKeyException | KeyStoreException | NoSuchProviderException | e) {
throw new KeyStoreAccessException("Unable to get KeyManagers for KeyStore", e);
}
}Example 77
| Project: AndroidStudyDemo-master File: HttpsUtil.java View source code |
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 keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(clientKeyStore, password.toCharArray());
return keyManagerFactory.getKeyManagers();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnrecoverableKeyException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}Example 78
| Project: asyn4j-master File: BogusSslContextFactory.java View source code |
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;
}Example 79
| Project: batchee-master File: ClientSslConfiguration.java View source code |
public SSLContext getSslContext() {
final SSLContext context;
try {
context = SSLContext.getInstance(sslContextType);
final KeyManagerFactory kmf = KeyManagerFactory.getInstance(keyManagerType);
final KeyManager[] km;
if (keyManagerPath != null) {
final InputStream fin = findInputStream(keyManagerPath);
final KeyStore ks = KeyStore.getInstance(keystoreType);
ks.load(fin, keystorePassword.toCharArray());
km = kmf.getKeyManagers();
} else {
km = null;
}
final TrustManager[] tm;
if (trustManagerAlgorithm != null) {
if (trustManagerProvider != null) {
tm = TrustManagerFactory.getInstance(trustManagerAlgorithm, trustManagerProvider).getTrustManagers();
} else {
tm = TrustManagerFactory.getInstance(trustManagerAlgorithm).getTrustManagers();
}
} else {
tm = null;
}
context.init(km, tm, null);
} catch (final Exception e) {
throw new IllegalArgumentException(e);
}
return context;
}Example 80
| Project: betfair-master File: HttpClientSSO.java View source code |
private static KeyManager[] getKeyManagers(String keyStoreType, InputStream keyStoreFile, String keyStorePassword) throws Exception {
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(keyStoreFile, keyStorePassword.toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(keyStore, keyStorePassword.toCharArray());
return kmf.getKeyManagers();
}Example 81
| Project: bgpcep-master File: SslContextFactory.java View source code |
public SSLContext getServerContext() {
try {
final KeyStore ks = KeyStore.getInstance(this.tlsConfig.getKeystoreType().name());
ks.load(SslKeyStore.asInputStream(this.tlsConfig.getKeystore(), this.tlsConfig.getKeystorePathType()), this.tlsConfig.getKeystorePassword().toCharArray());
final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks, this.tlsConfig.getCertificatePassword().toCharArray());
final KeyStore ts = KeyStore.getInstance(this.tlsConfig.getTruststoreType().name());
ts.load(SslKeyStore.asInputStream(this.tlsConfig.getTruststore(), this.tlsConfig.getTruststorePathType()), this.tlsConfig.getTruststorePassword().toCharArray());
final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ts);
final SSLContext serverContext = SSLContext.getInstance(PROTOCOL);
serverContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
return serverContext;
} catch (final IOException e) {
LOG.warn("IOException - Failed to load keystore / truststore. Failed to initialize the server-side SSLContext", e);
} catch (final NoSuchAlgorithmException e) {
LOG.warn("NoSuchAlgorithmException - Unsupported algorithm. Failed to initialize the server-side SSLContext", e);
} catch (final CertificateException e) {
LOG.warn("CertificateException - Unable to access certificate (check password). Failed to initialize the server-side SSLContext", e);
} catch (final Exception e) {
LOG.warn("Exception - Failed to initialize the server-side SSLContext", e);
}
//TODO try to use default SSLContext instance?
return null;
}Example 82
| Project: bonaparte-java-master File: KeyStoreIo.java View source code |
public static KeyManagerFactory getKeyManagerFactory(String filename) { KeyStore ks = keyStoreFromFile(filename); if (ks == null) { return null; } String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm"); if (algorithm == null) { algorithm = "SunX509"; } KeyManagerFactory kmf; try { kmf = KeyManagerFactory.getInstance(algorithm); } catch (NoSuchAlgorithmException e2) { LOGGER.error("Cannot instantiate key manager factory: {}", e2); return null; } String keyPwFilename = filename + "PW"; LOGGER.info("Reading key password from file {}", keyPwFilename); try (BufferedReader rpw = new BufferedReader(new FileReader(keyPwFilename))) { String line = rpw.readLine(); rpw.close(); // get user password char[] keyPassword = line.toCharArray(); kmf.init(ks, keyPassword); } catch (Exception e) { LOGGER.error("Cannot read from key pw file: {}", e); return null; } return kmf; }
Example 83
| Project: Cassandra-KVPM-master File: SSLFactory.java View source code |
private static SSLContext createSSLContext(EncryptionOptions options) throws IOException {
SSLContext ctx;
try {
ctx = SSLContext.getInstance(PROTOCOL);
TrustManagerFactory tmf = null;
KeyManagerFactory kmf = null;
tmf = TrustManagerFactory.getInstance(ALGORITHM);
KeyStore ts = KeyStore.getInstance(STORE_TYPE);
ts.load(new FileInputStream(options.truststore), options.truststore_password.toCharArray());
tmf.init(ts);
kmf = KeyManagerFactory.getInstance(ALGORITHM);
KeyStore ks = KeyStore.getInstance(STORE_TYPE);
ks.load(new FileInputStream(options.keystore), options.keystore_password.toCharArray());
kmf.init(ks, options.keystore_password.toCharArray());
ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
} catch (Exception e) {
throw new IOException("Error creating the initializing the SSL Context", e);
}
return ctx;
}Example 84
| Project: CorfuDB-master File: TlsUtils.java View source code |
public static SslContext enableTls(SslContextType desiredType, String keyStore, Consumer<Exception> keyStoreException, String ksPasswordFile, Consumer<Exception> ksPasswordFileException, String trustStore, Consumer<Exception> trustStoreException, String tsPasswordFile, Consumer<Exception> tsPasswordFileException) {
// Get the key store password
String ksp = "";
if (ksPasswordFile != null) {
try {
ksp = (new String(Files.readAllBytes(Paths.get(ksPasswordFile)))).trim();
} catch (Exception e) {
keyStoreException.accept(e);
return null;
}
}
// Get the key store
KeyStore ks = null;
if (keyStore != null) {
try (FileInputStream fis = new FileInputStream(keyStore)) {
ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(fis, ksp.toCharArray());
} catch (Exception e) {
ksPasswordFileException.accept(e);
return null;
}
}
// Get the trust store password
String tsp = "";
if (tsPasswordFile != null) {
try {
tsp = (new String(Files.readAllBytes(Paths.get(tsPasswordFile)))).trim();
} catch (Exception e) {
trustStoreException.accept(e);
return null;
}
}
// Get the trust store
KeyStore ts = null;
if (trustStore != null) {
try (FileInputStream fis = new FileInputStream(trustStore)) {
ts = KeyStore.getInstance(KeyStore.getDefaultType());
ts.load(fis, tsp.toCharArray());
} catch (Exception e) {
tsPasswordFileException.accept(e);
return null;
}
}
try {
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks, ksp.toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ts);
switch(desiredType) {
case CLIENT_CONTEXT:
return SslContextBuilder.forClient().keyManager(kmf).trustManager(tmf).build();
case SERVER_CONTEXT:
return SslContextBuilder.forServer(kmf).trustManager(tmf).build();
default:
throw new RuntimeException("Bad SSL context type: " + desiredType);
}
} catch (Exception e) {
throw new RuntimeException("Could not build SslContext type " + desiredType.toString() + ": " + e.getClass().getSimpleName(), e);
}
}Example 85
| Project: cxf-fediz-master File: Utils.java View source code |
public static KeyManager[] getKeyManagers(KeyStore keyStore, String keyPassword) throws GeneralSecurityException, IOException {
// For tests, we just use the default algorithm
String alg = KeyManagerFactory.getDefaultAlgorithm();
char[] keyPass = keyPassword != null ? keyPassword.toCharArray() : null;
// For tests, we just use the default provider.
KeyManagerFactory fac = KeyManagerFactory.getInstance(alg);
fac.init(keyStore, keyPass);
return fac.getKeyManagers();
}Example 86
| Project: deskcon-android-master File: Connection.java View source code |
public static SSLContext initSSLContext(Context context) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException, KeyManagementException {
// load the keystore
InputStream keyStoreStream;
try {
keyStoreStream = context.openFileInput("devicekeystore.bks");
} catch (FileNotFoundException e1) {
return null;
}
KeyStore MyKeyStore = KeyStore.getInstance("BKS");
MyKeyStore.load(keyStoreStream, "android".toCharArray());
// Enumeration<String> aliases = MyKeyStore.aliases();
// while(aliases.hasMoreElements()) {
// System.out.println(aliases.nextElement());
// }
// initialize trust manager factory with the read truststore
TrustManagerFactory trustManagerFactory = null;
trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(MyKeyStore);
TrustManager[] tm = trustManagerFactory.getTrustManagers();
// init KeyManagerFactory
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(MyKeyStore, "passwd".toCharArray());
KeyManager[] km = keyManagerFactory.getKeyManagers();
// Set SSL Context
SSLContext sslcontext;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
sslcontext = SSLContext.getInstance("TLSv1.2");
} else {
sslcontext = SSLContext.getInstance("TLSv1");
}
sslcontext.init(km, tm, new SecureRandom());
return sslcontext;
}Example 87
| Project: docker-java-master File: KeystoreSSLConfig.java View source code |
/**
* Get the SSL Context out of the keystore.
*
* @return java SSLContext
* @throws KeyManagementException
* @throws UnrecoverableKeyException
* @throws NoSuchAlgorithmException
* @throws KeyStoreException
*/
@Override
public SSLContext getSSLContext() throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException {
final SSLContext context = SSLContext.getInstance("TLS");
String httpProtocols = System.getProperty("https.protocols");
System.setProperty("https.protocols", "TLSv1");
if (httpProtocols != null) {
System.setProperty("https.protocols", httpProtocols);
}
final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keystore, keystorePassword.toCharArray());
context.init(keyManagerFactory.getKeyManagers(), new TrustManager[] { new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[] {};
}
@Override
public void checkClientTrusted(final X509Certificate[] arg0, final String arg1) {
}
@Override
public void checkServerTrusted(final X509Certificate[] arg0, final String arg1) {
}
} }, new SecureRandom());
return context;
}Example 88
| Project: DouYu-master File: SSLUtil.java View source code |
/**
* 获得��认�所需的�数
* @param bks bks�书的输入�
* @param keystorePass 秘钥
* @return KeyManager[]对象
*/
public static KeyManager[] getKeyManagers(InputStream bks, String keystorePass) {
KeyStore clientKeyStore = null;
try {
clientKeyStore = KeyStore.getInstance("BKS");
clientKeyStore.load(bks, keystorePass.toCharArray());
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(clientKeyStore, keystorePass.toCharArray());
KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();
return keyManagers;
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (UnrecoverableKeyException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}Example 89
| Project: dss-master File: DefaultKeyManager.java View source code |
/**
* Loads the keystore.
*
* @param keystore
* the keystore to load
* @param ksPasswd
* keystore's password
* @throws GeneralSecurityException
* Certificate/Keystore/Algorithm/... exception
* @throws IOException
* I/O Error
*/
private void initKeyManager(KeyStore keystore, String ksPasswd) throws GeneralSecurityException, IOException {
// initialize a new KMF with the ts we just loaded
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(keystore, ksPasswd.toCharArray());
// acquire X509 key manager from factory
KeyManager[] kms = kmf.getKeyManagers();
for (final KeyManager km : kms) {
if (km instanceof X509KeyManager) {
keyManager = (X509KeyManager) km;
return;
}
}
throw new NoSuchAlgorithmException("No X509KeyManager in KeyManagerFactory");
}Example 90
| Project: ecdr-master File: TLSUtil.java View source code |
public static void setTLSOptions(WebClient client, boolean disableCNCheck) {
ClientConfiguration clientConfiguration = WebClient.getConfig(client);
HTTPConduit httpConduit = clientConfiguration.getHttpConduit();
String keyStorePath = System.getProperty(SSL_KEYSTORE_JAVA_PROPERTY);
String keyStorePassword = System.getProperty(SSL_KEYSTORE_PASSWORD_JAVA_PROPERTY);
if (StringUtils.isNotBlank(keyStorePath) && StringUtils.isNotBlank(keyStorePassword)) {
try {
TLSClientParameters tlsParams = new TLSClientParameters();
LOGGER.debug("Setting disable of CN check on client URL {} to [{}]", client.getCurrentURI(), disableCNCheck);
tlsParams.setDisableCNCheck(disableCNCheck);
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
// add the keystore if it exists
File keystore = new File(keyStorePath);
if (keystore.exists() && keyStorePassword != null) {
FileInputStream fis = new FileInputStream(keystore);
try {
LOGGER.debug("Loading keyStore {}", keystore);
keyStore.load(fis, keyStorePassword.toCharArray());
} catch (IOException e) {
LOGGER.error("Unable to load keystore. {}", keystore, e);
} catch (CertificateException e) {
LOGGER.error("Unable to load certificates from keystore. {}", keystore, e);
} finally {
IOUtils.closeQuietly(fis);
}
KeyManagerFactory keyFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyFactory.init(keyStore, keyStorePassword.toCharArray());
KeyManager[] km = keyFactory.getKeyManagers();
tlsParams.setKeyManagers(km);
}
httpConduit.setTlsClientParameters(tlsParams);
} catch (KeyStoreException e) {
LOGGER.error("Unable to read keystore: ", e);
} catch (NoSuchAlgorithmException e) {
LOGGER.error("Problems creating SSL socket. Usually this is " + "referring to the certificate sent by the server not being trusted by the client.", e);
} catch (FileNotFoundException e) {
LOGGER.error("Unable to locate one of the SSL stores: {} | {}", keyStorePath, e);
} catch (UnrecoverableKeyException e) {
LOGGER.error("Unable to read keystore: ", e);
}
}
}Example 91
| Project: encryption-jvm-bootcamp-master File: HTTPFileServer.java View source code |
public static ServerSocketFactory buildServerSocketFactory(String type) {
//SSL or TLS Encrypted Socket
if (type.equals("SSL") || type.equals("TLS")) {
SSLServerSocketFactory ssf = null;
try {
// set up key manager to do server authentication
SSLContext ctx;
KeyManagerFactory kmf;
KeyStore ks;
char[] passphrase = "passphrase".toCharArray();
//The simple line that lets us toggle from SSL to TLS
ctx = SSLContext.getInstance(type);
kmf = KeyManagerFactory.getInstance("SunX509");
ks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream("keys/sample.keystore"), passphrase);
kmf.init(ks, passphrase);
ctx.init(kmf.getKeyManagers(), null, null);
ssf = ctx.getServerSocketFactory();
return ssf;
} catch (Exception e) {
e.printStackTrace();
}
} else {
//Encryptionless plain server
return ServerSocketFactory.getDefault();
}
return null;
}Example 92
| Project: errai-master File: SslHandlerFactory.java View source code |
/**
* Initialize the {@link javax.net.ssl.SSLEngine} for the
* {@link io.netty.handler.ssl.SslHandler}. Anytime the engine is null or no
* more valid. Otherwise the previous created will be reused.
*
* @param keyPassword
* @param keyStore
* @return
*/
public static SSLEngine getSslEngine(final KeyStore keyStore, final String keyPassword) {
if (sslEngine == null || sslEngine.isInboundDone() || sslEngine.isOutboundDone()) {
try {
final KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(keyStore, keyPassword.toCharArray());
final SSLContext sslc = SSLContext.getInstance("TLSv1");
sslc.init(kmf.getKeyManagers(), null, null);
final SSLEngine sslEngine = sslc.createSSLEngine();
sslEngine.setUseClientMode(false);
sslEngine.setNeedClientAuth(false);
SslHandlerFactory.sslEngine = sslEngine;
} catch (Exception e) {
throw new RuntimeException("could not build SSL Engine", e);
}
}
return sslEngine;
}Example 93
| Project: haze-master File: BasicSSLContextFactory.java View source code |
@Override
public void init(Properties properties) throws Exception {
KeyStore ks = KeyStore.getInstance("JKS");
KeyStore ts = KeyStore.getInstance("JKS");
String keyStorePassword = getProperty(properties, "keyStorePassword");
String keyStore = getProperty(properties, "keyStore");
String trustStore = getProperty(properties, "trustStore", keyStore);
String trustStorePassword = getProperty(properties, "trustStorePassword", keyStorePassword);
String keyManagerAlgorithm = properties.getProperty("keyManagerAlgorithm", KeyManagerFactory.getDefaultAlgorithm());
String trustManagerAlgorithm = properties.getProperty("trustManagerAlgorithm", TrustManagerFactory.getDefaultAlgorithm());
String protocol = properties.getProperty("protocol", "TLS");
KeyManager[] keyManagers = null;
if (keyStore != null) {
KeyManagerFactory kmf = KeyManagerFactory.getInstance(keyManagerAlgorithm);
char[] passPhrase = keyStorePassword != null ? keyStorePassword.toCharArray() : null;
loadKeyStore(ks, passPhrase, keyStore);
kmf.init(ks, passPhrase);
keyManagers = kmf.getKeyManagers();
}
TrustManager[] trustManagers = null;
if (trustStore != null) {
TrustManagerFactory tmf = TrustManagerFactory.getInstance(trustManagerAlgorithm);
char[] passPhrase = trustStorePassword != null ? trustStorePassword.toCharArray() : null;
loadKeyStore(ts, passPhrase, trustStore);
tmf.init(ts);
trustManagers = tmf.getTrustManagers();
}
sslContext = SSLContext.getInstance(protocol);
sslContext.init(keyManagers, trustManagers, null);
}Example 94
| Project: hazelcast-master File: SSLEngineFactorySupport.java View source code |
protected void load(Properties properties) throws Exception {
KeyStore ks = KeyStore.getInstance("JKS");
KeyStore ts = KeyStore.getInstance("JKS");
String keyStorePassword = getProperty(properties, "keyStorePassword");
String keyStore = getProperty(properties, "keyStore");
String trustStore = getProperty(properties, "trustStore", keyStore);
String trustStorePassword = getProperty(properties, "trustStorePassword", keyStorePassword);
String keyManagerAlgorithm = properties.getProperty("keyManagerAlgorithm", KeyManagerFactory.getDefaultAlgorithm());
String trustManagerAlgorithm = properties.getProperty("trustManagerAlgorithm", TrustManagerFactory.getDefaultAlgorithm());
this.protocol = properties.getProperty("protocol", "TLS");
kmf = loadKeyManagerFactory(ks, keyStorePassword, keyStore, keyManagerAlgorithm);
tmf = loadTrustManagerFactory(ts, trustStore, trustStorePassword, trustManagerAlgorithm);
}Example 95
| Project: http-client-master File: BogusSslContextFactory.java View source code |
// private static helpers -----------------------------------------------------------------------------------------
@SneakyThrows(Exception.class)
private static SSLContext createServerContext() {
String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
if (algorithm == null)
algorithm = "X509";
// If you're on android, use BKS here instead of JKS
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.
SSLContext serverContext = SSLContext.getInstance(PROTOCOL);
serverContext.init(kmf.getKeyManagers(), BogusTrustManagerFactory.getTrustManagers(), null);
return serverContext;
}Example 96
| Project: incubator-brooklyn-master File: JmxmpClient.java View source code |
/** tries to connect to the given JMX url over tls,
* optionally using the given keystore (if null using a randomly generated key)
* and optionally using the given truststore (if null trusting all) */
public void connectTls(String urlString, KeyStore keyStore, String keyStorePass, KeyStore trustStore) throws NoSuchAlgorithmException, UnrecoverableKeyException, KeyStoreException, InvalidKeyException, CertificateException, SecurityException, SignatureException, IOException, KeyManagementException {
Map env = new LinkedHashMap();
env.put("jmx.remote.profiles", JmxmpAgent.TLS_JMX_REMOTE_PROFILES);
if (keyStore == null)
throw new NullPointerException("keyStore must be supplied");
//"SunX509");
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(keyStore, (keyStorePass != null ? keyStorePass : "").toCharArray());
TrustManager tms = trustStore != null ? SecureKeys.getTrustManager(trustStore) : SslTrustUtils.TRUST_ALL;
SSLContext ctx = SSLContext.getInstance("TLSv1");
ctx.init(kmf.getKeyManagers(), new TrustManager[] { tms }, null);
SSLSocketFactory ssf = ctx.getSocketFactory();
env.put(JmxmpAgent.TLS_SOCKET_FACTORY_PROPERTY, ssf);
connect(urlString, env);
}Example 97
| Project: jade_agents-master File: SSLHelper.java View source code |
// end createContextNoAuth
/**
* creates a SSLContext with a keystore, no truststore is used
* @return
* @throws ICPException
*/
public static SSLContext createContextWithAuth() throws ICPException {
// Create the SSLContext with Authentication
SSLContext ctx = null;
try {
// open keystore
char[] passphrase = System.getProperty("javax.net.ssl.keyStorePassword").toCharArray();
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream(System.getProperty("javax.net.ssl.keyStore")), passphrase);
// init KeyManager
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, passphrase);
// create and init context
ctx = SSLContext.getInstance("TLS");
ctx.init(kmf.getKeyManagers(), null, null);
} catch (Exception e) {
throw new ICPException("Error creating SSLContext.", e);
}
return ctx;
}Example 98
| Project: jkdbx-master File: UrlStreamHelper.java View source code |
protected KeyManager[] getKeyManagers(String keyStoreType, InputStream keyStoreFile, String keyStorePassword) throws GeneralSecurityException, IOException {
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(keyStoreFile, keyStorePassword.toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(keyStore, keyStorePassword.toCharArray());
return kmf.getKeyManagers();
}Example 99
| Project: kazeproxy-master File: KazeSslEngineSource.java View source code |
private void initializeSSLContext() {
String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
if (algorithm == null) {
algorithm = "SunX509";
}
try {
final KeyStore ks = KeyStore.getInstance("JKS");
// ks.load(new FileInputStream("keystore.jks"),
// "changeit".toCharArray());
ks.load(KazeSslEngineSource.class.getResourceAsStream("/" + keyStoreFile), PASSWORD.toCharArray());
// Set up key manager factory to use our key store
final KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
kmf.init(ks, PASSWORD.toCharArray());
// Set up a trust manager factory to use our key store
TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);
final KeyStore tks = KeyStore.getInstance("JKS");
tks.load(KazeSslEngineSource.class.getResourceAsStream("/" + trustKeyStoreFile), PASSWORD.toCharArray());
tmf.init(tks);
TrustManager[] trustManagers = null;
if (!trustAllServers) {
trustManagers = tmf.getTrustManagers();
} else {
trustManagers = new TrustManager[] { new X509TrustManager() {
// TrustManager that trusts all servers
@Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
} };
}
KeyManager[] keyManagers = null;
if (sendCerts) {
keyManagers = kmf.getKeyManagers();
} else {
keyManagers = new KeyManager[0];
}
// Initialize the SSLContext to work with our key managers.
sslContext = SSLContext.getInstance(PROTOCOL);
sslContext.init(keyManagers, trustManagers, null);
} catch (final Exception e) {
throw new Error("Failed to initialize the server-side SSLContext", e);
}
}Example 100
| Project: ldaptive-master File: X509SSLContextInitializer.java View source code |
@Override
public KeyManager[] getKeyManagers() throws GeneralSecurityException {
KeyManager[] km = null;
if (authenticationCert != null && authenticationKey != null) {
final KeyStore ks = KeyStoreUtils.newInstance();
KeyStoreUtils.setKeyEntry("ldap_client_auth", ks, "changeit".toCharArray(), authenticationKey, authenticationCert);
final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks, "changeit".toCharArray());
km = kmf.getKeyManagers();
}
return km;
}Example 101
| Project: manifold-master File: KeystoreManager.java View source code |
/** Build a secure socket factory based on this keystore.
*/
@Override
public javax.net.ssl.SSLSocketFactory getSecureSocketFactory() throws ManifoldCFException {
try {
// Construct a key manager and a trust manager
javax.net.ssl.KeyManagerFactory keyManagerFactory = null;
// javax.net.ssl.KeyManagerFactory keyManagerFactory = javax.net.ssl.KeyManagerFactory.getInstance(javax.net.ssl.KeyManagerFactory.getDefaultAlgorithm());
// keyManagerFactory.init(keystore,passcode);
javax.net.ssl.TrustManagerFactory trustManagerFactory = javax.net.ssl.TrustManagerFactory.getInstance(javax.net.ssl.TrustManagerFactory.getDefaultAlgorithm());
Logging.keystore.debug("Contents of current trust keystore is:");
if (Logging.keystore.isDebugEnabled()) {
String[] contents = getContents();
int i = 0;
while (i < contents.length) {
Logging.keystore.debug("Description " + Integer.toString(i) + ": " + getDescription(contents[i]));
i++;
}
}
Logging.keystore.debug("Reading trust keystore...");
trustManagerFactory.init(keystore);
if (Logging.keystore.isDebugEnabled()) {
Logging.keystore.debug("...done");
javax.net.ssl.TrustManager array[] = trustManagerFactory.getTrustManagers();
Logging.keystore.debug("Found " + Integer.toString(array.length) + " trust managers");
int i = 0;
while (i < array.length) {
javax.net.ssl.TrustManager tm = array[i];
if (tm instanceof javax.net.ssl.X509TrustManager) {
Logging.keystore.debug("Trust manager " + Integer.toString(i) + " is an x509 trust manager; it's class is " + tm.getClass().getName());
javax.net.ssl.X509TrustManager tm2 = (javax.net.ssl.X509TrustManager) tm;
java.security.cert.X509Certificate calist[] = tm2.getAcceptedIssuers();
Logging.keystore.debug("There are " + Integer.toString(calist.length) + " accepted issuers");
int j = 0;
while (j < calist.length) {
String value = calist[j].getSubjectDN().toString();
Logging.keystore.debug("Authority " + Integer.toString(j) + " is " + value);
j++;
}
}
i++;
}
Logging.keystore.debug("No more trust contents");
}
java.security.SecureRandom secureRandom = java.security.SecureRandom.getInstance("SHA1PRNG");
// Create an SSL context
javax.net.ssl.SSLContext sslContext = javax.net.ssl.SSLContext.getInstance("SSL");
sslContext.init(((keyManagerFactory == null) ? null : keyManagerFactory.getKeyManagers()), ((trustManagerFactory == null) ? null : trustManagerFactory.getTrustManagers()), secureRandom);
return sslContext.getSocketFactory();
} catch (java.security.NoSuchAlgorithmException e) {
throw new ManifoldCFException("No such algorithm: " + e.getMessage(), e);
} catch (java.security.KeyStoreException e) {
throw new ManifoldCFException("Keystore exception: " + e.getMessage(), e);
} catch (java.security.KeyManagementException e) {
throw new ManifoldCFException("Key management exception: " + e.getMessage(), e);
}
}