#android #ssl-certificate #okhttp
Вопрос:
Здесь я создаю OkHttpClient с сертификатом клиента и закрытым ключом, кажется, что все в порядке, но, пожалуйста, если кто-нибудь может это проверить.
private OkHttpClient setUpClient() {
try {
final String SECRET = "secret"; // You may also store this String somewhere more secure.
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
// Get private key
InputStream privateKeyInputStream = getResources().openRawResource(R.raw.key);
byte[] privateKeyByteArray = new byte[privateKeyInputStream.available()];
privateKeyInputStream.read(privateKeyByteArray);
String privateKeyContent = new String(privateKeyByteArray, Charset.defaultCharset())
.replace("-----BEGIN PRIVATE KEY-----", "")
.replaceAll(System.lineSeparator(), "")
.replace("-----END PRIVATE KEY-----", "");
;
byte[] rawPrivateKeyByteArray = Base64.getDecoder().decode(privateKeyContent);
KeyFactory keyFactory = KeyFactory.getInstance("EC");
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(rawPrivateKeyByteArray);
// Get certificate
InputStream certificateInputStream = getResources().openRawResource(R.raw.certificate);
Certificate certificate = certificateFactory.generateCertificate(certificateInputStream);
// Set up KeyStore
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null, SECRET.toCharArray());
keyStore.setKeyEntry("client", keyFactory.generatePrivate(keySpec), SECRET.toCharArray(), new Certificate[]{certificate});
certificateInputStream.close();
// Set up Trust Managers
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init((KeyStore) null);
TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
throw new IllegalStateException("Unexpected default trust managers:" Arrays.toString(trustManagers));
}
X509TrustManager trustManager = (X509TrustManager) trustManagers[0];
// Set up Key Managers
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, SECRET.toCharArray());
KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();
// Obtain SSL Socket Factory
SSLContext sslContext = SSLContext.getInstance("TLS");
//sslContext.init(keyManagers, trustManagers, new SecureRandom());
sslContext.init(keyManagers, new TrustManager[] { trustManager }, new SecureRandom());
SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
// Finally, return the client, which will then be used to make HTTP calls.
OkHttpClient client = new OkHttpClient.Builder()
.sslSocketFactory(sslSocketFactory, trustManager)
.connectTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30,TimeUnit.SECONDS)
.readTimeout(30,TimeUnit.SECONDS)
.build();
return client;
} catch (CertificateException | IOException | NoSuchAlgorithmException | KeyStoreException | KeyManagementException | UnrecoverableKeyException | InvalidKeySpecException e) {
e.printStackTrace();
return null;
}
}
Здесь я создаю запрос OkHttp,я создаю тело формы с параметрами, запрос, а затем отправляю запрос,код 200, но тело пустое. Может быть, что-то не так с этим звонком ?
public void run() throws Exception {
RequestBody formBody = new FormBody.Builder()
.add("action", "login")
.add("username", etUsername.getText().toString())
.add("password", etPassword.getText().toString())
.add("pushid", sharedpreferences.getString(TokenVal, "")).build();
Request request = new Request.Builder()
.url(Common.prodURL)
.post(formBody)
.addHeader("Content-Type", "multipart/form-data")
//.addHeader("Accept","multipart/form-data")
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, okhttp3.Response response) throws IOException {
try (ResponseBody responseBody = response.body()) {
if (!response.isSuccessful())
throw new IOException("Unexpected code " response);
System.out.println(responseBody.string());
}
}
});
}