java/j2EE

Java Class Clone

Posted on November 18, 2012. Filed under: java/j2EE |

clone demo #mkdir cloneDemo
clone demo #cd cloneDemo/
clone demo #vi Driver.java
clone demo #vi PrototypeA.java
clone demo #vi PrototypeAA.java
clone demo #vi PrototypeAAA.java
clone demo #cat Driver.java
public class Driver {
 public PrototypeA prototypeA = null;
 public static void main(String[] args) throws CloneNotSupportedException {
 Driver driver = new Driver();
 driver.prototypeA = new PrototypeA();
 PrototypeA prototypeAClone = (PrototypeA)driver.prototypeA.clone();
 //change original object name
 driver.prototypeA.name = new String("newA");
 driver.prototypeA.prototypeAA.name = new String("newAA");
 driver.prototypeA.prototypeAA.prototypeAAA.name = new String("newAAA");
 //printout the cloned object names
 System.out.println("prototypeAClone.name: "+prototypeAClone.name);
 System.out.println("prototypeAClone.prototypeAA.name: "+prototypeAClone.prototypeAA.name);
 System.out.println("prototypeAClone.prototypeAA.prototypeAAA.name: "+prototypeAClone.prototypeAA.prototypeAAA.name);
 }
}

clone demo #
clone demo #cat PrototypeA.java
public class PrototypeA implements Cloneable{
 public String name = null;
 public PrototypeAA prototypeAA = null;
 public PrototypeA() throws CloneNotSupportedException{
 name = new String("A");
 prototypeAA = new PrototypeAA();
 }

 public Object clone() throws CloneNotSupportedException {
 System.out.println("in the prototypeA clone method");
 PrototypeA returnPrototype = (PrototypeA)super.clone();
 return returnPrototype;
 }
}

clone demo #
clone demo #cat PrototypeAA.java
public class PrototypeAA implements Cloneable{
 public String name = null;
 public PrototypeAAA prototypeAAA = null;
 public PrototypeAA() throws CloneNotSupportedException{
 name = new String("AA");
 prototypeAAA = new PrototypeAAA();
 }

 public Object clone() throws CloneNotSupportedException {
 System.out.println("in the prototypeAA clone method");
 PrototypeAA returnPrototype = (PrototypeAA)super.clone();
 return returnPrototype;
 }
}

clone demo #
clone demo #cat PrototypeAAA.java
public class PrototypeAAA implements Cloneable{
 public String name = null;
 public PrototypeAAA() throws CloneNotSupportedException{
 name = new String("AAA");
 }

 public Object clone() throws CloneNotSupportedException {
 System.out.println("in the prototypeAAA clone method");
 return super.clone();
 }
}

clone demo #
clone demo #echo "In the above shallow clone example, the class Driver has a field that is object (prototypeA). \The class PrototypeA has a field that is object (prototypeAA)
> The class PrototypeAA has a field that is object (protytypeAAA). \
> We made a shallow clone of object prototypeA in Driver.java by calling the clone method of the class PrototypeA. \
> It is called shallow clone because in the clone method of PrototypeA, all we did is to call the super.clone() to clone itself. \
> The super class of PrototypeA is class Object. By default, Object.clone() only makes shallow copy the member fields -- if a field is an object, only the reference is copied.\> As a result, the prototypeAA field in bothe prototypeA and prototypeAClone both reference the same object. Changes in the prototypeAA field is visible to both prototypeA and prototypeAClone\
> Of course, this is not what we want, we want to make a real clone of prototypeA, don't want to share any fields with original object prototypeA.">/dev/nullclone demo #
clone demo #javac Driver.java PrototypeA.java PrototypeAA.java PrototypeAAA.java
clone demo #java Driver
in the prototypeA clone method
prototypeAClone.name: A
prototypeAClone.prototypeAA.name: newAA
prototypeAClone.prototypeAA.prototypeAAA.name: newAAA
clone demo #
clone demo #echo "In the following example, what we will make a deep clone of object prototypeA in Driver.java.\> In order to deep clone, we need to modify the clone method of class PrototypeA, we need to recursively deep copy its member field prototypeAA.\ > In this case, we replace the reference to prototypeAA with the reference to prototypeAA's clone.\
> Of course, prototypeAA's clone has to be deep clone also, means in the cloned object, the member field prototypeAAA has to reference to original prototypeAA's member field prototypeAAA's clone.">/dev/null
clone demo #
clone demo #vi PrototypeA.java
clone demo #vi PrototypeAA.java
clone demo #cat PrototypeA.java
public class PrototypeA implements Cloneable{
 public String name = null;
 public PrototypeAA prototypeAA = null;
 public PrototypeA() throws CloneNotSupportedException{
 name = new String("A");
 prototypeAA = new PrototypeAA();
 }

