Encrypting/decrypting using Skipjack

Check out the following pages for more infomration on Skipjack encryption:
http://www.tropsoft.com/strongenc/skipjack.htm
http://www.cs.technion.ac.il/~biham/Reports/SkipJack/note1.html

Main.java:

import javax.crypto.spec.*;
import java.security.*;
import javax.crypto.*;
import org.bouncycastle.util.encoders.Hex;
 
public class Main
{
   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("Skipjack");
      kg.init(sr);
      SecretKey sk = kg.generateKey();
 
      // create an instance of cipher
      Cipher cipher = Cipher.getInstance("Skipjack");
 
      // 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("Skipjack");
      kg.init(sr);
      SecretKey sk = kg.generateKey();
 
      // do the decryption with that key
      Cipher cipher = Cipher.getInstance("Skipjack");
      cipher.init(Cipher.DECRYPT_MODE, sk);
      byte[] decrypted = cipher.doFinal(toDecrypt);
 
      return new String(decrypted);
   }
}

(tested with the BouncyCastle JCE provider, http://www.bouncycastle.org)

Tokenize a text into words

Use the BreakIterator class. First get an instance through the factory method getWordInstance, initialize it with the text using setText and iterate through the elements with first and next.

This example uses the following text: text.txt:

It is, in fact, nothing short of a miracle that the modern methods 
of instruction have not yet entirely strangled the holy curiosity 
of inquiry; for this delicate little plant, aside from stimulation, 
stands mainly in need of freedom; without this it goes to wrack and 
ruin without fail. It is a very grave mistake to think that the 
enjoyment of seeing and searching can promoted by means of coercion 
and sense of duty. To the contrary, I believe that it would be 
possible to rob even a healthy beast of prey of its voraciousness, 
if it were possible, with the aid of a whip, to force the beast to 
devour continuously, even when not hungry,especiallyif the food, 
handed out under such coercion, were to be selected accordingly. 

Albert Einstein 

Main.java:

import java.text.*;
import java.io.*;
  
public class Main {
   public static void main(String args[]) {
      if (args.length != 1) {
         System.err.println("Usage: java Main <file.txt>");
         System.exit(1);
      }
 
      String text = readFile(args[0]);
 
      BreakIterator biWord = BreakIterator.getWordInstance();
      biWord.setText(text);
      System.out.println("Splitting text up into wordsn");
      printInstances(biWord, text);
   }  
 
   public static void printInstances(BreakIterator bi, String text) {
      int start = bi.first();
      int end = bi.next();
      while (end != BreakIterator.DONE) {
         System.out.println("Found: " + text.substring(start, end));
         start = end;
         end = bi.next();
      }
   }
 
   public static String readFile(String filename) {
      StringBuffer total = new StringBuffer();
 
      try {
         BufferedReader br = new BufferedReader(new FileReader(filename));
         String line;
         while ((line = br.readLine()) != null) {
            total.append(line + "n");
         }
      }
      catch(Exception e) {
         e.printStackTrace();
         System.exit(1);
      }
      return total.toString();
   }
}

outputs:

Splitting text up into words

Found: It
Found:  
Found: is
Found: ,
Found:  
Found: in
Found:  
Found: fact
Found: ,
Found:  
Found: nothing
Found:  
Found: short
Found:  
Found: of
Found:  
Found: a
Found:  
Found: miracle
Found:  
Found: that
Found:  
Found: the
Found:  
Found: modern
Found:  
Found: methods
Found:  

Found: of
Found:  
Found: instruction
Found:  
Found: have
Found:  
Found: not
Found:  
Found: yet
Found:  
Found: entirely
Found:  
Found: strangled
Found:  
Found: the
Found:  
Found: holy
Found:  
Found: curiosity
Found:  

Found: of
Found:  
Found: inquiry
Found: ;
Found:  
Found: for
. . .

Note that also whitespace and punctuation are returned as being words. You may want to change the method so that it recognizes this fact, for example by checking whether the first character of the word is a letter.

Using a TreeMap in Java

A TreeMap maintains key/value objects in sorted order by using a balanced red-black tree. A red-black tree is a balanced binary tree, meaning a parent node has maximum 2 children and as an entry is inserted, the tree is monitored as to keep it well-balanced. For more information about red-black trees, check out the sites below!

Keeping the binary tree balanced ensures the fast insertion, removal and lookup time of O(log n). Not as fast as a HashMap which is O(constant), but remember that the TreeMap has the advantage that the keys are in sorted order which opens up a lot of other capabilities.

Following example shows most of the useful methods in TreeMap.

Main.java:

import java.util.*;
import java.io.*;
    
public class Main 
{
   public static void main(String []args) throws Exception {
      String[] colors = { "black", "white", "blue", "green", 
                          "red", "yellow", "magenta", "cyan", 
                          "orange", "redorange",
                         "violet", "purple" };
      String[] rgbs = { "[0,0,0]", "[255,255,255]", "[0,0,255]", "[0,255,0]", 
                        "[255,0,0]", "[255,255,0]", "[255,0,255]", "[0,255,255]",
                        "[255,165,0]", "[255,69,0]", "[255,69,0]",
                        "[238,130,238]", "[160,32,240]" };
 
      TreeMap tm = new TreeMap();
 
      for (int i=0; i<colors.length; i++) {
         tm.put(colors[i], rgbs[i]);
      }
 
      // containsKey, checks existence of a key
      System.out.println("containsKey("magenta"):nt" + 
                                tm.containsKey("magenta") + "n");
 
      // get, gets the value given the key
      System.out.println("get("yellow"):nt" + tm.get("yellow") + "n");
 
      // put, puts a key/value pair in the TreeMap
      tm.put("greenblue", "[46,139,87]");
 
      // firstKey, returns key for first entry
      System.out.println("firstKey():nt" + tm.firstKey() + "n");
 
      // lastKey, returns key for last entry
      System.out.println("lastKey():nt" + tm.lastKey() + "n");
 
      // entrySet, returns Set with key/value pairs each stored in 
      // an object of type Map.Entry
      Set entrySet = tm.entrySet();
      System.out.println("entrySet():nt" + entrySet + "n");
 
      // keySet, returns Set containing all keys
      Set keySet = tm.keySet();
      System.out.println("keySet():nt" + keySet + "n");
 
      // values, returns Collection containing all values
      Collection values = tm.values();
      System.out.println("values():nt" + values + "n");
 
      // headMap, returns sorted map of entries that are < than specified argument
      SortedMap headMap = tm.headMap("purple");
      System.out.println("headMap("purple"):nt" + headMap + "n");
 
      // subMap, returns sorted submap of entries that appear between two arguments
      SortedMap subMap = tm.subMap("green", "redorange");
      System.out.println("subMap("green", "redorange"):nt" + subMap + "n");
 
      // tailMap, returns sorted map of entries that are > than specified argument
      SortedMap tailMap = tm.tailMap("purple");
      System.out.println("tailMap("purple"):nt" + tailMap + "n");
   }
}

outputs:

containsKey("magenta"):
	true
 
get("yellow"):
	[255,255,0]
 
firstKey():
	black
 
lastKey():
	yellow
 
entrySet():
	[black=[0,0,0], blue=[0,0,255], cyan=[0,255,255], green=[0,255,0], 
greenblue=[46,139,87], magenta=[255,0,255], orange=[255,165,0], purple=[
238,130,238], red=[255,0,0], redorange=[255,69,0], violet=[255,69,0], wh
ite=[255,255,255], yellow=[255,255,0]]
 
keySet():
	[black, blue, cyan, green, greenblue, magenta, orange, purple, red,
 redorange, violet, white, yellow]
 
values():
	[[0,0,0], [0,0,255], [0,255,255], [0,255,0], [46,139,87], [255,0,2
55], [255,165,0], [238,130,238], [255,0,0], [255,69,0], [255,69,0], [255
,255,255], [255,255,0]]
 
headMap("purple"):
	{black=[0,0,0], blue=[0,0,255], cyan=[0,255,255], green=[0,255,0],
 greenblue=[46,139,87], magenta=[255,0,255], orange=[255,165,0]}
 
subMap("green", "redorange"):
	{green=[0,255,0], greenblue=[46,139,87], magenta=[255,0,255], ora
nge=[255,165,0], purple=[238,130,238], red=[255,0,0]}
 
tailMap("purple"):
	{purple=[238,130,238], red=[255,0,0], redorange=[255,69,0], viole
t=[255,69,0], white=[255,255,255], yellow=[255,255,0]}

Read an image resource from a Jar file

Let’s first create an JAR file containing an image. Assuming that you have a GIF file called test.gif, type on the command line:

 
jar cvf Tester.jar test.gif

This will create the file Tester.jar.

Add this jar file to your classpath:

 
set classpath=%classpath%;C:Tester.jar

(“C:” or wherever you put your jar file).

The following piece of code shows you how the classloader is used to locate the resource (in this case “test.gif”) in the search path:

 
import java.net.*;
import javax.swing.*;
 
public class Tester {
    
   public ImageIcon loadImageFromJar(String imagename) {
      ImageIcon image = null;
 
      try {
         URLClassLoader cl = (URLClassLoader) getClass().getClassLoader();
         URL url = cl.findResource(imagename);
         image = new ImageIcon(url);
      } catch (Exception e) {
         System.err.println(e);
         System.exit(1);
      }
  
      return image;
   }   
 
   public static void main(String [] args) {
      Tester tester = new Tester();
 
      ImageIcon image = tester.loadImageFromJar("test.gif");
 
      System.out.println(image);
   }
}

Using java.util.logging MemoryHandler

A MemoryHandler keeps track of a buffer of LogRecords in memory and will pass them on to another handler when a certain PushLevel is triggered. The following example creates a MemoryHandler that keeps track of maximum 5 LogRecords and writes to a ConsoleHandler when an error occurs that is equal or more “dangerous” than Level.WARNING.

Main.java:

import java.util.logging.*;
import java.io.*;

public class Main
{
   public static void main(String argv[]) {
      Logger logger = Logger.getLogger("main");
      logger.setUseParentHandlers(false);
      logger.setLevel(Level.ALL);

      ConsoleHandler ch = new ConsoleHandler();
      ch.setLevel(Level.ALL);

      MemoryHandler mh = new MemoryHandler(ch, 5, Level.WARNING);
      mh.setLevel(Level.ALL);
      logger.addHandler(mh);

      logger.info  ("log message #1");
      logger.info  ("log message #2");
      logger.config("log message #3");
      logger.fine  ("log message #4");
      logger.config("log message #5");
      logger.info  ("log message #6");
      logger.config("log message #7");
      logger.fine  ("log message #8");
      logger.severe("log message #9");
   }
}

outputs:

Jan 20, 2002 4:21:35 PM Main main
CONFIG: log message #5
Jan 20, 2002 4:21:35 PM Main main
INFO: log message #6
Jan 20, 2002 4:21:35 PM Main main
CONFIG: log message #7
Jan 20, 2002 4:21:35 PM Main main
FINE: log message #8
Jan 20, 2002 4:21:35 PM Main main
SEVERE: log message #9

Get started with the 1.4 regex package

If you have no clue about what regular expressions are, check out Introduction to Regular Expressions by Tom Sgouros.

First, define a regular expression:

   Pattern p = Pattern.compile("hol");

Then you can apply that pattern to a sequence of characters (the interface CharSequence, which String, StringBuffer and CharBuffer implement, has been added to JDK1.4.

You can then create a Matcher providing it with a CharSequence to which you want to apply your pattern:

 
   Matcher m = p.matcher("I am the great Cornholio! I am a gringo. " +
                         "(heh-heh) I have no bunghole. (heh-heh) Bungholio.");

Executing matches() returns true when the whole region matches the pattern. find() returns true when there is a subsequence of the region that matches the pattern. You can find the start and end indexes with start() and end().

For example: MatchString.java:

import java.util.regex.*;
import java.io.*;
 
public class MatchString
{
   public static void main(String []args) throws Exception {
      Pattern p = Pattern.compile("[A-Z|a-z]*hol[A-Z|a-z]*");
 
      String line = "I am the great Cornholio! I am a gringo. (heh-heh) " +
                    "I have no bunghole. (heh-heh) Bungholio.";
      Matcher m = p.matcher(line);
 
      while (m.find()) {
         System.out.print(m.group());
         System.out.println("t[" + m.start() + ", " + m.end() + "]");
      }
   }
}

outputs:

Cornholio	[15, 24]
bunghole	[61, 69]
Bungholio	[81, 90]

To test out different regular expressions (find a summary of regular-expression constructs in the Javadoc documentation of Pattern), you can use the following example. It prints out a series of matches, given an input file and a regular expression.

Main.java:

import java.util.regex.*;
import java.io.*;
 
public class Main
{
   public static void main(String []args) throws Exception {
      if (args.length != 2) {
         System.err.println("Usage: java Main filename regex");
         System.exit(1);
      }
 
      Pattern p = Pattern.compile(args[1]);
 
      BufferedReader br = new BufferedReader(new FileReader(args[0]));     
      String line = null;
      while ((line = br.readLine()) != null) {
         Matcher m = p.matcher(line);
         while (m.find()) {
            System.out.println(line);
            indent(m.start());
            System.out.print("^");
            indent(m.end()-m.start()-2);
            System.out.println("^");
         }
      } 
      br.close();
   }
 
   public static void indent(int h) {
      for (int i=0; i<h; i++) 
         System.out.print(' ');
   }
}

Example:

   c:jdk1.4binjava Main Main.java "[a-z]*fer"

outputs:

      BufferedReader br = new BufferedReader(new FileReader(args[0]));
       ^   ^
      BufferedReader br = new BufferedReader(new FileReader(args[0]));
                               ^   ^

Create my own java.util.zip checksum class

Implement the Checksum interface. This interface defines the following methods:

   long getValue();
   void reset();
   void update(byte[] b, int off, int len);
   void update(int b);

The following example creates a checksum that is based on the following algorithm:

   take remainder of (the sum of the byte values divided by 999999)

The distribution of this checksum is pretty bad, but that’s not the point :)

Main.java:

import java.util.zip.*;
import java.io.*;
 
public class Main {
   public static void main(String args[]) throws Exception {
      CheckedOutputStream cis = new CheckedOutputStream(new FileOutputStream("testfile"), 
                                                        new MyChecksum());
 
      cis.write("abcdef".getBytes());
      cis.close();
 
      System.out.println("Checksum of outputstream = " + 
                               + cis.getChecksum().getValue());
    }
}
 
class MyChecksum implements Checksum
{
   long value = 0;
 
   public long getValue() {
      return value % 999999;
   }
 
   public void update(int b) {
      value += b;
   }
 
   public void update(byte[] b, int off, int len) {
      for (int i=0; i<len; i++) {
         value += (int) b[off+i];
      }
   }
 
   public void reset() {
      value = 0;
   }
}

outputs:

597 			(since "abcdef" = 97+98+99+100+101+102 = 597)

Having the Enter key activate the default button on a JDialog

Use getRootPane() and setDefaultButton to make a button on a JDialog respond to the ‘enter’ key. I’ve included code that allows which ever button has focus to be the default.

   ... begin snippet ...
   JButton ok = new JButton("OK");
   JButton cancel = new JButton("CANCEL");
 
   //kicks off when component gains focus
   ok.addFocusListener(new buttonfocusEventHandler());
 
   //kicks off when component gains focus
   cancel.addFocusListener(new buttonfocusEventHandler()); 
 
   ... end snippet ...

   class buttonfocusEventHandler extends FocusAdapter {

      /** Checks buttons on dialog for focus
       * and makes that button the default
       * 
       * @param evt Holds event
       */
      public void focusGained(FocusEvent evt) {
 
         JButton button = (JButton) evt.getSource();
           
         if (button == ok) {
            JRootPane root = getRootPane();
            root.setDefaultButton(button);
         } //end if
            
         if (button == cancel){
            JRootPane root = getRootPane();
            root.setDefaultButton(button);
         } // end if
      }             
}  //  end buttonfocusEventHandler

Adding a JButton inside my JSplitPane divider

Main.java:

import javax.swing.plaf.basic.*;
import java.awt.event.*;
import javax.swing.*;
import java.beans.*;
import java.awt.*;
 
public class Main extends JFrame
{
   JSplitPane splitPane;
  
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
 
      splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, 
                                 new JPanel(), new JPanel());
      splitPane.setDividerSize(20);
  
      JButton button = new JButton("Exit!");
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            System.exit(0);
         }
      });
 
      setJMenuBar(getMainMenuBar());
 
      splitPane.setUI(new ButtonDividerUI(button));
 
      getContentPane().add(splitPane);
 
      addComponentListener(new ComponentAdapter() {
         public void componentShown(ComponentEvent event) {
            splitPane.setDividerLocation(0.5);  
                
            removeComponentListener(this);
         }
      });
   }
 
   public JMenuBar getMainMenuBar() {
      JMenuBar mainBar = new JMenuBar();
      JMenu menu = new JMenu("JSplitPane");
      JMenuItem item1 = new JMenuItem("HORIZONTAL_SPLIT");
      JMenuItem item2 = new JMenuItem("VERTICAL_SPLIT");
      menu.add(item1);
      menu.add(item2);
      mainBar.add(menu);
 
      item1.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            splitPane.setOrientation(JSplitPane.HORIZONTAL_SPLIT);
         }
      });
 
      item2.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
         }
      });
 
      return mainBar;
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(300, 300);
      main.setVisible(true);
   }
}
 
class ButtonDividerUI extends BasicSplitPaneUI
{
   protected JButton button;
 
   public ButtonDividerUI(JButton button) {
      this.button = button;
   }
 
   public BasicSplitPaneDivider createDefaultDivider() {
      BasicSplitPaneDivider divider = new BasicSplitPaneDivider(this) {
         public int getDividerSize() { 
            if (getOrientation() == JSplitPane.HORIZONTAL_SPLIT) {
               return button.getPreferredSize().width; 
            }
            return button.getPreferredSize().height;
         }
      };
 
      divider.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
      divider.add(button);
 
      return divider;
   }
}