Generating a SHA or SHA-1 message digest

Instantiate a MessageDigest object with the static method getInstance(“SHA”) or getInstance(“SHA-1″). Use the method update to pass in an array of bytes on which you want to compute a hash (you can call this method several times successively). After having passed in all the input bytes, get the digest by calling digest. The result is a 20 byte digest. You don’t need to reinstantiate a MessageDigest object if you need to compute digests of several byte streams, use the method reset to empty the buffer.

Main.java:

import java.security.*;
import java.io.*;
 
public class Main 
{
   public static void main(String []args) throws Exception {
      if (args.length != 1) {
         System.err.println("Usage: java Main <file>");
         System.exit(1);
      }
 
      BufferedInputStream bis = new BufferedInputStream(new FileInputStream(args[0]));
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      int c;
      while ((c = bis.read()) > -1) {
         baos.write(c);
      }
      bis.close();
      byte[] buf = baos.toByteArray();
 
      System.out.println(buf);
 
      MessageDigest md = MessageDigest.getInstance("SHA");
      md.update(buf);
      byte[] digest = md.digest();
 
      System.out.println("Digest (byte values):");
      for (int i=0; i<digest.length; i++) {
         System.out.print(digest[i] + " ");
      }
   }
}

Encrypting/decrypting using RC5

RC5 (Ron’s Code) is a block cipher, blocks of data are encrypted. Block size, key size and security level can be customized. In his paper, Ronald Rivest talks about a “variable number of rounds” allowing the user to make a tradeoff between higher security and higher speed, and a “variable length cryptographic key”. For more information, consult this cryptobytes edition (PDF).

Main.java:

import javax.crypto.spec.*;
import java.security.*;
import javax.crypto.*;
 
public class Main
{
   private static String algorithm = "RC5";
 
   public static void main(String []args) throws Exception {
      String toEncrypt = "The shorter you live, the longer you're dead!";
 
      System.out.println("Encrypting...");
      byte[] encrypted = encrypt(toEncrypt, "password");
 
      System.out.println("Decrypting...");
      String decrypted = decrypt(encrypted, "password");
    
      System.out.println("Decrypted text: " + decrypted);
   } 
 
   public static byte[] encrypt(String toEncrypt, String key) throws Exception {
      // create a binary key from the argument key (seed)
      SecureRandom sr = new SecureRandom(key.getBytes());
      KeyGenerator kg = KeyGenerator.getInstance(algorithm);
      kg.init(sr);
      SecretKey sk = kg.generateKey();
 
      // create an instance of cipher
      Cipher cipher = Cipher.getInstance(algorithm);
 
      // initialize the cipher with the key
      cipher.init(Cipher.ENCRYPT_MODE, sk);
 
      // enctypt!
      byte[] encrypted = cipher.doFinal(toEncrypt.getBytes());
 
      return encrypted;
   }
 
   public static String decrypt(byte[] toDecrypt, String key) throws Exception {
      // create a binary key from the argument key (seed)
      SecureRandom sr = new SecureRandom(key.getBytes());
      KeyGenerator kg = KeyGenerator.getInstance(algorithm);
      kg.init(sr);
      SecretKey sk = kg.generateKey();
 
      // do the decryption with that key
      Cipher cipher = Cipher.getInstance(algorithm);
      cipher.init(Cipher.DECRYPT_MODE, sk);
      byte[] decrypted = cipher.doFinal(toDecrypt);
 
      return new String(decrypted);
   }
}

Performing programmatic authorization with JAAS

Authorization

Authorization is about allowing or denying access to resources to a particular subject (a user, a group, a company, …). When a subject is authenticated, it is augmented with one or more principals that identify the subject for one or more resources, for example a social security number for one resource or a role of an administrator for another. A subject can also have credentials associated with them, any Java objects that contains security-related information about the subject, for example a certificate or a password.

To go ahead with this example, first read the authentication example.

In the following example, the authentication example will be augmented with a section that is only executed when it is permitted to do so by a particular principal, in our example “johndoe”. As opposed to specifying the principals and permissions in a policy file (see How do I use authorization with JAAS (declarative)) it is done programmatically.


We also have another policy file that grants permissions to read and write System properties (needed by the Swing DialogCallbackHandler), to create a LoginContext (necessary for authentication), to execute a doAsPrivileged method (necessary for executing sensitive code that requires principal permissions) and to modify principals (necessary when we add a principal to the subject). jaasmain.policy:

grant {
   permission java.util.PropertyPermission "*", "read, write";
   permission javax.security.auth.AuthPermission 
                    "createLoginContext.Main";
   permission javax.security.auth.AuthPermission "doAsPrivileged";
   permission javax.security.auth.AuthPermission "modifyPrincipals";
};

Our module that encapsulates code to do authentication has not changed from the authentication example.

UsernamePasswordLoginModule.java:

import javax.security.auth.callback.*;
import javax.security.auth.login.*;
import javax.security.auth.spi.*;
import javax.security.auth.*;
import java.security.*;
import java.util.*;
import java.io.*;
 
public class UsernamePasswordLoginModule implements LoginModule {
   private Subject subject;
   private CallbackHandler callbackHandler;
 
   private String username;
   private char[] password;
   private boolean loginSucceeded = false;
   private boolean commitSucceeded = false;
  
   private Principal principal;
 
   public void initialize(Subject subject, CallbackHandler callbackHandler, 
                          Map sharedState, Map options) {
      System.out.println("LoginModule initialize()");
      this.subject = subject;
      this.callbackHandler = callbackHandler;
      username = null;
      clearPassword();
      loginSucceeded = false;
      commitSucceeded = false;
   }
 
   public boolean login() throws LoginException {
      System.out.println("LoginModule login()");
      if (callbackHandler == null) {
         throw new LoginException("No CallbackHandler!");
      }
 
      Callback[] callbacks = new Callback[2];
      callbacks[0] = new NameCallback("Username: ");
      callbacks[1] = new PasswordCallback("Password: ", false);
 
      try {
         callbackHandler.handle(callbacks);
         username = ((NameCallback) callbacks[0]).getName();
         char[] temp = ((PasswordCallback) callbacks[1]).getPassword();
         password = new char[temp.length];
         System.arraycopy(temp, 0, password, 0, temp.length);
 
         BufferedReader br = new BufferedReader(new FileReader("passwd"));
         String line;
         while ((line = br.readLine()) != null) {
            int comma = line.indexOf(',');
            String un = line.substring(0, comma);
            String pw = line.substring(comma+1);
 
            if (username.equals(un) && new String(password).equals(pw)) {
               // succeeded!
               loginSucceeded = true;
               return true;
            }
         }
      }
      catch(IOException e) {
         throw new LoginException(e.toString());
      }
      catch(UnsupportedCallbackException e) {
         throw new LoginException(e.toString());
      }
 
      username = null;
      clearPassword();
      loginSucceeded = false;
 
      throw new FailedLoginException("Incorrect Username/Password");
   }
 
   public boolean commit() throws LoginException {
      System.out.println("LoginModule commit()");

      if (loginSucceeded == false) {
         return false;
      }
 
      principal = new MyPrincipal(username);
      if (!(subject.getPrincipals().contains(principal))) {
         subject.getPrincipals().add(principal);
      }
 
      username = null;
      clearPassword();
      commitSucceeded = true;
       
      return true;
   }
  
   public boolean abort() throws LoginException {
      System.out.println("LoginModule abort()");
 
      if (!loginSucceeded) {
         return false;
      }
      else if (loginSucceeded && commitSucceeded) {
         loginSucceeded = false;
         username = null;
         clearPassword();
         principal = null;
      }
      else {
         logout();
      }
 
      return true;
   }
 
   public boolean logout() throws LoginException {
      System.out.println("LoginModule logout()");
 
      subject.getPrincipals().remove(principal);
      loginSucceeded = false;
      commitSucceeded = false;
      username = null;
      clearPassword();
      principal = null;
 
      return true;
   }
 
   private void clearPassword() {
      if (password != null) {
         for (int i=0; i<password.length; i++) {
            password[i] = ' ';
         }
         password = null;
      }
   }
}

Our passwd “database” textfile has not changed from the authentication example.

passwd:

johndoe,sdefujm
janedoe,yuymndee

Our MyPrincipal class has also not changed from the authentication example.

MyPrincipal.java:

import java.security.*;
import java.io.*;
 
public class MyPrincipal implements Principal, Serializable
{
   private String name;

   public MyPrincipal(String name) {
      this.name = name;
   }
  
   public String getName() {
      return name;
   }
  
   public int hashCode() {
      return name.hashCode();
   }
 
   public String toString() {
      return getName();
   }
 