 public Object clone() throws CloneNotSupportedException {
 System.out.println("in the prototypeA clone method");
 PrototypeA returnPrototype = (PrototypeA)super.clone();
 returnPrototype.prototypeAA = (PrototypeAA)prototypeAA.clone();
 return returnPrototype;
 }
}

clone demo #
clone demo #cat PrototypeAA.java
public class PrototypeAA implements Cloneable{
 public String name = null;
 public PrototypeAAA prototypeAAA = null;
 public PrototypeAA() throws CloneNotSupportedException{
 name = new String("AA");
 prototypeAAA = new PrototypeAAA();
 }

 public Object clone() throws CloneNotSupportedException {
 System.out.println("in the prototypeAA clone method");
 PrototypeAA returnPrototype = (PrototypeAA)super.clone();
 returnPrototype.prototypeAAA = (PrototypeAAA)prototypeAAA.clone();
 return returnPrototype;
 }
}

clone demo #
clone demo #javac PrototypeA.java PrototypeAA.java
clone demo #java Driver
in the prototypeA clone method
in the prototypeAA clone method
in the prototypeAAA clone method
prototypeAClone.name: A
prototypeAClone.prototypeAA.name: AA
prototypeAClone.prototypeAA.prototypeAAA.name: AAA
clone demo #
clone demo #
clone demo #echo "The above clone example is not secure, to show why, we will write an EvileDriver.java and SpoofPrototypeA.java, which overwrite the clone method, and nullify all the deep clone effort" > /dev/null
clone demo #vi EvileDriver.java
clone demo #vi SpoofPrototypeA.java
clone demo #cat EvileDriver.java
public class EvilDriver {
 public SpoofPrototypeA prototypeA = null;
 public static void main(String[] args) throws CloneNotSupportedException {
 //Driver.main(null);
 Driver driver = new Driver();
 //EvilDriver driver = new EvilDriver();
 driver.prototypeA = new SpoofPrototypeA();
 PrototypeA prototypeAClone = (PrototypeA)driver.prototypeA.clone();
 //change original object name
 driver.prototypeA.name = new String("newA");
 driver.prototypeA.prototypeAA.name = new String("newAA");
 driver.prototypeA.prototypeAA.prototypeAAA.name = new String("newAAA");
 //printout the cloned object names
 System.out.println("prototypeAClone.name: "+prototypeAClone.name);
 System.out.println("prototypeAClone.prototypeAA.name: "+prototypeAClone.prototypeAA.name);
 System.out.println("prototypeAClone.prototypeAA.prototypeAAA.name: "+prototypeAClone.prototypeAA.prototypeAAA.name);
 //Driver.main(null);
 }
}

clone demo #
clone demo #cat SpoofPrototypeA.java
public class SpoofPrototypeA extends PrototypeA{
 public String name = null;
 public PrototypeAA prototypeAA = null;

public SpoofPrototypeA() throws CloneNotSupportedException {
 super();
 }

