JavaData & JavaCreating a Trusted Applet with Local File System Access Rights

Creating a Trusted Applet with Local File System Access Rights

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Creating trusted applets with the access rights to the local clients’ file system, even to this day remains a vital topic. A number of problems, by virtue of the specificity, can be executed only on the client side. Quite often, programmers unfamiliar with trusted applets technology accept it as an impossibility to work with client files and search for other ways to work. However, such ways exist and can be widely used in most variations. In this article, I will show you the example of how to create a simple trusted applet that will gain access to a local text file, which you will specify. (Please note that you will need to use JDK 1.3 or higher.)

To begin with, I would like to mention the restrictions we have to the client’s software. I want to stipulate at once that the given scheme of signing applets is suitable only for clients that have or can install JDK (1.3 or higher) or similar plug-in and use Internet Explorer (4 or higher) or Netscape Navigator (4.75 or higher). For all other clients, such a scheme is not supported and creating trusted applets for them will require the JDK 1.1 technology, using the javakey tool. Explaining this rather old method of creating signed applets goes beyond the scope of this article.

Now, a few words about our (developer’s) platform. We are working on a Windows platform, with Java 2 SDK 1.4.1 and the Java container Jakarta-Tomcat 4.1.29. If you are using the same software, you can be 100% sure that everything described in this article will run perfectly for you, too. Normally, everything should work on all compatible software, although it is known that sometimes software releases keep undocumented changes that can influence the process of building code.

Still, before starting directly with the code, I prefer to explain you why we need to find some specific and non-trivial ways to do, from one point of view, pretty easy and standard things such as reading local files. At the time of Java 1.1, there was an opinion that, with the help of applets, it will be possible and even necessary to transfer some specific parts of tasks to be carried out on client computers and thus, to create a future generation of network computers. However, owing to strict safety applets, it could not take place. Developers have deduced that applets in a so-called “sandbox”—one simple location—are an interdiction on the reference to any functions of the system. However, Java was growing and trusted applets have been thought up—such kinds of applets on which certain “sandbox” security rules are not distributed. But, how can you use this opportunity? You will find the answer below.

From JDK, we will require only two additional utilities besides javackeytool and jarsigner. keytool is a utility used to create and control a personal pair of private and public keys, and to administer your .keystore, which is your private store of keys. The jarsigner utility will be used to sign a jar-file that has an applet class inside and to authenticate the digital signature distributed together with an applet. The whole process of signing is pretty easy; however, we need to do a few initial steps to prepare. Let’s create our applet, which will have a text field where we will type a filename, a big text area where this file’s contents will appear, and a ‘Load’ button that will do file reading. The source code of such an applet is below but because it is simple enough, we shall not consider and make comments on it. We especially did not add in it any special checks and more complex functions so that the code would be easy to read, and the reader could concentrate on the process of its conversion into a trusted applet. Also, you can even create your own applet with your favorite visual editor (such as Sun ONE Studio, JBuilder, and so forth), but we provide this source code to help you to understand the process of signing applets faster.

1:    // TestApplet.java
2:    import java.io.*;
3:    import java.awt.*;
4:    import java.awt.event.*;
5:    import java.applet.*;
6:    import javax.swing.*;
7:    import javax.swing.border.*;
8:
9:    public class TestApplet extends JApplet
      implements ActionListener {
10:   private JPanel pane = null;
11:     private JScrollPane scrolling = null;
12:     private JTextPane fileBox = null;
13:     private JTextField tfFilename = null;
14:     private JButton butLoad = null;
15:     private final String LOAD = "load";
16:
17:   public void init() {
18:   try {
19:       jbInit();
20:     } catch(Exception e) {
21:       e.printStackTrace();
22:     }
23:   }
24:
25:   // method which will read data from file, and return it in
      // String
25:   public String readFile(String fn) {
26:     String thisLine, ret = "";
27:     try {
28:       FileInputStream fin =  new FileInputStream(fn);
29:       BufferedReader myInput = new BufferedReader
                         (new InputStreamReader(fin));
30:       while ((thisLine = myInput.readLine()) != null) {  
31:         ret += thisLine + "n";
32:       }
33:     } catch (Exception e) {
34:       ret = "Cannot load, exception!";
35:     }
36:     return ret;
37:   }
39:
40:   private void jbInit() throws Exception {
41:     pane = new JPanel();
42:     pane.setBounds(new Rectangle(0, 0, 500, 325));
43:     pane.setLayout(null);
44:     pane.setBorder(BorderFactory.createEtchedBorder(
                       EtchedBorder.LOWERED));
45:     pane.setBackground(new Color(221, 194, 219));
46:
47:     fileBox = new JTextPane();
48:     fileBox.setText("");
49:     fileBox.setEditable(false);
50:     scrolling = new JScrollPane(fileBox);
51:     scrolling.setBounds(new Rectangle(16, 65, 295, 225));
52:
53:     tfFilename = new JTextField();
54:     tfFilename.setText("");
55:     tfFilename.setBounds(new Rectangle(16, 23, 206, 29));
56:
57:     butLoad = new JButton();
58:     butLoad.setBounds(new Rectangle(231, 23, 80, 30));
59:     butLoad.setText("Load");
60:     butLoad.setActionCommand(LOAD);
61:     butLoad.addActionListener(this);
62:
63:     pane.add(scrolling);
64:     pane.add(tfFilename);
65:     pane.add(butLoad);
66:
67:     setContentPane(pane);
68:   }
69:
70:   public void actionPerformed(ActionEvent e) {
71:     if (e.getActionCommand().equals(LOAD)) {
72:         fileBox.setText(readFile(tfFilename.getText()));
73:     }
74:   }
75: }