   public boolean equals(Object obj) {
      if (obj == null) {
         return false;
      }
 
      if (!(obj instanceof MyPrincipal)) {
         return false;
      }
 
      MyPrincipal mp = (MyPrincipal) obj;
      if (name.equals(mp.getName())) {
         return true;
      }
 
      return false;
   }
}

The code that is to be executed based on user authentication must be inside the run method of a class that implements java.security.PrivilegedAction.

WriteFileAction.java:

import java.security.PrivilegedAction;
import java.io.*;
 
public class WriteFileAction implements PrivilegedAction {
   public Object run() {
 
      try {
         BufferedWriter bw = new BufferedWriter(new FileWriter("c:\testfile"));
         bw.write("the shorter you live, the longer you're dead");
         bw.close();
         System.out.println("c:\testfile successfully written!");
      }
      catch(IOException e) {
         System.out.println(e);
      }
 
      return null;
   }
}

We want this code to be executed only when a specified principal is running it (“johndoe” as specified in the policy file). We enforce this by calling this code indirectly through the method doAs or doAsPrivileged. The difference between the two is described here.

Main.java:

import com.sun.security.auth.callback.*;
import javax.security.auth.login.*;
import javax.security.auth.*;
import java.security.*;
import java.util.*;
import java.io.*;
 
public class Main {
   public static void main(String []args) throws Exception { 
      try {
         LoginContext loginContext = new LoginContext("Main", 
                                             new DialogCallbackHandler());
 
         // will throw a LoginException if it fails, falls through otherwise
         loginContext.login();
 
         Subject subject = loginContext.getSubject();
         System.out.println(subject);
 
         PrivilegedAction action = new WriteFileAction();
         subject.doAsPrivileged(subject, action, null);
  
         loginContext.logout();
      }
      catch(LoginException e) {
         System.out.println("Unauthorized user!");
      } 
 
      // stop AWT thread (DialogCallbackHandler)
      System.exit(0);
   }
}

To run the code, you need to specify the policy files (or change the default java.policy one):

   c:jdk1.4binjava -Djava.security.auth.policy=accesscontrol.policy
                      -Djava.security.policy=jaasmain.policy
                      -Djava.security.auth.login.config==jaasmain.config
                      -Djava.security.manager
                      Main

Running the code with username=”johndoe”, password=”sdefujm” results in:

LoginModule initialize()
LoginModule login()
LoginModule commit()
Subject:
	Principal: johndoe

c:testfile successfully written!
LoginModule logout()

Running the code with username=”janedoe”, password=”yuymndee” (another authenticated user, but not authorized) results in:

LoginModule initialize()
LoginModule login()
LoginModule commit()
Subject:
	Principal: janedoe
Exception in thread "main" java.security.AccessControlException: access denied
java.io.FilePermission c:testfile write)
        at java.security.AccessControlContext.checkPermission(AccessControlCont
xt.java:273)
        at java.security.AccessController.checkPermission(AccessController.java
400)
        at java.lang.SecurityManager.checkPermission(SecurityManager.java:545)
        at java.lang.SecurityManager.checkWrite(SecurityManager.java:978)
        at java.io.FileOutputStream.<init>(FileOutputStream.java:103)
        at java.io.FileOutputStream.<init>(FileOutputStream.java:69)
        at java.io.FileWriter.<init>(FileWriter.java:44)
        at WriteFileAction.run(WriteFileAction.java:8)
        at java.security.AccessController.doPrivileged(Native Method)
        at javax.security.auth.Subject.doAsPrivileged(Subject.java:436)
        at Main.main(Main.java:21)

Notice that “janedoe” is correctly authenticated, but not authorized to run the privileged code as that principal is not specified in the policy file accesscontrol.policy.

Determining whether a particular year is a leap year in Java

The rule is that all years divisible by 4 are leap years. An exception is when the year is divisible by 100 unless the year is also divisible by 400.

On a GreorianCalendar instance, you can invoke the method isLeapYear.

Main.java:

import java.util.*;
 
public class Main {
   public static void main(String args[]) {
      GregorianCalendar calendar = new GregorianCalendar();
 
      for (int i=1990; i<2010; i++) {
         System.out.println(i + ": " + (calendar.isLeapYear(i) ? "yes" : "no"));
      }
   }
}

outputs:

1990: no
1991: no
1992: yes
1993: no
1994: no
1995: no
1996: yes
1997: no
1998: no
1999: no
2000: yes
2001: no
2002: no
2003: no
2004: yes
2005: no
2006: no
2007: no
2008: yes
2009: no