 public Object clone() throws CloneNotSupportedException {
 System.out.println("in the SpoofPrototypeA clone method");
 PrototypeA returnPrototype = this;
 //returnPrototype.prototypeAA = (PrototypeAA)super.prototypeAA.clone();
 return returnPrototype;
 }
}

clone demo #
clone demo #javac EvileDriver.java SpoofPrototypeA.java
EvileDriver.java:1: class EvilDriver is public, should be declared in a file named EvilDriver.java
public class EvilDriver {
 ^
1 error
clone demo #mv EvileDriver.java EvilDriver.java
clone demo #javac EvileDriver.java SpoofPrototypeA.java
javac: file not found: EvileDriver.java
Usage: javac <options> <source files>
use -help for a list of possible options
clone demo #javac EvilDriver.java SpoofPrototypeA.java
clone demo #java EvilDriver
in the SpoofPrototypeA clone method
prototypeAClone.name: newA
prototypeAClone.prototypeAA.name: newAA
prototypeAClone.prototypeAA.prototypeAAA.name: newAAA
clone demo #
clone demo #
clone demo #echo "the cure of the above problem is to make the clone method final.">/dev/null
clone demo #vi PrototypeA.java
clone demo #vi PrototypeAA.java
clone demo #vi PrototypeAAA.java
clone demo #cat PrototypeA.java
public class PrototypeA implements Cloneable{
 public String name = null;
 public PrototypeAA prototypeAA = null;
 public PrototypeA() throws CloneNotSupportedException{
 name = new String("A");
 prototypeAA = new PrototypeAA();
 }

 public final Object clone() throws CloneNotSupportedException {
 System.out.println("in the prototypeA clone method");
 PrototypeA returnPrototype = (PrototypeA)super.clone();
 returnPrototype.prototypeAA = (PrototypeAA)prototypeAA.clone();
 return returnPrototype;
 }
}

clone demo #
clone demo #cat PrototypeAA.java
public class PrototypeAA implements Cloneable{
 public String name = null;
 public PrototypeAAA prototypeAAA = null;
 public PrototypeAA() throws CloneNotSupportedException{
 name = new String("AA");
 prototypeAAA = new PrototypeAAA();
 }

 public final Object clone() throws CloneNotSupportedException {
 System.out.println("in the prototypeAA clone method");
 PrototypeAA returnPrototype = (PrototypeAA)super.clone();
 returnPrototype.prototypeAAA = (PrototypeAAA)prototypeAAA.clone();
 return returnPrototype;
 }
}

clone demo #
clone demo #cat PrototypeAAA.java
public class PrototypeAAA implements Cloneable{
 public String name = null;
 public PrototypeAAA() throws CloneNotSupportedException{
 name = new String("AAA");
 }

