use of javax.net.ssl.SSLSocketFactory in project xDrip by NightscoutFoundation.
the class ShareRest method getOkHttpClient.
private synchronized OkHttpClient getOkHttpClient() {
try {
final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
} };
final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
final OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.networkInterceptors().add(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
try {
// Add user-agent and relevant headers.
Request original = chain.request();
Request copy = original.newBuilder().build();
Request modifiedRequest = original.newBuilder().header("User-Agent", "CGM-Store-1.2/22 CFNetwork/711.5.6 Darwin/14.0.0").header("Content-Type", "application/json").header("Accept", "application/json").build();
Log.d(TAG, "Sending request: " + modifiedRequest.toString());
Buffer buffer = new Buffer();
copy.body().writeTo(buffer);
Log.d(TAG, "Request body: " + buffer.readUtf8());
final Response response = chain.proceed(modifiedRequest);
Log.d(TAG, "Received response: " + response.toString());
if (response.body() != null) {
MediaType contentType = response.body().contentType();
String bodyString = response.body().string();
Log.d(TAG, "Response body: " + bodyString);
return response.newBuilder().body(ResponseBody.create(contentType, bodyString)).build();
} else
return response;
} catch (NullPointerException e) {
Log.e(TAG, "Got null pointer exception: " + e);
return null;
} catch (IllegalStateException e) {
UserError.Log.wtf(TAG, "Got illegal state exception: " + e);
return null;
}
}
});
okHttpClient.setSslSocketFactory(sslSocketFactory);
okHttpClient.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
return okHttpClient;
} catch (Exception e) {
throw new RuntimeException("Error occurred initializing OkHttp: ", e);
}
}
use of javax.net.ssl.SSLSocketFactory in project xDrip-plus by jamorham.
the class ShareRest method getOkHttpClient.
private synchronized OkHttpClient getOkHttpClient() {
try {
final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
} };
final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
final OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.networkInterceptors().add(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
try {
// Add user-agent and relevant headers.
Request original = chain.request();
Request copy = original.newBuilder().build();
Request modifiedRequest = original.newBuilder().header("User-Agent", "CGM-Store-1.2/22 CFNetwork/711.5.6 Darwin/14.0.0").header("Content-Type", "application/json").header("Accept", "application/json").build();
Log.d(TAG, "Sending request: " + modifiedRequest.toString());
Buffer buffer = new Buffer();
copy.body().writeTo(buffer);
Log.d(TAG, "Request body: " + buffer.readUtf8());
final Response response = chain.proceed(modifiedRequest);
Log.d(TAG, "Received response: " + response.toString());
if (response.body() != null) {
MediaType contentType = response.body().contentType();
String bodyString = response.body().string();
Log.d(TAG, "Response body: " + bodyString);
return response.newBuilder().body(ResponseBody.create(contentType, bodyString)).build();
} else
return response;
} catch (NullPointerException e) {
Log.e(TAG, "Got null pointer exception: " + e);
return null;
} catch (IllegalStateException e) {
UserError.Log.wtf(TAG, "Got illegal state exception: " + e);
return null;
}
}
});
okHttpClient.setSslSocketFactory(sslSocketFactory);
okHttpClient.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
return okHttpClient;
} catch (Exception e) {
throw new RuntimeException("Error occurred initializing OkHttp: ", e);
}
}
use of javax.net.ssl.SSLSocketFactory in project keystore-explorer by kaikramer.
the class TimeStampingClient method queryServer.
/**
* Get timestamp token (HTTP communication)
*
* @return TSA response, raw bytes (RFC 3161 encoded)
* @throws IOException
*/
private static byte[] queryServer(String tsaUrl, byte[] requestBytes) throws IOException {
// Install the all-trusting trust manager
SSLContext sc;
try {
sc = SSLContext.getInstance("SSL");
sc.init(null, new TrustManager[] { new X509TrustManager() {
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
} }, new java.security.SecureRandom());
} catch (NoSuchAlgorithmException e) {
throw new IOException(e);
} catch (KeyManagementException e) {
throw new IOException(e);
}
SSLSocketFactory defaultSSLSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
try {
URL url = new URL(tsaUrl);
URLConnection con = url.openConnection();
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestProperty("Content-Type", "application/timestamp-query");
con.setRequestProperty("Content-Transfer-Encoding", "binary");
OutputStream out = con.getOutputStream();
out.write(requestBytes);
out.close();
InputStream is = con.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = is.read(buffer, 0, buffer.length)) >= 0) {
baos.write(buffer, 0, bytesRead);
}
byte[] respBytes = baos.toByteArray();
String encoding = con.getContentEncoding();
if (encoding != null && encoding.equalsIgnoreCase("base64")) {
respBytes = Base64.decode(new String(respBytes));
}
return respBytes;
} finally {
// restore default trust manager
HttpsURLConnection.setDefaultSSLSocketFactory(defaultSSLSocketFactory);
}
}
use of javax.net.ssl.SSLSocketFactory in project AndroidStudy by tinggengyan.
the class UnsafeOkHttpClient method getUnsafeOkHttpClient.
public static OkHttpClient getUnsafeOkHttpClient() {
try {
// Create a trust manager that does not validate certificate chains
final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
} };
// Install the all-trusting trust manager
final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
// Create an ssl socket factory with our all-trusting manager
final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
OkHttpClient okHttpClient = new OkHttpClient();
OkHttpClient.Builder builder = okHttpClient.newBuilder();
builder.sslSocketFactory(sslSocketFactory);
builder.protocols(Arrays.asList(Protocol.HTTP_1_1));
builder.hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
return okHttpClient;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
use of javax.net.ssl.SSLSocketFactory in project MtgDesktopCompanion by nicho92.
the class InstallCert method install.
public static void install(String website) throws IOException, KeyManagementException, KeyStoreException, NoSuchAlgorithmException, CertificateException {
String host;
int port;
File defaultF = new File(System.getProperty("java.home") + File.separatorChar + "lib" + File.separatorChar + "security");
char[] passphrase;
String[] c = website.split(":");
host = c[0];
port = 443;
passphrase = MTGConstants.KEYSTORE_PASS.toCharArray();
File keystoreFile = new File(MTGConstants.CONF_DIR, MTGConstants.KEYSTORE_NAME);
if (!keystoreFile.exists()) {
boolean ret = keystoreFile.createNewFile();
if (ret)
FileUtils.copyFile(new File(defaultF, "cacerts"), keystoreFile);
else
throw new FileNotFoundException("Couldn't not create " + keystoreFile);
}
logger.debug("Loading KeyStore " + keystoreFile.getAbsolutePath() + "...");
try (InputStream in = new FileInputStream(keystoreFile)) {
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(in, passphrase);
SSLContext context = SSLContext.getInstance("TLS");
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
context.init(null, new TrustManager[] { tm }, null);
SSLSocketFactory factory = context.getSocketFactory();
logger.debug("Opening connection to " + host + ":" + port + "...");
try (SSLSocket socket = (SSLSocket) factory.createSocket(host, port)) {
socket.setSoTimeout(10000);
logger.debug("Starting SSL handshake...");
socket.startHandshake();
logger.debug("No errors, certificate is already trusted");
return;
} catch (SSLException e) {
logger.error(e);
}
X509Certificate[] chain = tm.chain;
if (chain == null) {
logger.error("Could not obtain server certificate chain");
return;
}
logger.debug("Server sent " + chain.length + " certificate(s):");
MessageDigest sha1 = MessageDigest.getInstance("SHA1");
MessageDigest md5 = MessageDigest.getInstance("MD5");
int i = 0;
X509Certificate cert = chain[0];
sha1.update(cert.getEncoded());
md5.update(cert.getEncoded());
String alias = host + "-" + (i++);
ks.setCertificateEntry(alias, cert);
OutputStream out = new FileOutputStream(new File(MTGConstants.CONF_DIR, MTGConstants.KEYSTORE_NAME));
ks.store(out, passphrase);
out.close();
logger.debug("Added certificate to keystore '" + new File(MTGConstants.CONF_DIR, MTGConstants.KEYSTORE_NAME) + "' using alias '" + alias + "'");
}
}
Aggregations