Using a java.util.logging ConsoleHandler

The following example uses a ConsoleHandler that logs to System.err. Our custom filter tells the logger only to log WARNING and FINE levels.

Main.java:

import java.util.logging.*;
import java.io.*;
 
public class Main
{
   public static void main(String argv[]) throws IOException {
      Logger logger = Logger.getLogger("main");
      logger.setUseParentHandlers(false);
      logger.setLevel(Level.ALL);
 
      ConsoleHandler ch = new ConsoleHandler();
      ch.setLevel(Level.ALL);
      ch.setFilter(new MyFilter());
      logger.addHandler(ch);
 
      logger.severe("log message #1");  
      logger.warning("log message #2");
      logger.info("log message #3");
      logger.config("log message #4");
      logger.fine("log message #5");
   }
}
 
class MyFilter implements Filter
{
   public boolean isLoggable(LogRecord lr) {
      if ((lr.getLevel() == Level.WARNING) ||
           (lr.getLevel() == Level.FINE))
         return true;
 
      return false;
   }
}

outputs:

Jan 20, 2002 4:46:14 AM Main main
WARNING: log message #2
Jan 20, 2002 4:46:15 AM Main main
FINE: log message #5

Generating a random float between x and y

You can use the formula:

   lowerbound + ((upperbound - lowerbound) * randomfloat)

To get a random float number, instantiate a Random object and call the method nextFloat which returns a pseudo-random float between 0 and 1.

Main.java:

import java.util.*;
  
public class Main {   
   static Random r = new Random();
 
   public static void main(String[] args) throws Exception {
  
      for (int i=0; i<10; i++) 
         System.out.println(getRandomFloat(-10, 15));
   }
 
   public static float getRandomFloat(float min, float max) {
      return min + (r.nextFloat() * (max - min));
   }
}

outputs:

-5.6623406
1.2526817
-9.871614
-9.995427
-1.407754
0.7924614
-5.201227
-3.9035373
11.673981
3.3402395

Calculating the checksum of a byte array using CRC32

Use the CRC32 class in the java.util.zip package. It contains an implementation of an algorithm to calculate the checksum of a set of bytes. It is slighly slower than Adler32, a class with the same purpose, but it generates a better result.

The procedure is simple: create an instance of the CRC32 class, call its method update and provide it with a set of bytes in the order as they appear in the stream. If all bytes have been processed, call getValue to get the checksum as a String.
If you need to calculate checksums of several bytestreams, you can reuse the CRC32 instance but you need to call reset in order to reset it to its original state.

Following example displays a checksum of a file provided at command line.

Main.java:

import java.util.zip.*;
import java.io.*;
 
public class Main {
   public static void main(String args[]) {
      if (args.length != 1) {
         System.err.println("Usage: java Main <file>");
         System.exit(1);
      }
 
      try {
         CRC32 crc32 = new CRC32();
         BufferedInputStream bis = new BufferedInputStream(new FileInputStream(args[0]));
  
         int l = 0;
         byte[] buffer = new byte[1024];
         while ((l = bis.read(buffer)) >= 0) {
            crc32.update(buffer, 0, l);
         }
 
         System.out.println("CRC-32 checksum of file " + args[0] + ":");
         System.out.println(crc32.getValue());
      }
      catch(IOException e) {
         System.err.println(e);
      }
   }
}

Controlling permissions with a JApplet

It is important that you have installed the JRE1.3 on your machine, that includes the Java 1.3 plug-in.

An JApplet runs by default in a security sandbox, an environment where it has no permission to do anything that might harm the client’s machine.

Consider the following applet.

WriteFile.java:

import javax.swing.*;
import java.awt.*;
import java.io.*;
 
public class WriteFile extends JApplet {
   public void paint(Graphics g) {
      String filename = "/tmp/esusfoo";
      if (System.getProperty("os.name").indexOf("Windows") != -1) {
         filename = "C:\esusfoo";
      }
 
      try {
         BufferedWriter bw = new BufferedWriter(new FileWriter(filename));
         bw.write("The sun is green and the grass shines.n");
         bw.flush();
         bw.close();
 
         g.drawString("File " + filename + " created!", 10, 10);
      }
      catch (Exception e) {
         g.drawString(""+e, 10, 10);
      }
   }
}

WriteFile.html (generated with Sun’s HTMLConverter tool):

