Tuesday 21 August 2012

How to read HTTPs URL in JAVA


Hi,

Below are a java method that read HTTS response from URL.I hope,it will be helpful. 

// @required import files 
import java.io.IOException;
import java.io.StringWriter;
import java.net.HttpURLConnection;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.SingleClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
//end


// java method
@SuppressWarnings("deprecation")
    private static String getHttpResponseAsString(String uri) throws Exception {
        TrustManager[] trustAllCerts = new TrustManager[]{
            new X509TrustManager() {
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
                public void checkClientTrusted(
                    java.security.cert.X509Certificate[] certs, String authType) {
                }
                public void checkServerTrusted(
                    java.security.cert.X509Certificate[] certs, String authType) {
                }
            }
        };
        HttpResponse resp = null;
        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
  
            SchemeRegistry registry = new SchemeRegistry();
            SSLSocketFactory socketFactory = new SSLSocketFactory(sc);
            socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
            HttpParams params = new BasicHttpParams();
            registry.register(new Scheme("https", socketFactory, 443));
            SingleClientConnManager mgr = new SingleClientConnManager(params, registry);
            DefaultHttpClient httpClient = new DefaultHttpClient(mgr, params);
          
            HttpGet get = new HttpGet(uri);
            UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("admin", "password");
          
            httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials);
            resp = httpClient.execute(get);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            throw new Exception(e.getMessage());
        } catch (IOException e) {
            throw new Exception(e.getMessage());
        } catch (Exception e1) {
            throw new RuntimeException(e1);
        }
        if (null == resp) {
            throw new Exception("Got Status Code : 100");
        }
        if (resp.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {
            StringWriter writer = new StringWriter();
            try {
                IOUtils.copy(resp.getEntity().getContent(), writer);
                return writer.toString();
            } catch (IOException e) {
                throw new Exception(e.getMessage());
            }
        } else {
            throw new Exception("Got Status Code : " + resp.getStatusLine().getStatusCode());
        }
    }

Friday 3 August 2012

JBoss SSL Installation Procedures


JBoss SSL Installation Procedures

The following procedures were utilized for adding a signed SSL certificate to JBoss for use with the Higher Reach, a package developed by Jenzabar.  These particular instructions were developed for a Windows Server platform but should be identical for Linux platforms by just changing the relevant file paths.

Step 1: Create a keystore for the new SSL certificate (example cert.keystore): 

            keytool -genkey -keyalg RSA -keysize 2048 -keystore cert.keystore -alias certrsakey

Step 2: You will be prompted for a password for the keystore (be sure to record this as you will need it inorder to fully complete the certificate installation process):
           
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

Enter keystore password:
Re-enter new password:

Step 3: Supply server specific data needed for CSR (Enter the FQDN of the server when prompted for first and last name):

What is your first and last name?
  [Unknown]:  myserver.domain.com
What is the name of your organizational unit?
  [Unknown]:  IT
What is the name of your organization?
  [Unknown]:  Luthor Corp
What is the name of your City or Locality?
  [Unknown]:  Metropolis
What is the name of your State or Province?
  [Unknown]:  Kansas
What is the two-letter country code for this unit?
  [Unknown]:  US
Is CN=myserver.domain.com, OU=IT, O=Luthor Corp, L=Metropolis, ST=Kansas,
C=US correct?
  [no]: yes

Step 4: Once again you will be prompted for a password.  YOU MUST USE THE SAME PASSWORD AS PREVIOUSLY SELECTED:

Enter key password for <certrsakey>
        (RETURN if same as keystore password):
Re-enter new password:

Step 5: Create the CSR request file for use with Verisign or other SSL provider:

            keytool -certreq -keyalg RSA -file cert.csr -keystore cert.keystore -alias certrsakey

Step 6: Perform certificate renewal or order process at Verisign.  Once you receive the cert.cer file save it to the server in the same directory you created your keystore file.  Example: C:/ssl_certs/cert.cer

Step 7: Download the primary and secondary intermediate certificates from Verisign and save them as primaryinter.cer and secondary inter.cer respectively. As of this writing the intermediate certificates can be retrieved from

Step 8: Import the primary intermediate certificate into the keystore (you will be prompted for the keystore password):

            keytool -import -trustcacerts -alias primaryIntermediate -keystore cert.keystore -file primaryinter.cer