 public final Object clone() throws CloneNotSupportedException {
 System.out.println("in the prototypeAAA clone method");
 return super.clone();
 }
}

clone demo #
clone demo #echo "now EvilDriver won't work because the clone method is no longer overwritable" > /dev/null
clone demo #javac Driver.java PrototypeA.java PrototypeAA.java PrototypeAAA.java
clone demo #javac EvilDriver.java
clone demo #java Driver
in the prototypeA clone method
in the prototypeAA clone method
in the prototypeAAA clone method
prototypeAClone.name: A
prototypeAClone.prototypeAA.name: AA
prototypeAClone.prototypeAA.prototypeAAA.name: AAA
clone demo #java EvilDriver
Exception in thread "main" java.lang.VerifyError: class SpoofPrototypeA overrides final method clone.()Ljava/lang/Object;
 at java.lang.ClassLoader.defineClass1(Native Method)
 at java.lang.ClassLoader.defineClassCond(ClassLoader.java:631)
 at java.lang.ClassLoader.defineClass(ClassLoader.java:615)
 at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
 at java.net.URLClassLoader.defineClass(URLClassLoader.java:283)
 at java.net.URLClassLoader.access$000(URLClassLoader.java:58)
 at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
 at java.security.AccessController.doPrivileged(Native Method)
 at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
 at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
 at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
 at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
clone demo #

Advertisements
Read Full Post | Make a Comment ( 1 so far )

Aspect oriented Programming (AOP)

Posted on November 14, 2012. Filed under: java/j2EE |

Read Full Post | Make a Comment ( None so far )

Spring AOP

Posted on November 14, 2012. Filed under: java/j2EE |

Read Full Post | Make a Comment ( None so far )

Java Exception Overview

Posted on November 14, 2012. Filed under: java/j2EE |

Read Full Post | Make a Comment ( None so far )

Java Garbage Collector

Posted on November 14, 2012. Filed under: java/j2EE |

Read Full Post | Make a Comment ( None so far )

Java Static and Final Keyword

Posted on November 12, 2012. Filed under: java/j2EE |

final keyword is import for security coding.
As a general rule, all classes should be final if they do not need to be extended. At least, we should make as much methods final as possible. Why, because subclass or anonymous class can change any behavior your class exposed to outside.

======
InnerClass>ls
OuterClass.java OuterClassDrive.java
InnerClass>cat OuterClass.java
public class OuterClass {
final private String aSecrete = “a secrete”;
public void display() {
System.out.println(aSecrete);
}

//private InnerClass in = new InnerClass();

public void doBusiness() {
new InnerClass().innocentMsd();
}

class InnerClass {
public void innocentMsd() {
System.out.println(“no harm”);
}
}
}

InnerClass>cat OuterClassDrive.java
public class OuterClassDrive {
OuterClass o = new OuterClass() {
final private String aSecrete = “a secrete?”;
class InnerClass {
public void innocentMsd() {
System.out.println(“no harm?”);
}
}
public void doBusiness() {
new InnerClass().innocentMsd();
}
public void display() {
System.out.println(aSecrete);
}
};

void doEvil() {
System.out.println(“normal object”);
OuterClass on = new OuterClass();
on.doBusiness();
System.out.println(“Evil Object”);
o.new InnerClass().innocentMsd();
o.doBusiness();
o.display();
}

public static void main(String…args) {
OuterClassDrive drive = new OuterClassDrive();
drive.doEvil();
}
}

InnerClass>javac *.java
InnerClass>ls
OuterClass$InnerClass.class OuterClassDrive$1.class
OuterClass.class OuterClassDrive.class
OuterClass.java OuterClassDrive.java
OuterClassDrive$1$InnerClass.class
InnerClass>java OuterClassDrive
normal object
no harm
Evil Object
no harm
no harm?
a secrete?
InnerClass>
======

Read Full Post | Make a Comment ( None so far )

Java Accessibility (public, protected, private, package, none)

Posted on November 12, 2012. Filed under: java/j2EE |

Read Full Post | Make a Comment ( None so far )

Java Inner Classes

Posted on November 12, 2012. Filed under: java/j2EE |

Read Full Post | Make a Comment ( None so far )

How to Sign a jar File

Posted on November 11, 2012. Filed under: java/j2EE |

based on oracle tutorial:

http://docs.oracle.com/javase/tutorial/deployment/jar/index.html

We can create a jar file with command jar.

We can create a signed jar file with command jarsigner.

The following is a video example of using signed jar on applet.

In How To Create New Java Permissions, we have created a customized permission file as well as a policy file, here we will create a jar file from it then sign it with a certificate:


jarsigner demo #mkdir jarsigner
jarsigner demo #cd jarsigner
jarsigner demo #echo "generate a self-siged keypair">/dev/null
jarsigner demo #keytool -genkeypair -alias keypair -keyalg RSA -keypass password -keystore keypair.jks -storepass password
What is your first and last name?
 [Unknown]: whatever
What is the name of your organizational unit?
 [Unknown]: kl2217org
What is the name of your organization?
 [Unknown]: kl2217
What is the name of your City or Locality?
 [Unknown]: bla
What is the name of your State or Province?
 [Unknown]: bla
What is the two-letter country code for this unit?
 [Unknown]: US
Is CN=whatever, OU=kl2217org, O=kl2217, L=bla, ST=bla, C=US correct?
 [no]: yes

jarsigner demo #keytool -exportcert -alias keypair -file pubkey.cer -keystore keypair.jks -storepass password
Certificate stored in file <pubkey.cer>
jarsigner demo #keytool -importcert -alias pubkey -file pubkey.cer -keystore pubkey.jks -storepass password
Owner: CN=whatever, OU=kl2217org, O=kl2217, L=bla, ST=bla, C=US
Issuer: CN=whatever, OU=kl2217org, O=kl2217, L=bla, ST=bla, C=US
Serial number: 50a073c3
Valid from: Sun Nov 11 22:57:55 EST 2012 until: Sat Feb 09 22:57:55 EST 2013
Certificate fingerprints:
 MD5: A3:1C:9C:E3:F7:E8:F2:97:E5:38:C4:0B:63:E1:49:32
 SHA1: A1:DC:0F:0C:95:AE:20:CA:E4:08:F9:6D:C8:F5:6D:30:80:B5:8B:AC
 Signature algorithm name: SHA1withRSA
 Version: 3
Trust this certificate? [no]: yes
Certificate was added to keystore
jarsigner demo #vi HelloFile.java
jarsigner demo #vi CustomerPermission.java
jarsigner demo #vi HelloFile.java
jarsigner demo #cat HelloFile.java
import java.io.*;
import java.security.AccessController;
public class HelloFile {
 public static void main(String [] args) {
 if(System.getSecurityManager()==null){
 System.setSecurityManager(new SecurityManager());
 }
 CustomerPermission cp = new CustomerPermission("cust");
 AccessController.checkPermission(cp);
 try{
 BufferedReader br = new BufferedReader(new FileReader("/tmp/testfile.txt"));
 System.out.println(br.readLine());
 }catch(Exception e){
 e.printStackTrace();
 }
 }
}
jarsigner demo #cat CustomerPermission.java
import java.security.BasicPermission;

public class CustomerPermission extends BasicPermission{
 public CustomerPermission(String name){
 super(name);
 }

}
jarsigner demo #
jarsigner demo #cat /tmp/testfile.txt
test for signed jar
jarsigner demo #echo "create unsigned jar first">/dev/null
jarsigner demo #javac HelloFile.java CustomerPermission.java
jarsigner demo #jar cf HelloFile.jar HelloFile.class CustomerPermission.class
jarsigner demo #jar cfe HelloFile.jar HelloFile HelloFile.class
jarsigner demo #vi HelloFile.policy
jarsigner demo #cat HelloFile.policy
grant codeBase "file:./*" {
permission java.io.FilePermission "/tmp/*", "read";
permission CustomerPermission "cust";
};
jarsigner demo #
jarsigner demo #java -jar HelloFile.jar -Djava.security.policy="./HelloFile.policy"
Exception in thread "main" java.lang.NoClassDefFoundError: CustomerPermission
Caused by: java.lang.ClassNotFoundException: CustomerPermission
 at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
 at java.security.AccessController.doPrivileged(Native Method)
 at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
 at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
 at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
 at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
jarsigner demo #jar tf HelloFile.jar
META-INF/
META-INF/MANIFEST.MF
HelloFile.class
jarsigner demo #jar uf HelloFile.jar CustomerPermission.class
jarsigner demo #jar tf HelloFile.jar
META-INF/
META-INF/MANIFEST.MF
HelloFile.class
CustomerPermission.class
jarsigner demo #java -jar HelloFile.jar -Djava.security.policy="./HelloFile.policy"
Exception in thread "main" java.security.AccessControlException: access denied (CustomerPermission cust)
 at java.security.AccessControlContext.checkPermission(AccessControlContext.java:374)
 at java.security.AccessController.checkPermission(AccessController.java:549)
 at HelloFile.main(HelloFile.java:9)
jarsigner demo #vi HelloFile.policy
jarsigner demo #java -jar -Djava.security.policy="./HelloFile.policy" HelloFile.jar
test for signed jar
jarsigner demo #echo "sign the jar file with private key">/dev/null
jarsigner demo #jarsigner -keystore keypair.jks -sigfile SIGNATURE -signedjar HelloFileSigned.jar HelloFile.jar keypair
Enter Passphrase for keystore:

Warning:
The signer certificate will expire within six months.
jarsigner demo #jar tf HelloFileSigned.jar
META-INF/MANIFEST.MF
META-INF/SIGNATUR.SF
META-INF/SIGNATUR.RSA
META-INF/
HelloFile.class
CustomerPermission.class
jarsigner demo #jar xf HelloFileSigned.jar META-INF
jarsigner demo #vi META-INF/MANIFEST.MF
jarsigner demo #vi META-INF/SIGNATUR.SF
jarsigner demo #vi META-INF/SIGNATUR.RSA
jarsigner demo #vi HelloFileSigned.policy
jarsigner demo #ls
CustomerPermission.class HelloFile.jar HelloFileSigned.jar keypair.jks
CustomerPermission.java HelloFile.java HelloFileSigned.policy pubkey.cer
HelloFile.class HelloFile.policy META-INF pubkey.jks
jarsigner demo #cat HelloFileSigned.policy
keystore "file:./pubkey.jks";
grant signedBy "pubkey", codeBase "file:./HelloFileSigned.jar" {
 permission java.io.FilePermission "/tmp/*", "read";
 permission CustomerPermission "cust";
};

jarsigner demo #java -jar -Djava.security.policy="./HelloFileSigned.policy" HelloFileSigned.jar
test for signed jar
jarsigner demo #echo "the policy will prevent unsigned jar to run">/dev/null
jarsigner demo #java -jar -Djava.security.policy="./HelloFileSigned.policy" HelloFile.jar
Exception in thread "main" java.security.AccessControlException: access denied (CustomerPermission cust)
 at java.security.AccessControlContext.checkPermission(AccessControlContext.java:374)
 at java.security.AccessController.checkPermission(AccessController.java:549)
 at HelloFile.main(HelloFile.java:9)
jarsigner demo #echo "jarsigner can also be used to verify a signed jar">/dev/null</pre>
jarsigner demo #jarsigner -verify -verbose HelloFileSigned.jar

228 Sun Nov 11 23:23:36 EST 2012 META-INF/MANIFEST.MF
 326 Sun Nov 11 23:23:36 EST 2012 META-INF/SIGNATUR.SF
 904 Sun Nov 11 23:23:36 EST 2012 META-INF/SIGNATUR.RSA
 0 Sun Nov 11 23:06:00 EST 2012 META-INF/
sm 1088 Sun Nov 11 23:04:26 EST 2012 HelloFile.class
sm 246 Sun Nov 11 23:04:26 EST 2012 CustomerPermission.class

s = signature was verified
 m = entry is listed in manifest
 k = at least one certificate was found in keystore
 i = at least one certificate was found in identity scope

jar verified.

Warning:
This jar contains entries whose signer certificate will expire within six months.

Re-run with the -verbose and -certs options for more details.
jarsigner demo #jarsigner -verify -verbose HelloFile.jar

0 Sun Nov 11 23:06:00 EST 2012 META-INF/
 83 Sun Nov 11 23:06:00 EST 2012 META-INF/MANIFEST.MF
 1088 Sun Nov 11 23:04:26 EST 2012 HelloFile.class
 246 Sun Nov 11 23:04:26 EST 2012 CustomerPermission.class

s = signature was verified
 m = entry is listed in manifest
 k = at least one certificate was found in keystore
 i = at least one certificate was found in identity scope

jar is unsigned. (signatures missing or not parsable)
jarsigner demo #
Read Full Post | Make a Comment ( None so far )

JSSE server/client SSL connection Example

Posted on November 11, 2012. Filed under: java/j2EE |

http://www.maximporges.com/2009/11/18/configuring-tomcat-ssl-clientserver-authentication/

http://docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html