<html>
<body>
 
<!--"CONVERTED_APPLET"-->
<!-- CONVERTER VERSION 1.0 -->
<OBJECT classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
WIDTH = 700 HEIGHT = 100  
codebase="http://java.sun.com/products/plugin/1.3/jinstall-13-win32.cab#Version=1,3,0,0">

<PARAM NAME = CODE VALUE = WriteFile >
 
<PARAM NAME="type" VALUE="application/x-java-applet;version=1.3">
<COMMENT>
<EMBED type="application/x-java-applet;version=1.3" java_CODE = WriteFile 
WIDTH = 700 HEIGHT = 100   
pluginspage="http://java.sun.com/products/plugin/1.3/plugin-install.html">
<NOEMBED></COMMENT>
 
</NOEMBED></EMBED>
</OBJECT>
 
<!--
<APPLET  CODE = WriteFile WIDTH = 700 HEIGHT = 100 >
 
 
</APPLET>
-->
<!--"END_CONVERTED_APPLET"-->
 
 
</body>
</html>

When you run this JApplet, you’ll get a security exception.
Check it out for yourself at http://www.esus.com/applets/WriteFile.html.

So what do we need to do to make this work?

You will have to explicitely give access to that applet to use resources it is normally not permitted to. To do so, one requirement is to sign our applet. The following procedure shows you how to sign an applet. You will need to have a certificate, either one you create yourself (a self-signed applet) or one that you have bought from a certificate authority like VeriSign or Thawte. For now, I’ll create one myself.

Create a certificate with keytool (JDK tool introduced in JDK1.2.2):

C:certificateapplet> keytool -genkey -alias esustest -keyalg rsa
Enter keystore password:  esuspass
What is your first and last name?
  [Unknown]:  Joris Van den Bogaert
What is the name of your organizational unit?
  [Unknown]:  ESUS Team
What is the name of your organization?
  [Unknown]:  ESUS, Inc.
What is the name of your City or Locality?
  [Unknown]:  Meerbeek
What is the name of your State or Province?
  [Unknown]:
What is the two-letter country code for this unit?
  [Unknown]:  BE
Is <CN=Joris Van den Bogaert, OU=ESUS Team, O="ESUS, Inc.", L=Meerbeek, ST=Unkno
wn, C=BE> correct?
  [no]:  yes

Enter key password for <esustest>
        (RETURN if same as keystore password):

C:certificateapplet>

(Note: if you haven’t used keytool before, just make up a password) Here we have created a RSA key with the name esustest. Now look in your home directory, a file should have been created called .keystore:

C:certificateapplet> dir c:windows.key*

 Volume in drive C has no label
 Volume Serial Number is 1380-0FE3
 Directory of C:WINDOWS

KEYSTO~1             1,382  07-21-01  1:28a .keystore
         1 file(s)          1,382 bytes
         0 dir(s)     164,356,096 bytes free

To see that the key has been added to the store:

C:certificateapplet> keytool -list
Enter keystore password:  esuspass

Keystore type: jks
Keystore provider: SUN

Your keystore contains 1 entry:

esustest, Sat Jul 21 01:28:48 CEST 2001, keyEntry,
Certificate fingerprint (MD5): 88:09:3D:97:3A:7B:91:AD:4B:01:B8:3E:40:B8:C6:2A

Now let’s create a JAR file from our applet:

C:certificateapplet>jar cvf WriteFile.jar WriteFile.class
added manifest
adding: WriteFile.class(in = 1250) (out= 732)(deflated 41%)

The jar has been created:

C:certificateapplet> dir *.jar

 Volume in drive C has no label
 Volume Serial Number is 1380-0FE3
 Directory of C:certificateapplet

WRITEF~1 JAR         1,196  07-21-01  1:38a WriteFile.jar
         1 file(s)          1,196 bytes
         0 dir(s)     164,347,904 bytes free

Now we can sign that JAR file with our generated keypair as follows:

C:certificateapplet> jarsigner WriteFile.jar esustest
Enter Passphrase for keystore: esuspass

C:certificateapplet> dir *.jar

 Volume in drive C has no label
 Volume Serial Number is 1380-0FE3
 Directory of C:certificateapplet

WRITEF~1 JAR         2,348  07-21-01  1:38a WriteFile.jar
         1 file(s)          2,332 bytes
         0 dir(s)     164,347,904 bytes free

