Repositorio del curso CCOM4030 el semestre B91 del proyecto Artesanías con el Instituto de Cultura

TLSConfiguration.java 1.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package com.silkimen.http;
  2. import java.io.IOException;
  3. import java.security.GeneralSecurityException;
  4. import java.security.SecureRandom;
  5. import javax.net.ssl.HostnameVerifier;
  6. import javax.net.ssl.KeyManager;
  7. import javax.net.ssl.SSLContext;
  8. import javax.net.ssl.SSLSocketFactory;
  9. import javax.net.ssl.TrustManager;
  10. import com.silkimen.http.TLSSocketFactory;
  11. public class TLSConfiguration {
  12. private TrustManager[] trustManagers;
  13. private KeyManager[] keyManagers;
  14. private HostnameVerifier hostnameVerifier;
  15. private SSLSocketFactory socketFactory;
  16. public void setHostnameVerifier(HostnameVerifier hostnameVerifier) {
  17. this.hostnameVerifier = hostnameVerifier;
  18. }
  19. public void setKeyManagers(KeyManager[] keyManagers) {
  20. this.keyManagers = keyManagers;
  21. this.socketFactory = null;
  22. }
  23. public void setTrustManagers(TrustManager[] trustManagers) {
  24. this.trustManagers = trustManagers;
  25. this.socketFactory = null;
  26. }
  27. public HostnameVerifier getHostnameVerifier() {
  28. return this.hostnameVerifier;
  29. }
  30. public SSLSocketFactory getTLSSocketFactory() throws IOException {
  31. if (this.socketFactory != null) {
  32. return this.socketFactory;
  33. }
  34. try {
  35. SSLContext context = SSLContext.getInstance("TLS");
  36. context.init(this.keyManagers, this.trustManagers, new SecureRandom());
  37. if (android.os.Build.VERSION.SDK_INT < 20) {
  38. this.socketFactory = new TLSSocketFactory(context);
  39. } else {
  40. this.socketFactory = context.getSocketFactory();
  41. }
  42. return this.socketFactory;
  43. } catch (GeneralSecurityException e) {
  44. IOException ioException = new IOException("Security exception occured while configuring TLS context");
  45. ioException.initCause(e);
  46. throw ioException;
  47. }
  48. }
  49. }