Getting the acos, asin or atan or a number

The asin is the inverse sin: sin(a) = b, asin(b) = a
The acos is the inverse cos: cos(a) = b, acos(b) = a
The atan is the inverse tan: tan(a) = b, atan(b) = a

To use asin, acos and atan in your Java programs, use the static methods in the Math class.
Here’s an example:

import java.math.*;
                           
public class Main 
{  
   public static void main(String args[]) throws Exception {
      double asinAngle = Math.asin(0.6287930240184686);
      double acosAngle = Math.acos(0.7775727187509279);
      double atanAngle = Math.atan(0.8086613751425653);
 
      System.out.println("asin: " + asinAngle);
      System.out.println("acos: " + acosAngle);
      System.out.println("atan: " + atanAngle);
   }
}

outputs:

asin: 0.6800000000000002
acos: 0.68
atan: 0.68

Note: angles to the trigonometric math methods should be given in radians.
If you want to use degrees, you have to convert the radians first:

     360 degrees = 2 pi radians
 
     So, to convert radians into degrees, multiply by 180 / Math.PI
         to convert degrees into radians, multiply by Math.PI / 180

Getting the contents of a URL in Java

import java.net.*;
import java.io.*;
 
class UrlDemo1
{
   public static void main(String [] args)
   {
      try
      {
         // step1: make a url object
         URL u=new URL("http:/C:/lbs/first.html");
 	
	 // step2: make a file object 
         // using the getFile method of the url class
         File f=new File(u.getFile());
         System.out.println(f.getName());//verify the name
         System.out.println(f.exists());//verify if the file exists
 
         // step3: start a datainputstream  and 
         // read from it and print
         DataInputStream dis =new DataInputStream(new FileInputStream (f));
         while(dis.readLine()!=null)
            System.out.println(dis.readLine());
      }
      catch(Exception e)
      {
         System.out.println(e);
      }
   }
}

Connecting to the daytime port (13)

The daytime port 13 will return a datagram containing the server time.
On many systems, this port is being disabled, fearing hackers may use it to perform a denial-of-service attack of some sort. Based on the date format that the server returns, the hacker may also find out about the operating system.

Just open a socket and read a line. It will contain the server time if the port is enabled.
DaytimeClient.java:

import java.util.*;
import java.net.*;
import java.io.*;
 
public class DaytimeClient {
   public static void main(String args[]) {
      if (args.length != 1) {
         System.out.println("java DaytimeClient <server>");
         System.exit(1);
      }
 
      try {
         Socket socket = new Socket(args[0], 13);    // 7 is echo port
         BufferedReader br = new BufferedReader(
                                new InputStreamReader(socket.getInputStream()));
  
         String ret = br.readLine();
         System.out.println(ret);
 
         socket.close();       
      }
      catch(Exception e) {
         e.printStackTrace();
      }
   }
}

Generating a MD5 message digest

What MD5 is and why it it important is explained well on the following page:

http://www.enteract.com/~lspitz/md5.html

A digest has two properties:
- it is computationally infeasible to find another input string that generates the same digest
- the digest does not reveal anything about the input that was used to generate it.

The engine class MessageDigest provides the functionality of several
types of cryptographic algorithms. What algorithms are available depends
on the provider you are using. For example, Sun (the default provider) supplies
implementations of the MD5 and SHA-1 message digest algorithms. Other providers
may have their own implementation of these algorithms or other algorithms.

As an implementation is supplied by Sun in the JDK, you don’t even have to
install another provider. Here’s is an example using the implementation by Cryptix:

 
import cryptix.util.core.Hex;
import cryptix.util.test.BaseTest;
import java.security.MessageDigest;
 
class TestMD5 
{
   public static void main(String[] args) {
      String plaintext = "The sun is green and the grass shines";

      MessageDigest md = null;
      try {
         // first create an instance, given the provider
         md = MessageDigest.getInstance("MD5", "Cryptix");
      }
      catch(java.security.NoSuchProviderException e) {
         System.out.println(e);
         System.exit(1);
      }
      catch(java.security.NoSuchAlgorithmException e) {
         System.out.println(e);
         System.exit(1);
      }

      md.reset();

      // call the update method one or more times 
      // (useful when you don't know the size of your data, eg. stream)
      md.update(plaintext.getBytes());

      // now calculate the hash
      byte[] hash = md.digest();

      System.out.println("Plaintext:nt" + plaintext + "n");
      // Hex is a function provided by Cryptix to produce a nice output
      System.out.println("Message Digest:nt" + Hex.toString(hash));
   }
}