Notice the size of our original JAR and the new digitally signed JAR! We can verify the JAR as follows:


C:certificateapplet>jarsigner -verify -certs -verbose WriteFile.jar

         136 Sat Jul 21 05:22:54 CEST 2001 META-INF/MANIFEST.MF
         189 Sat Jul 21 05:22:56 CEST 2001 META-INF/ESUSTEST.SF
         980 Sat Jul 21 05:22:56 CEST 2001 META-INF/ESUSTEST.RSA
           0 Sat Jul 21 05:22:16 CEST 2001 META-INF/
smk     1213 Sat Jul 21 05:21:10 CEST 2001 WriteFile.class

      X.509, CN=Joris Van den Bogaert, OU=ESUS Team, O="ESUS, Inc.", L=Meerbeek,
 ST=Unknown, C=BE (esustest)


  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.

Notice the files that have been added to the JAR file:ESUSTEST.SF and ESUSTEST.RSA. SF stands for Signature File and it includes the filename (WriteFile.class), the name of the algorithm used (RSA) and the digest value. Test it out for yourself:

C:certificateapplet>jar -xf WriteFile.jar META-INF/ESUSTEST.SF

C:certificateapplet>dir

 Volume in drive C has no label
 Volume Serial Number is 1380-0FE3
 Directory of C:certificateapplet

.              <DIR>        07-21-01 12:32a .
..             <DIR>        07-21-01 12:32a ..
WRITEF~1 JAV           728  07-21-01  1:14a WriteFile.java
WRITEF~1 CLA         1,250  07-21-01  1:14a WriteFile.class
WRITEF~1 HTM            95  07-21-01 12:47a WriteFile.html
WRITEF~1 JAR         2,348  07-21-01  1:38a WriteFile.jar
META-INF       <DIR>        07-21-01  1:45a META-INF
         4 file(s)          4,405 bytes
         3 dir(s)     164,265,984 bytes free

C:certificateapplet>cd meta-inf

C:certificateappletMETA-INF>dir

 Volume in drive C has no label
 Volume Serial Number is 1380-0FE3
 Directory of C:certificateappletMETA-INF

.              <DIR>        07-21-01  1:45a .
..             <DIR>        07-21-01  1:45a ..
ESUSTEST SF            189  07-21-01  1:45a ESUSTEST.SF
         1 file(s)            189 bytes
         2 dir(s)     164,265,984 bytes free

C:certificateappletMETA-INF> type esustest.sf
Signature-Version: 1.0
SHA1-Digest-Manifest: Zy9znt1bwLpXeGV+pr+rkaHU4Rw=
Created-By: 1.2.2 (Sun Microsystems Inc.)

Name: WriteFile.class
SHA1-Digest: JFrqA7g/ZadrRHkJmXgsCTwZRSo=

The other file that has been added to the JAR is ESUSTEST.RSA. This is the Signature Block File It contains the certificate or certificate chain.

Now we’re ready to deploy our signed applet and see if that changed the situation. Let’s first modify our HTML file so that it uses the JAR file instead of the class file.

WriteFile2.html:

<html>
<body>
This file will create a file on your drive called esusfoo.  
Under Windows it will be located in C:, under unix it will be located in /tmp.  
If you do not want this to happen, click DENY when your browser asks you 
for additional permissions.
<br><br><br><br>
<!--"CONVERTED_APPLET"-->
<!-- CONVERTER VERSION 1.3 -->
<OBJECT classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
WIDTH = 700 HEIGHT = 100  
codebase="http://java.sun.com/products/plugin/1.3/jinstall-13-win32.cab#Version=1,3,0,0">
<PARAM NAME = CODE VALUE = "WriteFile.class" >
<PARAM NAME = ARCHIVE VALUE = "WriteFile.jar" >

<PARAM NAME="type" VALUE="application/x-java-applet;version=1.3">
<PARAM NAME="scriptable" VALUE="false">
<COMMENT>
<EMBED type="application/x-java-applet;version=1.3"  CODE = "WriteFile.class" 
ARCHIVE = "WriteFile.jar" WIDTH = 700 HEIGHT = 100  scriptable=false 
pluginspage="http://java.sun.com/products/plugin/1.3/plugin-install.html">
<NOEMBED></COMMENT>

</NOEMBED></EMBED>
</OBJECT>

<!--
<APPLET CODE = "WriteFile.class" ARCHIVE = "WriteFile.jar" WIDTH = 700 HEIGHT = 100>


