Guest User

Untitled

a guest
May 24th, 2018
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. public class SslUtility {
  2. private static SslUtility mInstance = null;
  3. private Context mContext = null;
  4. private HashMap<Integer, SSLSocketFactory> mSocketFactoryMap = new HashMap<Integer, SSLSocketFactory>();
  5.  
  6.  
  7. public SslUtility(Context context) {
  8. mContext = context;
  9. }
  10. public static SslUtility getInstance( ) {
  11. if ( null == mInstance ) {
  12. throw new RuntimeException("first call must be to SslUtility.newInstance(Context) ");
  13. }
  14. return mInstance;
  15. }
  16. public static SslUtility newInstance( Context context ) {
  17. if ( null == mInstance ) {
  18. mInstance = new SslUtility( context );
  19. }
  20. return mInstance;
  21. }
  22. public SSLSocketFactory getSocketFactory(int certificateId, String certificatePassword ) {
  23. SSLSocketFactory result = mSocketFactoryMap.get(certificateId); // check to see if already created
  24. if ( ( null == result) && ( null != mContext ) ) { // not cached so need to load server certificate
  25. try {
  26. KeyStore keystoreTrust = KeyStore.getInstance("BKS"); // Bouncy Castle
  27. keystoreTrust.load(mContext.getResources().openRawResource(certificateId),
  28. certificatePassword.toCharArray());
  29. TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
  30. trustManagerFactory.init(keystoreTrust);
  31. SSLContext sslContext = SSLContext.getInstance("TLS");
  32. sslContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());
  33. result = sslContext.getSocketFactory();
  34. mSocketFactoryMap.put( certificateId, result); // cache for reuse
  35. }
  36. catch ( Exception ex ) {
  37. // log exception
  38. }
  39. }
  40. return result;
  41. }
  42.  
  43.  
  44. }
Add Comment
Please, Sign In to add comment