Here we go. The next steps are pretty easy. We need to compile, create a jar archive, create a simple HTML file and demonstrational text file, and try to use it. Maybe it will be able to a load file even without signing! Let’s see. To compile and create a jar archive, follow these next steps:

javac TestApplet.java
jar cvf TestApplet.jar TestApplet.class

The cvf arguments force the jar utility to create a new archive with the specified name of TestApplet.jar and generate verbose output on standard output.

Okay, now please, with any text editor, create the TestApplet.html file and type the following contents into it:

1: <html><body>
2: <applet code="SignedApplet.class" archive="SignedApplet.jar"
           width=325 height=325>
3: </applet>
4: </body></html>

And, with the same text editor, create any text file—for example, C:Demo.txt—in which you need to type a few words or sentences. We have Hello World in our text file. So, if everything loaded properly, we should see exactly these words.

Show time! Copy your TestApplet.html and TestApplet.jar files into your webapps/ Tomcat directory where you are keeping your Web applications, and browse to the HTML file; in our case it’s http://localhost:8080/green/TestApplet.html. When the applet is loaded, type your simple text document path (C:Demo.txt) and click the ‘Load’ button. The following is what you will see:

Okay, we have an exception. I guess that’s not a surprise? Let’s try to sign it and see whether something changes. You will need to run the keytool utility this way:

keytool -genkey -alias TestApplet -validity 365

This will force keytool to generate a key certificate with the alias of TestApplet, with which it will be stored in your .keystore. Validity means how many days your key will remain valid; by default, it should be 180, but we want a whole year, so we set it to 365. Run this command from your Windows command prompt and you will get numerous easy questions from keytool, which you need to answer. Use the following screenshot as an example and there should be no difficulties.

As you can probably understand, the most important thing is, certainly, a password. You can use yours, but do not forget it. Remember, I told you in the very beginning that creating trusted applets is an easy operation, but you need to understand what’s going on at each step. We are almost finished, but first a few words about the keytool utility. I would recommend that you to pay some attention and read its manual about using these or other additional arguments. This way, you will more deeply understand its abilities. Okay, once we have our key generated, let’s do the simplest operation: just sign our applet with our key. Use the next command for that (please, remember to change the directory to the place where your TestApplet.jar stored):

jarsigner TestApplet.jar TestApplet

The first argument is our jar file and the second is a key alias that we just created above. jarsigner is not very affable, so you will not be able to see something else, which I didn’t see.

Congratulations! You just created your first real signed applet. I think that you can hardly wait to try how it works and I do not see any reason why you should not do that. Upload or just copy your signed jar archive into the directory where you placed your TestApplet.html and previous TestApplet.jar files, overwrite it, and again browse to your TestApplet.html.

Right after that, your applet will start loading and you will get a window that will be the same as, or very much like this one:

Probably you will not see ‘green’ in case you typed other data while generating your key. But the idea is the same. It’s asking you to accept or decline trusting this signed applet. Clicking ‘No’ will make the applet open like its old, unsigned version. It will stand in the “sandbox” and still have all restrictions to access the “outer” world. Clicking ‘Yes’ will earn a bit more freedom for our applet.

We clicked ‘Yes’, and our applet opened. Now, we need to do the same operation as above: type the path to our local file (C:Demo.txt) and click ‘Load’. And…

I believe you got the same result. So, our is task accomplished. Everything was not hard; it was not even complex. You just need to understand what are you doing in each step. I guess, after you have a feel for the additional power at your fingertips, you will be interested to learn exactly what a signed applet could also do. For this purpose, you need to look at http://java.sun.com/j2se/1.3/docs/tooldocs/win32/jarsigner.html, where you can get official information about the jarsigner utility and its possibilities.

© Olexiy Prokhorenko
http://www.7dots.com/resume
Co-author: Alexander Prohorenko

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories