Example #1
0
  public static KeyPair getPrivateKey(String alias, char[] password)
      throws FileNotFoundException, IOException, CertificateException {
    try {

      KeyStore ks = KeyStore.getInstance("JKS");

      char[] passPhrase = "123456".toCharArray();
      // BASE64Encoder myB64 = new BASE64Encoder();

      File certificateFile = new File("C:\\Temp\\repositorio.jks");
      ks.load(new FileInputStream(certificateFile), passPhrase);

      // Get private key
      Key key = ks.getKey(alias, password);
      if (key instanceof PrivateKey) {
        // Get certificate of public key
        Certificate cert = ks.getCertificate(alias);

        // Get public key
        PublicKey publicKey = cert.getPublicKey();

        // Return a key pair
        return new KeyPair(publicKey, (PrivateKey) key);
      }
    } catch (UnrecoverableKeyException e) {
      System.out.print(e.getMessage());
    } catch (NoSuchAlgorithmException e) {
      System.out.print(e.getMessage());
    } catch (KeyStoreException e) {
      System.out.print(e.getMessage());
    }
    return null;
  }
Example #2
0
  private static SSLSocketFactory getSocketFactory(Boolean d) {
    // Enable debug mode to ignore all certificates
    if (DEBUG) {
      KeyStore trustStore;
      try {
        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        SSLSocketFactory sf = new DebugSSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        return sf;

      } catch (KeyStoreException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
      } catch (NoSuchAlgorithmException e3) {
        // TODO Auto-generated catch block
        e3.printStackTrace();
      } catch (CertificateException e3) {
        // TODO Auto-generated catch block
        e3.printStackTrace();
      } catch (IOException e3) {
        // TODO Auto-generated catch block
        e3.printStackTrace();
      } catch (KeyManagementException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
      } catch (UnrecoverableKeyException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
      }
    }

    return SSLSocketFactory.getSocketFactory();
  }