</APPLET>
-->
<!--"END_CONVERTED_APPLET"-->


</body>
</html>

Upload the files to your webserver and try it out! You can also try it out here:
http://www.esus.com/applets/WriteFile2.html.

With both Netscape and IE, you’ll get the following window:




Hmm, it doesn’t really create a file, does it? Well, earlier version of the plug-in (JDK1.2.2) would actually ask you if you want to grant extra permissions. But from the 1.3 plugin onwards, self-signed applets (like our WriteFile.jar) will need extra work! If you would have signed your applet with a certificate you bought from a recognized standard root CA, like VeriSign or Thawte, the browser would ask you if you want to grant additional permissions. Check out http://java.sun.com/products/plugin/1.3/docs/nsobjsigning.html!

Just like anyone else, I don’t have no money :) So for the time being, I won’t buy such a certificated from a trusted CA. But I’ll show you a way to have your applet run anyway (useful for testing purposes). It is important to realize that in order to do so, you must have access to the client’s machine(s) onto which you want to deploy your applet.

What happens when you download a signed applet is this: the browser downloads the JAR file and checks whether it is signed. If it is, it will check the security policy configuration file whether the “usePolicy” RuntimePermission is set. There are two policy files, a system-wide one, (JRE_HOME/lib/security/java.policy) and a user specific one (USER_HOME/.java.policy). In my case, my system-wide one is at C:Program FilesJavaSoftJRE1.3.1libsecurity and my user one is at C:Windows.java.policy. When the plug-in starts, it will concatenate both of them together and use them as a security policy for the rest of the session. If the usePolicy permission is set, security is controlled based on the permissions that are set in the policy files, even if you have an RSA signed applet signed by a trusted authority that wants full control over your client’s machine. This allows you to have finer-grained security control over what your signed applets are able to do.

Let’s change our policy file to grant the permission to write to the local file c:esusfoo. Add the following lines of code to your .java.policy file:

grant {
   permission java.io.FilePermission "C:${/}esusfoo", "write";
};

and test out http://www.esus.com/applets/WriteFile2.html again.

You get the following error:



Click OK, the file will be created anyway, since you granted that permission explicitely in your policy file.

To get rid of that annoying error, define the extra permission “usePolicy” in your policy file:

grant {
   permission java.lang.RuntimePermission "usePolicy";
   permission java.io.FilePermission "C:${/}esusfoo", "write";
};

Try out the applet again! No errors!

Let’s modify the applet a bit so that it also tries to write to a file c:esusfoo2. The new applet look like this.

WriteTwoFiles.java:

import javax.swing.*;
import java.awt.*;
import java.io.*;
 
public class WriteTwoFiles extends JApplet {
   public void paint(Graphics g) {
      String filename1 = "/tmp/esusfoo";
      String filename2 = "/tmp/esusfoo2";
      if (System.getProperty("os.name").indexOf("Windows") != -1) {
         filename1 = "C:\esusfoo";
         filename2 = "C:\esusfoo2";
      }
 
      BufferedWriter bw;
      try {
         bw = new BufferedWriter(new FileWriter(filename1));
         bw.write("The sun is green and the grass shines.n");
         bw.flush();
         bw.close();
 
         g.drawString("File " + filename1 + " created!", 10, 10);
      }
      catch (Exception e) {
         g.drawString(""+e, 10, 10);
      }
 
      try { 
         bw = new BufferedWriter(new FileWriter(filename2));
         bw.write("The sun shines and the grass is green.n");
         bw.flush();
         bw.close();
 
         g.drawString("File " + filename2 + " created!", 10, 50);
      }
      catch (Exception e) {
         g.drawString(""+e, 10, 50);
      }
   }
}

Sign the jar file as described above:

C:certificateapplet> jar cvf WriteTwoFiles.jar WriteTwoFiles.class
added manifest
adding: WriteTwoFiles.class(in = 1458) (out= 822)(deflated 43%)

C:certificateapplet> jarsigner WriteTwoFiles.jar esustest
Enter Passphrase for keystore: esuspass

WriteTwoFiles.html:

<html>
<body>
<br>
<!--"CONVERTED_APPLET"-->
<!-- CONVERTER VERSION 1.3 -->
<OBJECT classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
WIDTH = 700 HEIGHT = 100  
codebase="http://java.sun.com/products/plugin/1.3/jinstall-13-win32.cab#Version=1,3,0,0">
<PARAM NAME = CODE VALUE = "WriteTwoFiles.class" >
<PARAM NAME = ARCHIVE VALUE = "WriteTwoFiles.jar" >