Step 9: Import the secondary intermediate certificate into the keystore (you will be prompted for the keystore password):

            keytool -import -trustcacerts -alias secondaryIntermediate -keystore cert.keystore -file secondaryinter.cer.txt

Step 10: Import the ssl certificate sent by Verisign (you will be prompted for the keystore password):

            keytool -import -trustcacerts -alias certrsakey -keystore cert.keystore -file cert.cer

Step 11: [optional] Test keystore properly contains all certificates with the follwoing command:

            keytool -list -v -keystore  cert.keystore >test.txt

Verify the following information:

- The SSL certificate is imported into the alias with the "Entry Type" of PrivateKeyEntry or KeyEntry.  If not, please import the certificate into the Private Key alias.

- The Certificate chain length is 4.

Step 12: Modify JBoss to use the new keystore and key password by editing C:\jboss-5.1.0\server\dirname\deploy\jbossweb.sar\server.xml, note: replace dirname with the appropriate folder name for your installation.  The relevant sections are below:

      <!-- SSL/TLS Connector configuration using the admin devl guide keystore -->
      <Connector protocol="HTTP/1.1" SSLEnabled="true"
           port="8443" address="${jboss.bind.address}"
           scheme="https" secure="true" clientAuth="false"
           keystoreFile="C:/ssl_certs/cert.keystore"
           keystorePass="Password you selected in step 4" sslProtocol = "TLS" />

<!--


<ssl password="changeit" key-alias="tomcat"
                    certificate-key-file="/path/to/keystore.p12"
                    verify-client="true"
                    ca-certificate-file="/path/to/truststore.jks"
                    ca-certificate-password="changeit"
                    keystore-type="PKCS12" truststore-type="JKS" />



-->

Step 13: Restart JBoss using the Windows Services utility.  Note: It takes a few minutes for the web component to restart so do not panic if you get can't connect to site while browsing to https://myserver.domain.com:8443/

=====================
OTHER USEFUL COMMANDS
=====================

•Delete a certificate from a Java Keytool keystore

keytool -delete -alias [alias name] -keystore [keystore name]


Administration Guide :


Https Confituration on Jboss 7



HiIn this demonstration we will see how to create a simple keystore and based on this how to configure the HTTPs connector in JBoss AS7. Also in many production environments it is desired to redirect clients incoming HTTP requests to HTTPs automatically.So here we will see how can be use the redirect port configuration in the http connector and what kind of information we need to provide inside the “web.xml” file of our web application where we want automatic HTTPs redirection feature to make all the client conversation with the server CONFIDENTIAL.

SSL Configuration on JBoss AS7

Step1). Create a simple SSL certificate keystore. We can use the “keytool” utility which comes by default with the JDK and present inside the “$JAVA_HOME/bin” directory. So before running the below command make sure that you have set the PATH to point to your JDK bin directory.
1For Unix Based OS:
2export PATH=/home/userone/jdk1.6.0_21/bin:$PATH
3
4For Windows Based OS:
5set PATH=C:/jdk1.6.0_21/bin;%PATH%
Step2). Run the following command to create a sample key store file with name “chap8.keystore”
1keytool -genkey -keystore chap8.keystore -storepass rmi+ssl -keypass rmi+ssl
2           -keyalg RSA -alias chapter8  -validity 3650
3           -dname "cn=chapter8 example,ou=admin book,dc=jboss,dc=org"
Step3). Now paste the generated “chap8.keystore” inside the “/home/userone/jboss-as-7.1.0.Beta1/standalone/configuration” directory and then edit the “standalone-full.xml” file present in the same directory. We will need to edit the “urn:jboss:domain:web:1.1″ subsystem as following:
01<subsystem xmlns="urn:jboss:domain:web:1.1" default-virtual-server="default-host">
02    <connector name="http" protocol="HTTP/1.1" scheme="http" socket-binding="http" redirect-port="8443"/>
03
04    <connector name="https" protocol="HTTP/1.1" scheme="https" socket-binding="https" enable-lookups="false" secure="true">
05        <ssl name="ssl"
06             key-alias="chapter8"
07             password="rmi+ssl"
08             certificate-key-file="../standalone/configuration/chap8.keystore"
09             protocol="TLSv1"
10             verify-client="false"/>
11    </connector>
12    <virtual-server name="default-host" enable-welcome-root="true">
13        <alias name="localhost"/>
14        <alias name="example.com"/>
15    </virtual-server>
16</subsystem>
NOTE: We added the redirect-port=”8443″ inside the http connector as well as we added the “https” connector settings with the ssl informations.
Step4). Now restart the JBoss AS7 server from inside “/home/userone/jboss-as-7.1.0.Beta1//bin” directory as following:
1[userone@localhost bin]$./standalone.sh -c standalone-full.xml