Example #3
0
  private 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;
  }
  /**
   * ִ��http���á�true:�ɹ� false:ʧ��
   *
   * @return boolean
   */
  public boolean call() {

    boolean isRet = false;

    // http
    if (null == this.caFile && null == this.certFile) {
      try {
        this.callHttp();
        isRet = true;
      } catch (IOException e) {
        this.errInfo = e.getMessage();
      }
      return isRet;
    }

    // https
    try {
      this.callHttps();
      isRet = true;
    } catch (UnrecoverableKeyException e) {
      this.errInfo = e.getMessage();
    } catch (KeyManagementException e) {
      this.errInfo = e.getMessage();
    } catch (CertificateException e) {
      this.errInfo = e.getMessage();
    } catch (KeyStoreException e) {
      this.errInfo = e.getMessage();
    } catch (NoSuchAlgorithmException e) {
      this.errInfo = e.getMessage();
    } catch (IOException e) {
      this.errInfo = e.getMessage();
    }

    return isRet;
  }
 /**
  * Key store 类型HttpClient
  *
  * @param keystore keystore
  * @param keyPassword keyPassword
  * @param supportedProtocols supportedProtocols
  * @param timeout timeout
  * @param retryExecutionCount retryExecutionCount
  * @return CloseableHttpClient
  */
 public static CloseableHttpClient createKeyMaterialHttpClient(
     KeyStore keystore,
     String keyPassword,
     String[] supportedProtocols,
     int timeout,
     int retryExecutionCount) {
   try {
     SSLContext sslContext =
         SSLContexts.custom()
             .useSSL()
             .loadKeyMaterial(keystore, keyPassword.toCharArray())
             .build();
     SSLConnectionSocketFactory sf =
         new SSLConnectionSocketFactory(
             sslContext,
             supportedProtocols,
             null,
             SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
     SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(timeout).build();
     return HttpClientBuilder.create()
         .setDefaultSocketConfig(socketConfig)
         .setSSLSocketFactory(sf)
         .setRetryHandler(new HttpRequestRetryHandlerImpl(retryExecutionCount))
         .build();
   } catch (KeyManagementException e) {
     e.printStackTrace();
   } catch (NoSuchAlgorithmException e) {
     e.printStackTrace();
   } catch (UnrecoverableKeyException e) {
     e.printStackTrace();
   } catch (KeyStoreException e) {
     e.printStackTrace();
   }
   return null;
 }
Example #6
0
  /*
   * Encrypt private key using Password-based encryption (PBE)
   * as defined in PKCS#5.
   *
   * NOTE: Currently pbeWithSHAAnd3-KeyTripleDES-CBC algorithmID is
   *       used to derive the key and IV.
   *
   * @return encrypted private key encoded as EncryptedPrivateKeyInfo
   */
  private byte[] encryptPrivateKey(byte[] data, char[] password)
      throws IOException, NoSuchAlgorithmException, UnrecoverableKeyException {
    byte[] key = null;

    try {
      // create AlgorithmParameters
      AlgorithmParameters algParams = getAlgorithmParameters("PBEWithSHA1AndDESede");

      // Use JCE
      SecretKey skey = getPBEKey(password);
      Cipher cipher = Cipher.getInstance("PBEWithSHA1AndDESede");
      cipher.init(Cipher.ENCRYPT_MODE, skey, algParams);
      byte[] encryptedKey = cipher.doFinal(data);

      // wrap encrypted private key in EncryptedPrivateKeyInfo
      // as defined in PKCS#8
      AlgorithmId algid = new AlgorithmId(pbeWithSHAAnd3KeyTripleDESCBC_OID, algParams);
      EncryptedPrivateKeyInfo encrInfo = new EncryptedPrivateKeyInfo(algid, encryptedKey);
      key = encrInfo.getEncoded();
    } catch (Exception e) {
      UnrecoverableKeyException uke =
          new UnrecoverableKeyException("Encrypt Private Key failed: " + e.getMessage());
      uke.initCause(e);
      throw uke;
    }

    return key;
  }
Example #7
0
  private searchMenuMgr() {

    try {
      KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
      trustStore.load(null, null);
      MySSLSocketFactory socketFactory = new MySSLSocketFactory(trustStore);
      socketFactory.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
      client = new AsyncHttpClient();
      client.setSSLSocketFactory(socketFactory);
      client.setCookieStore(new PersistentCookieStore(Login_Main.getContext()));
      client.setTimeout(10000);
    } catch (KeyStoreException e) {
      e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (CertificateException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (KeyManagementException e) {
      e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
      e.printStackTrace();
    }
  }
Example #8
0
  private void testIt() {

    String https_url = requestURL;
    URL url;

    SSLSocketFactory socketFactory = null;

    try {

      try {
        socketFactory = createSSLContext().getSocketFactory();
      } catch (UnrecoverableKeyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (CertificateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }

      url = new URL(https_url);
      HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
      conn.setDoInput(true); // Allow Inputs
      conn.setDoOutput(true); // Allow Outputs
      conn.setRequestMethod("POST");
      conn.setRequestProperty("Connection", "Keep-Alive");
      conn.setRequestProperty("ENCTYPE", "multipart/form-data");
      conn.setSSLSocketFactory(socketFactory);

      DataOutputStream dos = new DataOutputStream(conn.getOutputStream());

      conn.addRequestProperty("app_id", app_id);
      conn.addRequestProperty("app_key", app_key);

      // dump all cert info
      // print_https_cert(con);

      // dump all the content
      print_content(conn);

    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  public GoogleClientManager() {

    try {
      Initiallize();
    } catch (KeyManagementException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (KeyStoreException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  /**
   * Key store 类型HttpClient
   *
   * @param keystore
   * @param keyPassword
   * @param supportedProtocols
   * @param maxTotal
   * @param maxPerRoute
   * @return
   */
  public static HttpClient createKeyMaterialHttpClient(
      KeyStore keystore,
      String keyPassword,
      String[] supportedProtocols,
      int maxTotal,
      int maxPerRoute) {
    try {

      SSLContext sslContext =
          SSLContexts.custom()
              .useSSL()
              .loadKeyMaterial(keystore, keyPassword.toCharArray())
              .build();
      SSLConnectionSocketFactory sf =
          new SSLConnectionSocketFactory(
              sslContext,
              supportedProtocols,
              null,
              SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
      PoolingHttpClientConnectionManager poolingHttpClientConnectionManager =
          new PoolingHttpClientConnectionManager();
      poolingHttpClientConnectionManager.setMaxTotal(maxTotal);
      poolingHttpClientConnectionManager.setDefaultMaxPerRoute(maxPerRoute);
      return HttpClientBuilder.create()
          .setConnectionManager(poolingHttpClientConnectionManager)
          .setSSLSocketFactory(sf)
          .build();
    } catch (KeyManagementException e) {
      e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
      e.printStackTrace();
    } catch (KeyStoreException e) {
      e.printStackTrace();
    }
    return null;
  }
 private SSLSocketFactory getSSLSocketFactory(String keyStoreName, String password) {
   KeyStore ks = getKeyStore(keyStoreName, password);
   KeyManagerFactory keyManagerFactory = null;
   try {
     keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
     keyManagerFactory.init(ks, password.toCharArray());
     SSLContext context = SSLContext.getInstance("TLS");
     context.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom());
     return context.getSocketFactory();
   } catch (NoSuchAlgorithmException e) {
     logger.error(e.getMessage(), e);
     throw new RuntimeException(e.getMessage(), e);
   } catch (KeyStoreException e) {
     logger.error(e.getMessage(), e);
     throw new RuntimeException(e.getMessage(), e);
   } catch (UnrecoverableKeyException e) {
     logger.error(e.getMessage(), e);
     throw new RuntimeException(e.getMessage(), e);
   } catch (KeyManagementException e) {
     logger.error(e.getMessage(), e);
     throw new RuntimeException(e.getMessage(), e);
   }
 }
Example #12
0
 /**
  * Return KeyPair from the keystore stored under alias and secured by the password
  *
  * @return KeyPair - private a public key
  */
 private KeyPair loadAllKeysFromKeystore() {
   try {
     // Get private key
     Key key = keystore.getKey(alias, keyStorePasswordChar);
     if (key instanceof PrivateKey) {
       // Get certificate of public key
       Certificate cert = keystore.getCertificate(alias);
       this.cetificate = (X509Certificate) cert;
       // Get public key
       this.publicKey = cert.getPublicKey();
       this.privateKey = (PrivateKey) key;
       // Return a key pair
       return new KeyPair(publicKey, (PrivateKey) key);
     }
   } catch (UnrecoverableKeyException e) {
     e.printStackTrace();
   } catch (NoSuchAlgorithmException e) {
     e.printStackTrace();
   } catch (KeyStoreException e) {
     e.printStackTrace();
   }
   return null;
 }
Example #13
0
  private SSLSocketFactory getSSLSocketFactory() {
    if (mSocketFactory != null) return mSocketFactory;

    mSocketFactory = SSLSocketFactory.getSocketFactory();

    KeyStore trustStore;
    try {
      trustStore = KeyStore.getInstance(KeyStore.getDefaultType());

      trustStore.load(null, null);
      mSocketFactory = new MySSLSocketFactory(trustStore);

      mSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } catch (NoSuchAlgorithmException e) {
      // TODO Auto-generated catch block
      Log.e("getSSLSocketFactory", e.getLocalizedMessage(), e);

    } catch (CertificateException e) {
      // TODO Auto-generated catch block
      Log.e("getSSLSocketFactory", e.getLocalizedMessage(), e);

    } catch (IOException e) {
      // TODO Auto-generated catch block
      Log.e("getSSLSocketFactory", e.getLocalizedMessage(), e);

    } catch (KeyStoreException e) {
      // TODO Auto-generated catch block
      Log.e("getSSLSocketFactory", e.getLocalizedMessage(), e);

    } catch (KeyManagementException e) {
      Log.e("getSSLSocketFactory", e.getLocalizedMessage(), e);

    } catch (UnrecoverableKeyException e) {
      Log.e("getSSLSocketFactory", e.getLocalizedMessage(), e);
    }
    return mSocketFactory;
  }
Example #14
0
  public static void writeMsg() {
    Message msg = null;

    try {
      String data = "This is a test message.\n" + "This is another line.\n";
      LiteralMessageBuilder lmb = LiteralMessageBuilder.getInstance("OpenPGP");
      lmb.init(data);
      msg = lmb.build();
    } catch (NoSuchAlgorithmException nsae) {
      System.err.println(
          "Cannot find the OpenPGP LiteralMessageBuilder."
              + " This usually means that the Cryptix OpenPGP provider is not "
              + "installed correctly.");
      nsae.printStackTrace();
      System.exit(-1);
    } catch (MessageException me) {
      System.err.println("Creating the literal message failed.");
      me.printStackTrace();
      System.exit(-1);
    }

    // **********************************************************************
    // Sign the message.
    //
    // Note that signing usually comes before encryption, such that
    // unauthorized parties cannot see who signed the message.
    // **********************************************************************
    try {

      SignedMessageBuilder smb = SignedMessageBuilder.getInstance("OpenPGP");

      // use the following line for compatibility with older PGP versions

      // SignedMessageBuilder smb =
      //     SignedMessageBuilder.getInstance("OpenPGP/V3");

      smb.init(msg);
      smb.addSigner(clientPrivateKey, "TestingPassphrase".toCharArray());

      msg = smb.build();

    } catch (NoSuchAlgorithmException nsae) {
      System.err.println(
          "Cannot find the OpenPGP SignedMessageBuilder. "
              + "This usually means that the Cryptix OpenPGP provider is not "
              + "installed correctly.");
      nsae.printStackTrace();
      System.exit(-1);
    } catch (UnrecoverableKeyException uke) {
      System.err.println("Incorrect passphrase.");
      uke.printStackTrace();
      System.exit(-1);
    } catch (MessageException me) {
      System.err.println("Generating the message failed.");
      me.printStackTrace();
      System.exit(-1);
    }

    // **********************************************************************
    // Armour the message and write it to disk
    // **********************************************************************
    try {

      PGPArmouredMessage armoured;

      armoured = new PGPArmouredMessage(msg);
      FileOutputStream out = new FileOutputStream("signed.asc");
      out.write(armoured.getEncoded());
      out.close();

    } catch (MessageException me) {
      System.err.println("Writing the encrypted message failed.");
      me.printStackTrace();
      System.exit(-1);
    } catch (IOException ioe) {
      System.err.println("Writing the encrypted message failed.");
      ioe.printStackTrace();
      System.exit(-1);
    }

    // **********************************************************************
    // Encrypt the message.
    // **********************************************************************
    try {

      EncryptedMessageBuilder emb = EncryptedMessageBuilder.getInstance("OpenPGP");
      emb.init(msg);
      emb.addRecipient(serverPublicKey);
      msg = emb.build();

    } catch (NoSuchAlgorithmException nsae) {
      System.err.println(
          "Cannot find the OpenPGP "
              + "EncryptedMessageBuilder. "
              + "This usually means that the Cryptix OpenPGP provider is not "
              + "installed correctly.");
      nsae.printStackTrace();
      System.exit(-1);
    } catch (MessageException me) {
      System.err.println("Creating the encrypted message failed.");
      me.printStackTrace();
      System.exit(-1);
    }

    // **********************************************************************
    // Armour the message and write it to disk
    // **********************************************************************
    try {

      PGPArmouredMessage armoured;

      armoured = new PGPArmouredMessage(msg);
      FileOutputStream out = new FileOutputStream("encrypted-signed.asc");
      out.write(armoured.getEncoded());
      out.close();

    } catch (MessageException me) {
      System.err.println("Writing the encrypted message failed.");
      me.printStackTrace();
      System.exit(-1);
    } catch (IOException ioe) {
      System.err.println("Writing the encrypted message failed.");
      ioe.printStackTrace();
      System.exit(-1);
    }
  }
Example #15
0
  public PushManager get(Product product) {

    if (StringUtils.isBlank(product.getDevCertPath())
        || StringUtils.isBlank(product.getDevCertPass())
        || StringUtils.isBlank(product.getCertPath())
        || StringUtils.isBlank(product.getCertPass())) {
      logger.error("Product iOS Push Service Miss Cert Path and Password. {}", product);
      return null;
    }

    PushManager service = mapping.get(product.getId());
    if (service == null) {

      ApnsEnvironment apnsEnvironment = null;
      SSLContext sslContext = null;

      try {
        if (sandBox) {
          apnsEnvironment = ApnsEnvironment.getSandboxEnvironment();
          sslContext =
              SSLContextUtil.createDefaultSSLContext(
                  product.getDevCertPath(), product.getDevCertPass());
        } else {
          apnsEnvironment = ApnsEnvironment.getProductionEnvironment();
          sslContext =
              SSLContextUtil.createDefaultSSLContext(product.getCertPath(), product.getCertPass());
        }
      } catch (KeyStoreException e) {
        logger.error(e.getMessage(), e);
      } catch (NoSuchAlgorithmException e) {
        logger.error(e.getMessage(), e);
      } catch (CertificateException e) {
        logger.error(e.getMessage(), e);
      } catch (UnrecoverableKeyException e) {
        logger.error(e.getMessage(), e);
      } catch (KeyManagementException e) {
        logger.error(e.getMessage(), e);
      } catch (IOException e) {
        logger.error(e.getMessage(), e);
      }

      PushManagerConfiguration configuration = new PushManagerConfiguration();
      configuration.setConcurrentConnectionCount(1);

      final PushManager<SimpleApnsPushNotification> pushManager =
          new PushManager<SimpleApnsPushNotification>(
              apnsEnvironment,
              sslContext,
              null, // Optional: custom event loop group
              null, // Optional: custom ExecutorService for calling listeners
              null, // Optional: custom BlockingQueue implementation
              configuration,
              "ApnsPushManager-" + product.getId());

      pushManager.registerRejectedNotificationListener(new PushRejectedNotificationListener());
      pushManager.registerFailedConnectionListener(new PushFailedConnectionListener());

      pushManager.start();

      //             ApnsServiceBuilder builder =  APNS.newService();
      //            if (sandBox){
      //                builder.withCert(product.getDevCertPath(), product.getDevCertPass());
      //                builder.withSandboxDestination();
      //            }else{
      //                builder.withCert(product.getCertPath(), product.getCertPass());
      //                builder.withProductionDestination();
      //            }
      //            service =
      // builder.asPool(10).withCacheLength(Integer.MAX_VALUE).withDelegate(delegateAdapter).asQueued().build();

      mapping.put(product.getId(), pushManager);
      service = pushManager;
    }

    return service;
  }
Example #16
0
  /**
   * Sign file.
   *
   * @param signingDTO sign informations
   * @param pdfSignedFile signed pdf returned
   */
  public void sign(final DigitalSigningDTO signingDTO) {
    if (signingDTO != null) {

      try {
        Security.addProvider(new BouncyCastleProvider());
        final File alfTempDir = TempFileProvider.getTempDir();

        if (alfTempDir != null) {
          final String keyType =
              (String) nodeService.getProperty(signingDTO.getKeyFile(), SigningModel.PROP_KEYTYPE);

          if (SigningConstants.KEY_TYPE_X509.equals(keyType)) {
            // Sign the file
            final KeyStore ks = KeyStore.getInstance("pkcs12");
            final ContentReader keyContentReader = getReader(signingDTO.getKeyFile());

            if (keyContentReader != null && ks != null && signingDTO.getKeyPassword() != null) {

              final List<AlfrescoRuntimeException> errors =
                  new ArrayList<AlfrescoRuntimeException>();

              // Get crypted secret key and decrypt it
              final Serializable encryptedPropertyValue =
                  nodeService.getProperty(
                      signingDTO.getKeyFile(), SigningModel.PROP_KEYCRYPTSECRET);
              final Serializable decryptedPropertyValue =
                  metadataEncryptor.decrypt(
                      SigningModel.PROP_KEYCRYPTSECRET, encryptedPropertyValue);

              // Decrypt key content
              InputStream decryptedKeyContent;
              try {
                decryptedKeyContent =
                    CryptUtils.decrypt(
                        decryptedPropertyValue.toString(),
                        keyContentReader.getContentInputStream());
              } catch (Throwable e) {
                log.error(e);
                throw new AlfrescoRuntimeException(e.getMessage(), e);
              }

              ks.load(
                  new ByteArrayInputStream(IOUtils.toByteArray(decryptedKeyContent)),
                  signingDTO.getKeyPassword().toCharArray());

              final String alias =
                  (String)
                      nodeService.getProperty(signingDTO.getKeyFile(), SigningModel.PROP_KEYALIAS);

              final PrivateKey key =
                  (PrivateKey) ks.getKey(alias, signingDTO.getKeyPassword().toCharArray());
              final Certificate[] chain = ks.getCertificateChain(alias);

              final Iterator<NodeRef> itFilesToSign = signingDTO.getFilesToSign().iterator();
              while (itFilesToSign.hasNext()) {
                final NodeRef nodeRefToSign = itFilesToSign.next();
                final AlfrescoRuntimeException exception =
                    signFile(nodeRefToSign, signingDTO, alfTempDir, alias, ks, key, chain);
                if (exception != null) {
                  // Error on the file process
                  errors.add(exception);
                }
              }

              if (errors != null && errors.size() > 0) {
                final StringBuffer allErrors = new StringBuffer();
                final Iterator<AlfrescoRuntimeException> itErrors = errors.iterator();
                if (errors.size() > 1) {
                  allErrors.append("\n");
                }
                while (itErrors.hasNext()) {
                  final AlfrescoRuntimeException alfrescoRuntimeException = itErrors.next();
                  allErrors.append(alfrescoRuntimeException.getMessage());
                  if (itErrors.hasNext()) {
                    allErrors.append("\n");
                  }
                }
                throw new RuntimeException(allErrors.toString());
              }

            } else {
              log.error("Unable to get key content, key type or key password.");
              throw new AlfrescoRuntimeException(
                  "Unable to get key content, key type or key password.");
            }
          }
        } else {
          log.error("Unable to get temporary directory.");
          throw new AlfrescoRuntimeException("Unable to get temporary directory.");
        }
      } catch (KeyStoreException e) {
        log.error(e);
        throw new AlfrescoRuntimeException(e.getMessage(), e);
      } catch (NoSuchAlgorithmException e) {
        log.error(e);
        throw new AlfrescoRuntimeException(e.getMessage(), e);
      } catch (CertificateException e) {
        log.error(e);
        throw new AlfrescoRuntimeException(e.getMessage(), e);
      } catch (IOException e) {
        log.error(e);
        throw new AlfrescoRuntimeException(e.getMessage(), e);
      } catch (UnrecoverableKeyException e) {
        log.error(e);
        throw new AlfrescoRuntimeException(e.getMessage(), e);
      }
    } else {
      log.error("No object with signing informations.");
      throw new AlfrescoRuntimeException("No object with signing informations.");
    }
  }
  @Override
  public void contextInitialized(ServletContextEvent arg0) {
    final String S_ProcName = "contextInitialized";

    Properties props = System.getProperties();
    if (null == CFBamSchemaPool.getSchemaPool()) {
      try {
        Context ctx = new InitialContext();
        String poolClassName = (String) ctx.lookup("java:comp/env/CFBam24PoolClass");
        if ((poolClassName == null) || (poolClassName.length() <= 0)) {
          throw CFLib.getDefaultExceptionFactory()
              .newNullArgumentException(
                  getClass(), S_ProcName, 0, "JNDI lookup for CFBam24PoolClass");
        }

        Class poolClass = Class.forName(poolClassName);
        if (poolClass == null) {
          throw CFLib.getDefaultExceptionFactory()
              .newNullArgumentException(
                  getClass(),
                  S_ProcName,
                  0,
                  "CFBam24PoolClass \"" + poolClassName + "\" not found.");
        }

        Object obj = poolClass.newInstance();
        if (obj instanceof CFBamSchemaPool) {
          CFBamSchemaPool newPool = (CFBamSchemaPool) obj;
          newPool.setConfigurationFile(null);
          newPool.setJndiName("java:comp/env/CFBam24Connection");
          CFBamSchemaPool.setSchemaPool(newPool);
        } else {
          throw CFLib.getDefaultExceptionFactory()
              .newRuntimeException(
                  getClass(), S_ProcName, "Problems constructing an instance of " + poolClassName);
        }

        String smtpHost = (String) ctx.lookup("java:comp/env/CFBam24SmtpHost");
        if ((smtpHost == null) || (smtpHost.length() <= 0)) {
          throw CFLib.getDefaultExceptionFactory()
              .newNullArgumentException(
                  getClass(), S_ProcName, 0, "JNDI lookup for CFBam24SmtpHost");
        }
        props.setProperty("mail.smtp.host", smtpHost);

        String smtpStartTLS = (String) ctx.lookup("java:comp/env/CFBam24SmtpStartTLS");
        if ((smtpHost == null) || (smtpHost.length() <= 0)) {
          throw CFLib.getDefaultExceptionFactory()
              .newNullArgumentException(
                  getClass(), S_ProcName, 0, "JNDI lookup for CFBam24SmtpStartTLS");
        }
        props.setProperty("mail.smtp.starttls.enable", smtpStartTLS);

        String smtpSocketFactoryClass =
            (String) ctx.lookup("java:comp/env/CFBam24SmtpSocketFactoryClass");
        if ((smtpSocketFactoryClass == null) || (smtpSocketFactoryClass.length() <= 0)) {
          throw CFLib.getDefaultExceptionFactory()
              .newNullArgumentException(
                  getClass(), S_ProcName, 0, "JNDI lookup for CFBam24SmtpSocketFactoryClass");
        }
        props.setProperty("mail.smtp.socketFactory.class", smtpSocketFactoryClass);

        props.setProperty("mail.smtp.socketFactory.fallback", "false");

        String smtpPort = (String) ctx.lookup("java:comp/env/CFBam24SmtpPort");
        if ((smtpPort == null) || (smtpPort.length() <= 0)) {
          throw CFLib.getDefaultExceptionFactory()
              .newNullArgumentException(
                  getClass(), S_ProcName, 0, "JNDI lookup for CFBam24SmtpPort");
        }
        props.setProperty("mail.smtp.port", smtpPort);
        props.setProperty("mail.smtp.socketFactory.port", smtpPort);

        props.setProperty("mail.smtps.auth", "true");

        props.put("mail.smtps.quitwait", "false");

        String smtpEmailFrom = (String) ctx.lookup("java:comp/env/CFBam24SmtpEmailFrom");
        if ((smtpEmailFrom == null) || (smtpEmailFrom.length() <= 0)) {
          throw CFLib.getDefaultExceptionFactory()
              .newNullArgumentException(
                  getClass(), S_ProcName, 0, "JNDI lookup for CFBam24SmtpEmailFrom");
        }

        smtpUsername = (String) ctx.lookup("java:comp/env/CFBam24SmtpUsername");
        if ((smtpUsername == null) || (smtpUsername.length() <= 0)) {
          throw CFLib.getDefaultExceptionFactory()
              .newNullArgumentException(
                  getClass(), S_ProcName, 0, "JNDI lookup for CFBam24SmtpUsername");
        }

        smtpPassword = (String) ctx.lookup("java:comp/env/CFBam24SmtpPassword");
        if ((smtpPassword == null) || (smtpPassword.length() <= 0)) {
          throw CFLib.getDefaultExceptionFactory()
              .newNullArgumentException(
                  getClass(), S_ProcName, 0, "JNDI lookup for CFBam24SmtpPassword");
        }

        String serverKeyStore;
        try {
          serverKeyStore = (String) ctx.lookup("java:comp/env/CFBam24ServerKeyStore");
        } catch (NamingException e) {
          serverKeyStore = null;
        }

        String keyStorePassword;
        try {
          keyStorePassword = (String) ctx.lookup("java:comp/env/CFBam24KeyStorePassword");
        } catch (NamingException e) {
          keyStorePassword = null;
        }

        String keyName;
        try {
          keyName = (String) ctx.lookup("java:comp/env/CFBam24KeyName");
        } catch (NamingException e) {
          keyName = null;
        }

        String keyPassword;
        try {
          keyPassword = (String) ctx.lookup("java:comp/env/CFBam24KeyPassword");
        } catch (NamingException e) {
          keyPassword = null;
        }

        if (((serverKeyStore != null) && (serverKeyStore.length() > 0))
            && (keyStorePassword != null)
            && ((keyName != null) && (keyName.length() > 0))
            && (keyPassword != null)) {
          KeyStore keyStore = null;
          File keystoreFile = new File(serverKeyStore);
          if (!keystoreFile.exists()) {
            throw CFLib.getDefaultExceptionFactory()
                .newUsageException(
                    getClass(),
                    S_ProcName,
                    "CFBam24ServerKeyStore file \"" + serverKeyStore + "\" does not exist.");
          } else if (!keystoreFile.isFile()) {
            throw CFLib.getDefaultExceptionFactory()
                .newUsageException(
                    getClass(),
                    S_ProcName,
                    "CFBam24ServerKeyStore file \"" + serverKeyStore + "\" is not a file.");
          } else if (!keystoreFile.canRead()) {
            throw CFLib.getDefaultExceptionFactory()
                .newUsageException(
                    getClass(),
                    S_ProcName,
                    "Permission denied attempting to read CFBam24ServerKeyStore file \""
                        + serverKeyStore
                        + "\".");
          }

          try {
            keyStore = KeyStore.getInstance("jceks");
            char[] caPassword = keyStorePassword.toCharArray();
            FileInputStream input = new FileInputStream(serverKeyStore);
            keyStore.load(input, caPassword);
            input.close();
            Certificate publicKeyCertificate = keyStore.getCertificate(keyName);
            if (publicKeyCertificate == null) {
              throw CFLib.getDefaultExceptionFactory()
                  .newUsageException(
                      getClass(),
                      S_ProcName,
                      "Could not read CFBam24KeyName \""
                          + keyName
                          + "\" from CFBam24ServerKeyStore file \""
                          + serverKeyStore
                          + "\".");
            }
            publicKey = publicKeyCertificate.getPublicKey();
            char[] caKeyPassword = keyPassword.toCharArray();
            Key key = keyStore.getKey(keyName, caKeyPassword);
            if (key instanceof PrivateKey) {
              privateKey = (PrivateKey) key;
            } else {
              throw CFLib.getDefaultExceptionFactory()
                  .newUnsupportedClassException(getClass(), S_ProcName, "key", key, "PrivateKey");
            }

            getServerInfo();
          } catch (CertificateException x) {
            publicKey = null;
            privateKey = null;
            throw CFLib.getDefaultExceptionFactory()
                .newRuntimeException(
                    getClass(),
                    S_ProcName,
                    "Could not open keystore due to CertificateException -- " + x.getMessage(),
                    x);
          } catch (IOException x) {
            publicKey = null;
            privateKey = null;
            throw CFLib.getDefaultExceptionFactory()
                .newRuntimeException(
                    getClass(),
                    S_ProcName,
                    "Could not open keystore due to IOException -- " + x.getMessage(),
                    x);
          } catch (KeyStoreException x) {
            publicKey = null;
            privateKey = null;
            throw CFLib.getDefaultExceptionFactory()
                .newRuntimeException(
                    getClass(),
                    S_ProcName,
                    "Could not open keystore due to KeyStoreException -- " + x.getMessage(),
                    x);
          } catch (NoSuchAlgorithmException x) {
            publicKey = null;
            privateKey = null;
            throw CFLib.getDefaultExceptionFactory()
                .newRuntimeException(
                    getClass(),
                    S_ProcName,
                    "Could not open keystore due to NoSuchAlgorithmException -- " + x.getMessage(),
                    x);
          } catch (UnrecoverableKeyException x) {
            publicKey = null;
            privateKey = null;
            throw CFLib.getDefaultExceptionFactory()
                .newRuntimeException(
                    getClass(),
                    S_ProcName,
                    "Could not access key due to UnrecoverableKeyException -- " + x.getMessage(),
                    x);
          } catch (RuntimeException x) {
            publicKey = null;
            privateKey = null;
            throw x;
          }
        } else if ((serverKeyStore != null)
            || (keyStorePassword != null)
            || (keyName != null)
            || (keyPassword != null)) {
          publicKey = null;
          privateKey = null;
          throw CFLib.getDefaultExceptionFactory()
              .newUsageException(
                  getClass(),
                  S_ProcName,
                  "All or none of CFBam24ServerKeyStore, "
                      + "CFBam24KeyStorePassword, "
                      + "CFBam24KeyName, and "
                      + "CFBam24KeyPassword must be configured");
        } else {
          getServerInfo();
          try {
            serverInfo.initServerKeys();
          } catch (Exception x) {
            throw CFLib.getDefaultExceptionFactory()
                .newRuntimeException(
                    getClass(),
                    S_ProcName,
                    "Caught "
                        + x.getClass().getName()
                        + " during initServerKeys() -- "
                        + x.getMessage(),
                    x);
          }
        }
      } catch (ClassNotFoundException e) {
        publicKey = null;
        privateKey = null;
        throw CFLib.getDefaultExceptionFactory()
            .newRuntimeException(
                getClass(), S_ProcName, "Caught ClassNotFoundException -- " + e.getMessage(), e);
      } catch (IllegalAccessException e) {
        publicKey = null;
        privateKey = null;
        throw CFLib.getDefaultExceptionFactory()
            .newRuntimeException(
                getClass(),
                S_ProcName,
                "Caught IllegalAccessException trying to construct newInstance() -- "
                    + e.getMessage(),
                e);
      } catch (InstantiationException e) {
        publicKey = null;
        privateKey = null;
        throw CFLib.getDefaultExceptionFactory()
            .newRuntimeException(
                getClass(),
                S_ProcName,
                "Caught InstantiationException trying to construct newInstance() -- "
                    + e.getMessage(),
                e);
      } catch (NamingException e) {
        publicKey = null;
        privateKey = null;
        throw CFLib.getDefaultExceptionFactory()
            .newRuntimeException(
                getClass(), S_ProcName, "Caught NamingException -- " + e.getMessage(), e);
      }
    }
  }
Example #18
0
  /**
   * Performs test signatures for the specified keys or for all if "all" specified.
   *
   * @param keyStore Loaded keystore to read keys from
   * @param alias Alias of key to test or "all" to test all
   * @param authCode Key password (if used, ie for JKS only)
   * @param signatureProvider Provider for creating the signature
   * @return The results for each key found
   * @throws CryptoTokenOfflineException In case the key could not be used
   */
  public static Collection<KeyTestResult> testKey(
      KeyStore keyStore, String alias, char[] authCode, String signatureProvider)
      throws CryptoTokenOfflineException {
    if (LOG.isDebugEnabled()) {
      LOG.debug("testKey for alias: " + alias);
    }

    final Collection<KeyTestResult> result = new LinkedList<KeyTestResult>();

    try {
      final Enumeration<String> e = keyStore.aliases();
      while (e.hasMoreElements()) {
        final String keyAlias = e.nextElement();
        if (alias.equalsIgnoreCase(ICryptoToken.ALL_KEYS) || alias.equals(keyAlias)) {
          if (LOG.isDebugEnabled()) {
            LOG.debug("checking keyAlias: " + keyAlias);
          }

          if (keyStore.isKeyEntry(keyAlias)) {
            String status;
            String publicKeyHash = null;
            boolean success = false;
            try {
              final PrivateKey privateKey = (PrivateKey) keyStore.getKey(keyAlias, authCode);
              final Certificate entryCert = keyStore.getCertificate(keyAlias);
              if (entryCert != null) {
                final PublicKey publicKey = entryCert.getPublicKey();
                publicKeyHash = createKeyHash(publicKey);
                testSignAndVerify(privateKey, publicKey, signatureProvider);
                success = true;
                status = "";
              } else {
                status = "Not testing keys with alias " + keyAlias + ". No certificate exists.";
              }
            } catch (ClassCastException ce) {
              status = "Not testing keys with alias " + keyAlias + ". Not a private key.";
            } catch (InvalidKeyException ex) {
              LOG.error("Error testing key: " + keyAlias, ex);
              status = ex.getMessage();
            } catch (KeyStoreException ex) {
              LOG.error("Error testing key: " + keyAlias, ex);
              status = ex.getMessage();
            } catch (NoSuchAlgorithmException ex) {
              LOG.error("Error testing key: " + keyAlias, ex);
              status = ex.getMessage();
            } catch (NoSuchProviderException ex) {
              LOG.error("Error testing key: " + keyAlias, ex);
              status = ex.getMessage();
            } catch (SignatureException ex) {
              LOG.error("Error testing key: " + keyAlias, ex);
              status = ex.getMessage();
            } catch (UnrecoverableKeyException ex) {
              LOG.error("Error testing key: " + keyAlias, ex);
              status = ex.getMessage();
            }
            result.add(new KeyTestResult(keyAlias, success, status, publicKeyHash));
          }
        }
      }
    } catch (KeyStoreException ex) {
      throw new CryptoTokenOfflineException(ex);
    }

    if (LOG.isDebugEnabled()) {
      LOG.debug("<testKey");
    }
    return result;
  }
  private void m(Context context) {
    SSLSocket sslSocket = null;
    try {
      boolean connected = false;
      if (sslSocket == null || sslSocket.isClosed() || !sslSocket.isConnected()) {
        if (sslSocket != null && !sslSocket.isClosed()) {
          sslSocket.close();
        }

        Log.i(getClass().toString(), "Connecting...");
        //            messages.getText().append("Connecting...");
        final KeyStore keyStore = KeyStore.getInstance("BKS");
        keyStore.load(context.getResources().openRawResource(R.raw.clientkey), null);

        final KeyManagerFactory keyManager =
            KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManager.init(keyStore, null);
        // keyManager.init(null, null);

        final TrustManagerFactory trustFactory =
            TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustFactory.init(keyStore);

        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(
            keyManager.getKeyManagers(), trustFactory.getTrustManagers(), new SecureRandom());
        final SSLSocketFactory delegate = sslContext.getSocketFactory();
        SocketFactory factory =
            new SSLSocketFactory() {
              @Override
              public Socket createSocket(String host, int port)
                  throws IOException, UnknownHostException {
                InetAddress addr = InetAddress.getByName(host);
                injectHostname(addr, host);
                return delegate.createSocket(addr, port);
              }

              @Override
              public Socket createSocket(InetAddress host, int port) throws IOException {
                return delegate.createSocket(host, port);
              }

              @Override
              public Socket createSocket(
                  String host, int port, InetAddress localHost, int localPort)
                  throws IOException, UnknownHostException {
                return delegate.createSocket(host, port, localHost, localPort);
              }

              @Override
              public Socket createSocket(
                  InetAddress address, int port, InetAddress localAddress, int localPort)
                  throws IOException {
                return delegate.createSocket(address, port, localAddress, localPort);
              }

              private void injectHostname(InetAddress address, String host) {
                try {
                  Field field = InetAddress.class.getDeclaredField("hostName");
                  field.setAccessible(true);
                  field.set(address, host);
                } catch (Exception ignored) {
                }
              }

              @Override
              public Socket createSocket(Socket s, String host, int port, boolean autoClose)
                  throws IOException {
                injectHostname(s.getInetAddress(), host);
                return delegate.createSocket(s, host, port, autoClose);
              }

              @Override
              public String[] getDefaultCipherSuites() {
                return delegate.getDefaultCipherSuites();
              }

              @Override
              public String[] getSupportedCipherSuites() {
                return delegate.getSupportedCipherSuites();
              }
            };
        sslSocket = (SSLSocket) factory.createSocket("195.248.169.76", 4445);
        sslSocket.setSoTimeout(20000);
        sslSocket.setUseClientMode(true);
        connected = true;
        Log.i(getClass().toString(), "Connected.");
        //                messages.getText().append("Connected.");
      }

      // Secure
      if (connected) {
        Log.i(getClass().toString(), "Securing...");
        //                messages.getText().append("Securing...");
        SSLSession session = sslSocket.getSession();
        boolean secured = session.isValid();
        if (secured) {
          Log.i(getClass().toString(), "Secured.");
          //                    messages.getText().append("Secured.");
        }
      }
    } catch (CertificateException e) {
      e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
      e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (KeyStoreException e) {
      e.printStackTrace();
    } catch (KeyManagementException e) {
      e.printStackTrace();
    } catch (UnknownHostException e) {
      e.printStackTrace();
    } catch (SocketException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Example #20
0
  /**
   * Returns the key associated with the given alias, using the given password to recover it.
   *
   * @param alias the alias name
   * @param password the password for recovering the key. This password is used internally as the
   *     key is exported in a PKCS12 format.
   * @return the requested key, or null if the given alias does not exist or does not identify a
   *     <i>key entry</i>.
   * @exception NoSuchAlgorithmException if the algorithm for recovering the key cannot be found
   * @exception UnrecoverableKeyException if the key cannot be recovered (e.g., the given password
   *     is wrong).
   */
  public Key engineGetKey(String alias, char[] password)
      throws NoSuchAlgorithmException, UnrecoverableKeyException {
    permissionCheck();

    // An empty password is rejected by MacOS API, no private key data
    // is exported. If no password is passed (as is the case when
    // this implementation is used as browser keystore in various
    // deployment scenarios like Webstart, JFX and applets), create
    // a dummy password so MacOS API is happy.
    if (password == null || password.length == 0) {
      // Must not be a char array with only a 0, as this is an empty
      // string.
      if (random == null) {
        random = new SecureRandom();
      }
      password = Long.toString(random.nextLong()).toCharArray();
    }

    Object entry = entries.get(alias.toLowerCase());

    if (entry == null || !(entry instanceof KeyEntry)) {
      return null;
    }

    // This call gives us a PKCS12 bag, with the key inside it.
    byte[] exportedKeyInfo = _getEncodedKeyData(((KeyEntry) entry).keyRef, password);
    if (exportedKeyInfo == null) {
      return null;
    }

    PrivateKey returnValue = null;

    try {
      byte[] pkcs8KeyData = fetchPrivateKeyFromBag(exportedKeyInfo);
      byte[] encryptedKey;
      AlgorithmParameters algParams;
      ObjectIdentifier algOid;
      try {
        // get the encrypted private key
        EncryptedPrivateKeyInfo encrInfo = new EncryptedPrivateKeyInfo(pkcs8KeyData);
        encryptedKey = encrInfo.getEncryptedData();

        // parse Algorithm parameters
        DerValue val = new DerValue(encrInfo.getAlgorithm().encode());
        DerInputStream in = val.toDerInputStream();
        algOid = in.getOID();
        algParams = parseAlgParameters(in);

      } catch (IOException ioe) {
        UnrecoverableKeyException uke =
            new UnrecoverableKeyException(
                "Private key not stored as " + "PKCS#8 EncryptedPrivateKeyInfo: " + ioe);
        uke.initCause(ioe);
        throw uke;
      }

      // Use JCE to decrypt the data using the supplied password.
      SecretKey skey = getPBEKey(password);
      Cipher cipher = Cipher.getInstance(algOid.toString());
      cipher.init(Cipher.DECRYPT_MODE, skey, algParams);
      byte[] decryptedPrivateKey = cipher.doFinal(encryptedKey);
      PKCS8EncodedKeySpec kspec = new PKCS8EncodedKeySpec(decryptedPrivateKey);

      // Parse the key algorithm and then use a JCA key factory to create the private key.
      DerValue val = new DerValue(decryptedPrivateKey);
      DerInputStream in = val.toDerInputStream();

      // Ignore this -- version should be 0.
      int i = in.getInteger();

      // Get the Algorithm ID next
      DerValue[] value = in.getSequence(2);
      AlgorithmId algId = new AlgorithmId(value[0].getOID());
      String algName = algId.getName();

      // Get a key factory for this algorithm.  It's likely to be 'RSA'.
      KeyFactory kfac = KeyFactory.getInstance(algName);
      returnValue = kfac.generatePrivate(kspec);
    } catch (Exception e) {
      UnrecoverableKeyException uke =
          new UnrecoverableKeyException("Get Key failed: " + e.getMessage());
      uke.initCause(e);
      throw uke;
    }

    return returnValue;
  }
  protected @Nonnull HttpClient getClient() throws CloudException, InternalException {
    ProviderContext ctx = provider.getContext();

    if (ctx == null) {
      throw new AzureConfigException("No context was defined for this request");
    }
    String endpoint = ctx.getEndpoint();

    if (endpoint == null) {
      throw new AzureConfigException("No cloud endpoint was defined");
    }
    boolean ssl = endpoint.startsWith("https");
    int targetPort;

    try {
      URI uri = new URI(endpoint);

      targetPort = uri.getPort();
      if (targetPort < 1) {
        targetPort = (ssl ? 443 : 80);
      }
    } catch (URISyntaxException e) {
      throw new AzureConfigException(e);
    }
    HttpParams params = new BasicHttpParams();
    SchemeRegistry registry = new SchemeRegistry();

    try {
      registry.register(
          new Scheme(
              ssl ? "https" : "http",
              targetPort,
              new AzureSSLSocketFactory(new AzureX509(provider))));
    } catch (KeyManagementException e) {
      e.printStackTrace();
      throw new InternalException(e);
    } catch (UnrecoverableKeyException e) {
      e.printStackTrace();
      throw new InternalException(e);
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
      throw new InternalException(e);
    } catch (KeyStoreException e) {
      e.printStackTrace();
      throw new InternalException(e);
    }

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
    HttpProtocolParams.setUserAgent(params, "Dasein Cloud");
    params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
    params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 300000);

    HttpProxyConfig httpProxyConfig = getHttpProxyConfigData();
    if (httpProxyConfig != null) {
      params.setParameter(
          ConnRoutePNames.DEFAULT_PROXY,
          new HttpHost(httpProxyConfig.getHost(), httpProxyConfig.getPort()));
      registry.register(new Scheme("http", httpProxyConfig.getPort(), new PlainSocketFactory()));
    }

    ClientConnectionManager ccm = new ThreadSafeClientConnManager(registry);

    return new DefaultHttpClient(ccm, params);
  }