  • Step 1 Create self-signed server and client certificates with keytool.
  • Step 2 create server java code.
  • Step 3 create client java code.
SSLDemo #mkdir ssldemo
SSLDemo #cd ssldemo/
SSLDemo #echo "Generate the Client and Server Keystores" > /dev/null
SSLDemo #keytool -genkeypair -alias plainserverkeys -keyalg RSA -dname "CN=Plain Server,OU=kl2217,O=kl2217org,L=Boston,ST=MA,C=US" -keypass password -keystore plainserver.jks -storepass password
SSLDemo #keytool -genkeypair -alias plainclientkeys -keyalg RSA -dname "CN=Plain Client,OU=kl2217,O=kl2217org,L=Boston,ST=MA,C=US" -keypass password -keystore plainclient.jks -storepass password
SSLDemo #echo "Export the server public certificate and create a seperate keystore">/dev/null
SSLDemo #keytool -exportcert -alias plainserverkeys -file serverpub.cer -keystore plainserver.jks -storepass password
Certificate stored in file <serverpub.cer>
SSLDemo #keytool -importcert -keystore serverpub.jks -alias serverpub -file serverpub.cer -storepass password
Owner: CN=Plain Server, OU=kl2217, O=kl2217org, L=Boston, ST=MA, C=US
Issuer: CN=Plain Server, OU=kl2217, O=kl2217org, L=Boston, ST=MA, C=US
Serial number: 509fdd3e
Valid from: Sun Nov 11 12:15:42 EST 2012 until: Sat Feb 09 12:15:42 EST 2013
Certificate fingerprints:
 MD5: 22:28:1C:8C:EE:19:10:E6:E4:A3:A3:F8:24:D0:E3:11
 SHA1: 22:C7:1B:18:0D:8D:0A:6D:31:BD:CF:90:09:E9:6A:42:AA:4B:14:2A
 Signature algorithm name: SHA1withRSA
 Version: 3
Trust this certificate? [no]: yes
Certificate was added to keystore
SSLDemo #echo "Export the client public certificate and create a seperate keystore">/dev/null
SSLDemo #keytool -exportcert -alias plainclientkeys -file clientpub.cer -keystore plainclient.jks -storepass password
Certificate stored in file <clientpub.cer>
SSLDemo #keytool -importcert -keystore clientpub.jks -alias clientpub -file clientpub.cer -storepass password
Owner: CN=Plain Client, OU=kl2217, O=kl2217org, L=Boston, ST=MA, C=US
Issuer: CN=Plain Client, OU=kl2217, O=kl2217org, L=Boston, ST=MA, C=US
Serial number: 509fdd8c
Valid from: Sun Nov 11 12:17:00 EST 2012 until: Sat Feb 09 12:17:00 EST 2013
Certificate fingerprints:
 MD5: 6A:4B:AC:16:6B:5B:4E:A4:F2:9B:4C:83:A9:6D:31:4D
 SHA1: 71:EA:11:0E:87:DB:E1:ED:66:68:C3:D4:D9:78:83:48:C9:C0:15:69
 Signature algorithm name: SHA1withRSA
 Version: 3
Trust this certificate? [no]: yes
Certificate was added to keystore</pre>
SSLDemo #ls
clientpub.cer clientpub.jks plainclient.jks plainserver.jks serverpub.cer serverpub.jks
SSLDemo #vi PlainServer.java
SSLDemo #vi PlainClient.java
SSLDemo #cat PlainServer.java
import java.io.*;
import java.security.*;
import javax.net.ssl.*;

public class PlainServer {
 public static void main(String [] args) {
 SSLServerSocket serverSock = null;
 SSLSocket socket = null;
 PrintWriter out = null;
 try {
 //load server private key
 KeyStore serverKeys = KeyStore.getInstance("JKS");
 serverKeys.load(new FileInputStream("plainserver.jks"),"password".toCharArray());
 KeyManagerFactory serverKeyManager = KeyManagerFactory.getInstance("SunX509");
 //System.out.println(KeyManagerFactory.getDefaultAlgorithm());
 //System.out.println(serverKeyManager.getProvider());
 serverKeyManager.init(serverKeys,"password".toCharArray());
 //load client public key
 KeyStore clientPub = KeyStore.getInstance("JKS");
 clientPub.load(new FileInputStream("clientpub.jks"),"password".toCharArray());
 TrustManagerFactory trustManager = TrustManagerFactory.getInstance("SunX509");
 trustManager.init(clientPub);
 //use keys to create SSLSoket
 SSLContext ssl = SSLContext.getInstance("TLS");
 ssl.init(serverKeyManager.getKeyManagers(), trustManager.getTrustManagers(), SecureRandom.getInstance("SHA1PRNG"));
 serverSock = (SSLServerSocket)ssl.getServerSocketFactory().createServerSocket(8889);
 serverSock.setNeedClientAuth(true);
 socket = (SSLSocket)serverSock.accept();
 //send data
 out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())));
 out.println("data from PlainServer");
 out.flush();
 } catch (Exception e) {
 e.printStackTrace();
 } finally {
 if(out!=null) out.close();
 try {
 if(serverSock!=null) serverSock.close();
 if(socket!=null) socket.close();
 } catch (IOException e) {
 e.printStackTrace();
 }
 }
 }
}