generates the output:

 
Plaintext:
	The sun is green and the grass shines

Message Digest:
	470DB3B23F9D445446DFCE291C9F17AB

Encrypting/decrypting using RC4

RC4 (Ron’s Code) is a symmetric key encryption algorithm. Developed in 1987 by Ronald Rivest, it is used in SSL and many applications such as Lotus Notes and Oracle Secure SQL.

RC4 is a stream cipher, meaning that it encrypts one byte at a time. With RC4, the key is variable, from 1 to 2048 bits. RC4 is about 10 times as fast as DES. The algorithm is small and simple to implement. Here’s an unreadable version of it written in Perl.

Main.java:

import javax.crypto.spec.*;
import java.security.*;
import javax.crypto.*;
 
public class Main
{
   private static String algorithm = "RC4";
 
   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 declarative 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”. The following policy file will grant permissions to the principal “johndoe” to read and write to the file “c:\testfile”. A policy file specifies what permissions are allowed to code coming from a specified code source and executed by a specified principal.

accesscontrol.policy:

/** User-Based Access Control Policy **/

grant Principal MyPrincipal "johndoe" {
   permission java.io.FilePermission "c:/testfile", "read,write";
};

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";
   permission javax.security.auth.AuthPermission "doAsPrivileged";
   permission javax.security.auth.AuthPermission "modifyPrincipals";
};

jaas.config:

MyAuthenticationComponents {
   UsernamePasswordLoginModule required;
};

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("MyAuthenticationComponents", 
                                             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==jaas.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.

Using a HashSet in Java

A HashSet holds a set of objects, but in a way that it allows you to easily and quickly determine whether an object is already in the set or not. It does so by internally managing an array and storing the object using an index which is calculated from the hashcode of the object.

For more information on hashing, check out the HashMap category.

Things to remember:
– A HashSet is not synchronized, so not thread-safe.
– Its elements are not ordered
– Add an element to the HashSet with the method add(Object o)
– Remove an element with the method remove(Object o)
– Remove all elements with the method clear()
– Get the number of elements with the method size()

Here’s an example:

import java.util.*;
import java.io.*;
    
public class Main 
{
   public static void main(String []args) throws Exception {
      String[] keywords = { "abstract", "boolean", "break", "byte", "case", "cast",
                            "catch", "char", "class", "const", "continue", "default",
                            "do", "double", "else", "extends", "final", "finally",
                            "float", "for", "future", "generic", "goto", "if",
                            "implements", "import", "inner", "instanceof", "int",
                            "interface", "long", "native", "new", "null", "operator",
                            "outer", "package", "private", "protected", "public",
                            "rest", "return", "short", "static", "super", "switch",
                            "synchronized", "this", "throw", "throws", "transient",
                            "try", "var", "void", "volatile" };
 
      // convert this array to a Collection and create a HashSet
      HashSet hs = new HashSet(Arrays.asList(keywords));
 
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      
      String line;
      System.out.print("Enter keyword ('exit' to exit): ");
      line = br.readLine();
      while (!line.equals("exit")) {
         if (hs.contains(line)) {
            System.out.println("t" + line + " is a Java keyword!");
         }
         else {
            System.out.println("t" + line + " is not a Java keyword!");
         }
         System.out.print("Enter keyword ('exit' to exit): ");
         line = br.readLine();
      }
   }
}

sample output:

C:>java Main
Enter keyword ('exit' to exit): public
        public is a Java keyword!
Enter keyword ('exit' to exit): jefke
        jefke is not a Java keyword!
Enter keyword ('exit' to exit): instanceof
        instanceof is a Java keyword!
Enter keyword ('exit' to exit): coke
        coke is not a Java keyword!
Enter keyword ('exit' to exit): esus
        esus is not a Java keyword!
Enter keyword ('exit' to exit): package
        package is a Java keyword!
Enter keyword ('exit' to exit): exit

Comparing whether a date comes before or after another date in Java

The Date class has two useful methods for this: before and after.

Main.java:

import java.util.*;
import java.text.*;
   
public class Main {
   public static void main(String args[]) {
      Date date1, date2, date3;
 
      try {
         DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
         date1 = df.parse("20/12/72");   // date in the past
         date2 = new Date();             // current date
         date3 = df.parse("05/07/06");   // date in the future
 
         System.out.println(date2.after(date1));
         System.out.println(date2.after(date3));
         System.out.println(date2.before(date1));
         System.out.println(date2.before(date3));
      }
      catch(ParseException e) {
         e.printStackTrace();
      }
  
   }
}

outputs:

true
false
false
true