Monday, March 21, 2011

How to create signed trusted applet?

Applets that get downloaded from server and executes on client browser operates in a sandbox. The process of applet getting downloaded is without user's approval and is automatic as we navigate to a page that contains applet. Hence, to prevent a malicious applet from potentially affecting the client system, the applet has certain constraints on what it can and what it cannot do.

If for a specific reason, you wish to allow the applet to (say) write to the file system on the client disk, you could do so by making a signed applet and user could accept the certificate to allow the applet to perform its operation. Without deliberating too much on the theory, I will illustrate the steps to create a signed applet.


1) Write the Java Applet code.

package com.emjay.applet;

import java.applet.Applet;
import java.awt.Graphics;
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class WriteFile extends Applet {
String myFile = "C:\\Users\\emjay\\test.foo";
File f = new File(myFile);
DataOutputStream ds;

public void paint(Graphics g) {
try {
ds = new DataOutputStream(new BufferedOutputStream(
new FileOutputStream(myFile), 128));

ds.writeChars("Wrote into the file system!!");
ds.flush();
g.drawString("Successfully wrote to " + myFile, 10, 10);
} catch (SecurityException e) {
g.drawString("Caught security exception", 10, 10);
} catch (IOException ioe) {
g.drawString("Caught I/O exception", 10, 10);
}
}
}

2) Compile the Java class and Jar the applet

javac com\emjay\applet\WriteFile.java
jar cvf WriteFile.jar com\emjay\applet\WriteFile.class

3) Generate the key certificate (Self Signed) using the command below:

keytool -genkey -alias WriteFileApplet -validity 365

* WriteFileApplet is an alias for the certificate that will be stored in .keystore.
* 365 indicates that this self signed certificate will be valid for 1 year
* You will have to answer a few questions while you generate the self signed cert including selecting a password.

4) Now, sign the applet jar filewith the Self Signed Cert using the command below:

jarsigner WriteFile.jar WriteFileApplet

* You will have to enter the password selected in the Step 3 while executing the command mentioned above.

5) Finally, create a simple web application and write the HTML file that uses this applet:

<applet code="com.emjay.applet.WriteFile" archive="WriteFile.jar" div=""></applet>

* Remember to place the WriteFile.jar and the HTML file under Web application's root directory.

6) When you access the HTML using a browser, you will see the certificate similar to the picture below:



Once you accept the certificate and press the Run button, the applet will load and execute.

No comments:

Post a Comment