SSLDemo #cat PlainClient.java
import java.io.*;
import java.security.*;
import javax.net.ssl.*;

public class PlainClient {
 public static void main(String [] args) {
 SSLSocket socket = null;
 BufferedReader in = null;
 try {
 //load client private key
 KeyStore clientKeys = KeyStore.getInstance("JKS");
 clientKeys.load(new FileInputStream("plainclient.jks"),"password".toCharArray());
 KeyManagerFactory clientKeyManager = KeyManagerFactory.getInstance("SunX509");
 clientKeyManager.init(clientKeys,"password".toCharArray());
 //load server public key
 KeyStore serverPub = KeyStore.getInstance("JKS");
 serverPub.load(new FileInputStream("serverpub.jks"),"password".toCharArray());
 TrustManagerFactory trustManager = TrustManagerFactory.getInstance("SunX509");
 trustManager.init(serverPub);
 //use keys to create SSLSoket
 SSLContext ssl = SSLContext.getInstance("TLS");
 ssl.init(clientKeyManager.getKeyManagers(), trustManager.getTrustManagers(), SecureRandom.getInstance("SHA1PRNG"));
 socket = (SSLSocket)ssl.getSocketFactory().createSocket("localhost", 8889);
 socket.startHandshake();
 //receive data
 in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
 String data;
 while((data = in.readLine())!=null) {
 System.out.println(data);
 }
 } catch (Exception e) {
 e.printStackTrace();
 } finally {
 try {
 if(in!=null) in.close();
 if(socket!=null) socket.close();
 if(socket!=null) socket.close();
 } catch (IOException e) {
 e.printStackTrace();
 }
 }
 }
}

SSLDemo #
SSLDemo #javac PlainServer.java PlainClient.java
SSLDemo #java PlainServer &
[1] 5749
SSLDemo #java PlainClient
data from PlainServer
[1]+ Done java PlainServer
SSLDemo #

 

Read Full Post | Make a Comment ( 4 so far )

« Previous Entries

Liked it here?
Why not try sites on the blogroll...