Writing Test WebApplication

Step5). For simple testing we will write a web application. So create a directory somewhere in your file system with name “/home/userone/SelfSigned_SSL_Demo” and then create another directory “src” inside “/home/userone/SelfSigned_SSL_Demo”.
Step6). place the following kind of simple “index.jsp” file inside “/home/userone/SelfSigned_SSL_Demo/src” directory:
01<html>
02  <head>
03    <title>SSL Demo</title>
04  </head>
05  <body bgcolor=maroon text=white>
06      <BR><BR><BR><BR><BR><BR>
07      <center>
08       <b>index.jsp executed successfully over HTTPS.</b>
09      </center>
10  </body>
11</html>
Step7). Now we will write a “web.xml” file inside the “/home/userone/SelfSigned_SSL_Demo/src” directory, and in this file we will define the user-data-constraint as CONFIDENTIAL sothat clients request matching the url-pattern defined will be automatically be redirected to the redirect-port defined inside the “standalone-full.xml” file.
01<?xml version="1.0" encoding="UTF-8"?>
02<web-app version="2.5"
03         xmlns="http://java.sun.com/xml/ns/javaee"
04         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
06    <security-constraint>
07         <web-resource-collection>
08             <web-resource-name>HTTPs Test</web-resource-name>
09             <url-pattern>/*</url-pattern>
10         </web-resource-collection>
11         <user-data-constraint>
12             <transport-guarantee>CONFIDENTIAL</transport-guarantee>
13         </user-data-constraint>
14    </security-constraint>
15</web-app>
Step8). To simply build and deploy the above web application we will write the following kind of “build.xml” file inside “/home/userone/SelfSigned_SSL_Demo” directory.
01<project name="JBoss_Service" default="post-deploy">
02<property name="jboss.home" value="/home/userone/jboss-as-7.1.0.Beta1" />
03<property name="jboss.module.dir" value="${jboss.home}/modules" />
04<property name="java.home.dir" value="/home/userone/MyJdks/jdk1.6.0_05" />
05<property name="basedir" value="." />
06<property name="war.exploaded.name" value="SelfSigned_HttpsTest" />
07<property name="src.dir" value="src" />
08<property name="output.dir" value="build" />
09
10   <path id="jboss.classpath">
11     <fileset dir="${jboss.module.dir}">
12        <include name="**/*.jar"/>
13     </fileset>
14   </path>
15
16   <target name="init">
17      <delete dir="${output.dir}" />
18      <mkdir dir="${output.dir}" />
19      <mkdir dir="${output.dir}/${war.exploaded.name}"/>
20      <mkdir dir="${output.dir}/${war.exploaded.name}/WEB-INF"/>
21   </target>
22
23   <target name="build" depends="init">
24        <copy todir="${output.dir}/${war.exploaded.name}/WEB-INF">
25      <fileset dir="${basedir}/src">
26          <include name="web.xml"/>
27      </fileset>
28    </copy>
29        <copy todir="${output.dir}/${war.exploaded.name}">
30      <fileset dir="${basedir}/src">
31          <include name="index.jsp"/>
32      </fileset>
33    </copy>
34        <jar jarfile="${output.dir}/${war.exploaded.name}.war" basedir="${output.dir}/${war.exploaded.name}" compress="true" />
35   </target>
36
37        <target name="deploy" depends="build">
38            <echo message="*******************  Deploying   *********************" />
39            <echo message="********** ${war.exploaded.name}.war to ${jboss.home}/standalone/deployments **********" />
40            <copy todir="${jboss.home}/standalone/deployments/">
41                <fileset dir="${output.dir}/">
42                  <include name="${war.exploaded.name}.war"/>
43                </fileset>
44            </copy>
45            <echo message="*******************  Deployed Successfully   *********************" />
46        </target>
47
48        <target name="post-deploy" depends="deploy">
49            <echo message="*******************  NOTE  *********************" />
50            <echo message="***** You should be able to access your WSDL using Browser now *****" />
51            <echo message="                http://localhost:8080/${war.exploaded.name}/index.jsp" />
52            <echo message="You will notice that your URL is automactically changing to https"/>
53            <echo message="https://localhost:8443/${war.exploaded.name}/index.jsp" />
54        </target>
55</project>
Step9). Now before running your ANT script to build and deploy the above webapplication you should have the ANT as well as JAVA set in the $PATH variable of the Shell / command prompt as following:
1For Unix Based OS:
2export PATH=/home/userone/jdk1.6.0_21/bin:/home/userone/org.apache.ant_1.6.5/bin:$PATH
3
4For Windows Based OS:
5set PATH=C:/jdk1.6.0_21/bin;C:/org.apache.ant_1.6.5/bin;%PATH%
Step10). run the ant script “ant” to build and deploy the application on JBoss AS7.
01[userone@localhost SelfSigned_SSL_Demo]$ ant
02Buildfile: build.xml
03
04init:
05   [delete] Deleting directory /home/userone/SelfSigned_SSL_Demo/build
06    [mkdir] Created dir: /home/userone/SelfSigned_SSL_Demo/build
07    [mkdir] Created dir: /home/userone/SelfSigned_SSL_Demo/build/SelfSigned_HttpsTest
08    [mkdir] Created dir: /home/userone/SelfSigned_SSL_Demo/build/SelfSigned_HttpsTest/WEB-INF
09
10build:
11     [copy] Copying 1 file to /home/userone/SelfSigned_SSL_Demo/build/SelfSigned_HttpsTest/WEB-INF
12     [copy] Copying 1 file to /home/userone/SelfSigned_SSL_Demo/build/SelfSigned_HttpsTest
13      [jar] Building jar: /home/userone/SelfSigned_SSL_Demo/build/SelfSigned_HttpsTest.war
14
15deploy:
16     [echo] *******************  Deploying   *********************
17     [echo] ********** SelfSigned_HttpsTest.war to /home/userone/jboss-as-7.1.0.Beta1/standalone/deployments **********
18     [copy] Copying 1 file to /home/userone/jboss-as-7.1.0.Beta1/standalone/deployments
19     [echo] *******************  Deployed Successfully   *********************
20
21post-deploy:
22     [echo] *******************  NOTE  *********************
23     [echo] ***** You should be able to access your WSDL using Browser now *****
24     [echo]                 http://localhost:8080/SelfSigned_HttpsTest/index.jsp
25     [echo] You will notice that your URL is automactically changing to https
26     [echo] https://localhost:8443/SelfSigned_HttpsTest/index.jsp
27
28BUILD SUCCESSFUL
29Total time: 0 seconds
NOTE: Access the application with URL “http://localhost:8080/SelfSigned_HttpsTest/index.jsp” and you will notice that your URL is automatically chaged to ” https://localhost:8443/SelfSigned_HttpsTest/index.jsp


  • How are change HTTPs protocal :

Edit Standalone.xml and go to red mark line and change the port number that you want to replace with.

<socket-binding-group name="standard-sockets" default-interface="public" port-offset="${jboss.socket.binding.port-offset:0}">
        <socket-binding name="management-native" interface="management" port="${jboss.management.native.port:9999}"/>
        <socket-binding name="management-http" interface="management" port="${jboss.management.http.port:9990}"/>
        <socket-binding name="management-https" interface="management" port="${jboss.management.https.port:9443}"/>
        <socket-binding name="ajp" port="8009"/>
        <socket-binding name="http" port="8080"/>
        <socket-binding name="https" port="8443"/>
        <socket-binding name="osgi-http" interface="management" port="8090"/>
        <socket-binding name="remoting" port="4447"/>
        <socket-binding name="txn-recovery-environment" port="4712"/>
        <socket-binding name="txn-status-manager" port="4713"/>
        <outbound-socket-binding name="mail-smtp">
            <remote-destination host="localhost" port="25"/>
        </outbound-socket-binding>
    </socket-binding-group>