<PARAM NAME="type" VALUE="application/x-java-applet;version=1.3">
<PARAM NAME="scriptable" VALUE="false">
<COMMENT>
<EMBED type="application/x-java-applet;version=1.3"  
CODE = "WriteTwoFiles.class" ARCHIVE = "WriteTwoFiles.jar" WIDTH = 700 HEIGHT = 100  
scriptable=false pluginspage="http://java.sun.com/products/plugin/1.3/plugin-install.html">
<NOEMBED></COMMENT>

</NOEMBED></EMBED>
</OBJECT>

<!--
<APPLET CODE = "WriteTwoFiles.class" ARCHIVE = "WriteTwoFiles.jar" WIDTH = 700 HEIGHT = 100>


</APPLET>
-->
<!--"END_CONVERTED_APPLET"-->


</body>
</html>

If you run this signed applet (http://www.esus.com/applets/WriteTwoFiles.html), using the same modified policy file, esusfoo was successfully accessed but, a AccessControlException is thrown in accessing esusfoo2, as expected.

One more problem: the extra permissions to write to esusfoo and esusfoo2 are granted to all applets. You can fine-tune your policy configuration file with signedBy and/or codeBase. With signedBy, you can specify the keystore entry that contains the public key so that verification of the signed JAR file is possible. The runtime system then verifies the association of the private key with which the JAR file was signed with the public key of the specified entry in the keystore. codeBase specifies that the permissions in this grant entry are only applicable to signed applets coming from a particular code source.

Because we’re using a self-signed applet, we need to import our certificate in the keystore of the plug-in. The following steps show you how to:

  1. export the certificate to a file:
    C:certificateapplet> keytool -export -alias esustest -file esustest.cer
    Enter keystore password:  esuspass
    Certificate stored in file <esustest.cer>
    
  2. copy esustest.cer to the directory that contains the file cacerts:
    C:certificateapplet> copy esustest.cer "c:program filesjavasoftjre1.3.1libsecurity
            1 file(s) copied
    
  3. make a backup of cacerts:
    C:Program FilesJavaSoftJRE1.3.1libsecurity>copy cacerts cacerts.bak
            1 file(s) copied
    
  4. import the certificate into the cacerts keystore:
    C:Program FilesJavaSoftJRE1.3.1libsecurity>keytool -import -alias esustest
     -keystore cacerts -file esustest.cer
    Enter keystore password:  changeit
    Owner: CN=Joris Van den Bogaert, OU=ESUS Team, O="ESUS, Inc.", L=Meerbeek, ST=Un
    known, C=BE
    Issuer: CN=Joris Van den Bogaert, OU=ESUS Team, O="ESUS, Inc.", L=Meerbeek, ST=U
    nknown, C=BE
    Serial number: 3b58beaa
    Valid from: Sat Jul 21 01:28:42 CEST 2001 until: Fri Oct 19 01:28:42 CEST 2001
    Certificate fingerprints:
             MD5:  88:09:3D:97:3A:7B:91:AD:4B:01:B8:3E:40:B8:C6:2A
             SHA1: 6A:A1:0E:19:45:91:07:97:B0:75:BE:BB:79:91:2A:1A:27:F2:36:93
    Trust this certificate? [no]:  yes
    Certificate was added to keystore
    

    (Note: the initial password for the cacerts file is changeit as specified in the documentation)

Our self-signed certificate is now added to our database.

Run WriteTwoFiles again. Notice that now you’ll get the following dialog box:




This dialog box would also show up if your applet was signed by a certificate assigned by a VeriSign or Thawte type trusted CA.

Now change to policy file for more fine-grained control:

grant signedBy "esustest", codeBase "http://www.esus.com/applets/WriteTwoFiles.jar" {
   permission java.lang.RuntimePermission "usePolicy";
   permission java.io.FilePermission "C:${/}esusfoo", "write";
   permission java.io.FilePermission "C:${/}esusfoo2", "write";
};

Creating a JFrame that cannot be resized

There is no good way to do this. The closest thing is to create a regular Frame (it doesn’t really matter whether it’s JFrame or Frame for this issue), register a ComponentListener on it and whenever it is resized, resize it back to its original size.

Most times you don’t need to do this though, you can almost always use a Window to achieve what you want.