Encypting/decrypting a message with the Blowfish algorithm

Blowfish is a free and strong encryption algorithm that uses a key from 32bits to 448bits.

Following code has been tested with the BouncyCastle JCE provider.

Main.java:

import java.security.*;
import javax.crypto.*;
 
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 = blowfishEncrypt(toEncrypt, "password");
 
      System.out.println("Decrypting...");
      String decrypted = blowfishDecrypt(encrypted, "password");
    
      System.out.println("Decrypted text: " + decrypted);
   } 
 
   public static byte[] blowfishEncrypt(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("Blowfish");
      kg.init(sr);
      SecretKey sk = kg.generateKey();
 
      // do the encryption with that key
      Cipher cipher = Cipher.getInstance("Blowfish");
      cipher.init(Cipher.ENCRYPT_MODE, sk);
      byte[] encrypted = cipher.doFinal(toEncrypt.getBytes());
 
      return encrypted;
   }
 
   public static String blowfishDecrypt(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("Blowfish");
      kg.init(sr);
      SecretKey sk = kg.generateKey();
 
      // do the decryption with that key
      Cipher cipher = Cipher.getInstance("Blowfish");
      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)

Creating an easter egg and hiding it from other developers

If you want to create an easter egg and make sure other developer’s that have access to the source code don’t know what’s going on, you can use the encryption and message digests functions that are available in the standard JDK.

First of all, you need a key that only you know. The key could be the sequence of steps one has to go through to see the egg. For example, clicking on the right mouse button on a component then typing giraffesarecool. So the first step is to manually compute a messagedigest from those events by capturing and concatenating them together.
Eg.

   KEY = MessageDigest(MouseEvt(right click) + KeyEvent('g') + KeyEvent('i') + ... )

KEY could be “3F4D1054FFA30B”.
Now program your class in such a way that it captures the events and compares it with the messagedigest that you have hardcoded:

   newEvent(Event e) {
      totalEvents += e;
      if (MessageDigest(totalEvents) == "3F4D1054FFA30B") {
         // invoke easter egg
      }
   }

The easter egg could be in a separate class that you have encrypted. The key for encryption should be different than the key to invoke the easter egg. If you don’t, another fellow developer could decrypt the class with the hardcoded key and see the easter egg with some minor code modifications. You can create the decryption (and encryption) key by taking a concatenation on for instance the inverse of the events:

   newEvents(Event e) {
      totalEvents += e;
      if (MessageDigest(totalEvents) == "3F4D1054FFA30B") {
         INVERSE = totalEvents.inverse();
         decrypt class (eg. stored as a JPG resource) with key INVERSE
         load class
         invoke easter egg on class
      }
   }

Another developer can only notice that something in your code is obscure but cannot figure out what the result of it is. He doesn’t know how to invoke it neither what it does.

Formatting a date using SimpleDateFormat

Use SimpleDateFormat.

Main.java:

import java.util.*;
import java.text.*;
 
public class Main
{
   public static void main(String []args) {
      SimpleDateFormat formatter = null;
 
      Date currentDate = new Date();
 
      String[] patterns = { 
         "hh:mm:ss          ",
         "MMM yyyy          ",
         "MM/yy             ",
         "h'hr' mm'min'     ",
         "SSSSS             ",
         "ww 'out of 52'    ",
         "z                 ",
         "dd/MM/yyyy - kk:mm",
      };
 
      for (int i=0; i<patterns.length; i++) {
         formatter = new SimpleDateFormat(patterns[i]);
         System.out.println(patterns[i] + "t" + formatter.format(currentDate));
      }
   }
}

outputs:

hh:mm:ss                08:26:30
MMM yyyy                Dec 2002
MM/yy                   12/02
h'hr' mm'min'           8hr 26min
SSSSS                   00755
ww 'out of 52'          51 out of 52
z                       CET
dd/MM/yyyy - kk:mm      15/12/2002 - 20:26

Comparing dates in Java

Use the compareTo method of java.util.Date.
it says that if both date are equal then it returns 0
> 0 – if one date is greater than another
< 0 - for one date is lesser than another

Main.java:

import java.util.*; 
 
public class Main {   
   public static void main(String args[]) 
   {        
      Date today=new Date();                 	 
      Date myDate=new Date(today.getYear(),today.getMonth()-1,today.getDay());
      System.out.println("My Date is"+myDate);    
      System.out.println("Today Date is"+today);
      if(today.compareTo(myDate)<0)
         System.out.println("Today Date is Lesser than my Date");
      else if(today.compareTo(myDate)>0)
         System.out.println("Today Date is Greater than my date"); 
      else
         System.out.println("Both Dates are equal");      
  }
}

Getting the language of the current locale in Java

Main.java:

import java.util.*;
 
public class Main {
   public static void main(String []args) {
      // for default locale 
      Locale locale = Locale.getDefault();
      System.out.println(locale);  
      System.out.println("Language          " + locale.getLanguage());
      System.out.println("DisplayLanguage   " + locale.getDisplayLanguage());
 
      // for specific locale
      locale = new Locale("nl", "BE");
      System.out.println(locale);  
      System.out.println("Language          " + locale.getLanguage());
      System.out.println("DisplayLanguage   " + locale.getDisplayLanguage());
   }
}

outputs:

en_US
Language          en
DisplayLanguage   English
nl_BE
Language          nl
DisplayLanguage   Dutch

Adding a listener to a preferences tree

You can implement the NodeChangeListener to listen for events when nodes are added or removed and implement the PreferenceChangeListener to listen for events that are emitted when the value of the preference changes. You need to add a listener to that particular node in which you are interested.

The first example I wrote involved 2 VMs. The first app showed a Swing gui and listened to preference change events, while the other app changed the preferences. Events were not received by the first app. It turns out that event notification is only guaranteed for changes made in the same VM.

This example starts up, writes a couple preferences, fires up a thread that changes these preferences after 5 seconds. You should see the changes in the GUI.

com/esus/examples/preferences/Main.java:

package com.esus.examples.preferences;

import javax.swing.border.*;
import java.util.prefs.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame 
{
   Preferences preferences;
 
   public static final String APPLICATIONPATH = "applicationpath";
   public static final String USERFONT        = "userfont";
   public static final String LASTUSERLOGIN   = "lastuserlogin";
   public static final String LDAPURL         = "ldapurl";
 
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
 
      loadPreferences();
 
      JLabel appPathLabel       = new JLabel("Application Path:");
      JLabel userFontLabel      = new JLabel("User font:");
      JLabel lastUserLoginLabel = new JLabel("Last user logged in: ");
      JLabel ldapURLLabel       = new JLabel("LDAP url:");
      final JTextField appPathTf       = new JTextField(
                                  preferences.get(APPLICATIONPATH, ""));
      final JTextField userFontTf      = new JTextField(
                                  preferences.get(USERFONT, ""));
      final JTextField lastUserLoginTf = new JTextField(
                                  preferences.get(LASTUSERLOGIN, ""));
      final JTextField ldapURLTf       = new JTextField(
                                  preferences.get(LDAPURL, ""));
 
      JPanel prefsPanel = new JPanel();
      prefsPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
      prefsPanel.setLayout(new GridLayout(4, 4, 10, 10));
      prefsPanel.add(appPathLabel);
      prefsPanel.add(appPathTf);
      prefsPanel.add(userFontLabel);
      prefsPanel.add(userFontTf);
      prefsPanel.add(lastUserLoginLabel);
      prefsPanel.add(lastUserLoginTf);
      prefsPanel.add(ldapURLLabel);
      prefsPanel.add(ldapURLTf);
 
      JPanel buttonPanel = new JPanel();
      buttonPanel.setLayout(new GridLayout(1, 2, 70, 70));
 
      JButton cancelButton = new JButton("Cancel");
      cancelButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            System.exit(0);
         }
      });
 
      JButton saveButton = new JButton("Save");
      saveButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            preferences.put(APPLICATIONPATH, appPathTf.getText());
            preferences.put(USERFONT,        userFontTf.getText());
            preferences.put(LASTUSERLOGIN,   lastUserLoginTf.getText());
            preferences.put(LDAPURL,         ldapURLTf.getText());
            System.out.println("Preferences saved!");
         }
      });

      // listen for changes to my preferences
      preferences.addPreferenceChangeListener(new PreferenceChangeListener() {
         public void preferenceChange(PreferenceChangeEvent pce) {
            String key = pce.getKey();
            String value = pce.getNewValue();
            if (key.equals(APPLICATIONPATH))    appPathTf.setText(value);
            else if (key.equals(USERFONT))      userFontTf.setText(value);
            else if (key.equals(LASTUSERLOGIN)) lastUserLoginTf.setText(value);
            else if (key.equals(LDAPURL))       ldapURLTf.setText(value);
         }
      });
  
      buttonPanel.add(cancelButton);
      buttonPanel.add(saveButton);
 
      getContentPane().setLayout(new BorderLayout());
      getContentPane().add(BorderLayout.CENTER, prefsPanel);
      getContentPane().add(BorderLayout.SOUTH, buttonPanel);
   }
 
   public void loadPreferences() {
      preferences = Preferences.userNodeForPackage(this.getClass());
 
      // put in some default values
      preferences.put(APPLICATIONPATH, "c:\application");
      preferences.put(USERFONT,        "Courier New");
      preferences.put(LASTUSERLOGIN,   "Joris Van den Bogaert");
      preferences.put(LDAPURL,         "ldap://localhost:389");
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(350, 190);
      main.setVisible(true);
 
      main.new ChangePreference().start();
   }
 
   class ChangePreference extends Thread {
      public void run() {
         try {
            Thread.sleep(5000);
         }
         catch(InterruptedException e) { }
 
         preferences.put(APPLICATIONPATH, "/home/me/test");
         preferences.put(USERFONT,        "Arial");
         preferences.put(LASTUSERLOGIN,   "Alicia Kolesnikova");
         preferences.put(LDAPURL,         "ldap://111.222.333.444:389");
      }
   }
}

Using a ListResourceBundle

A ListResourceBundle is one where you centralize all your locale-specific strings and objects in a class. Provide your own versions by extending the abstract class ListResourceBundle and implementing the method getContents that returns an 2d array containing key/values pairs.

Keep in mind that:

  • keys are case-sensitive

  • a value doesn’t need to be a String, it may be an array or any type of object
  • you should put the resourcebundle in separate files and declare the class public

    To instantiate one of your resourcebundles, determine a locale (or use the default one) and call ResourceBundle.getResourceBundle(name of family class, locale). This method will look up the class using a certain lookup mechanism that goes from specific to general, in terms of locale information. For example, if the default locale is “en_US” and your specify “nl_BE”, the lookup will search for the following classes (assuming just MyResources.class exists):

       MyResources_nl_BE
       MyResources_nl
       MyResources_en_US
       MyResources_en
       MyResources
    

    If the lookup doesn’t find the class, it will throw a MissingResourceException.

    Once you have an instance of ResourceBundle, you can look up its contents using the three methods getString, getStringArray and getObject. If you want another type of array, for example an int[][], just use getObject and cast the result to int[][].

    Main.java:

    import java.util.*;
     
    public class Main {
       public static void main(String []args) {
          // use default locale 
          printLabelValues("LabelResourceBundle");
     
          // use locale en/../..
          Locale.setDefault(new Locale("en", "", ""));	
          printLabelValues("LabelResourceBundle");
     
          // use locale nl/BE/Unix
          Locale.setDefault(new Locale("nl", "BE", "Unix"));
          printLabelValues("LabelResourceBundle");
        
          // use locale nl					// MissingResourceException!
          Locale.setDefault(new Locale("nl", "", ""));	
          printLabelValues("LabelResourceBundle");
     
          // use locale ../BE/..				// MissingResourceException!
          Locale.setDefault(new Locale("", "BE", ""));
          printLabelValues("LabelResourceBundle");
     
          // use locale ../../.. 				// MissingResourceException!
          Locale.setDefault(new Locale("", "", ""));
          printLabelValues("LabelResourceBundle");
       }
     
       public static void printLabelValues(String resourceName) {
          ResourceBundle rb = ResourceBundle.getBundle(resourceName);  
     
          System.out.println("For locale: " + Locale.getDefault());
          System.out.println("tContents for LBL_NAME: " + rb.getString("LBL_NAME"));
          System.out.print("tContents for LBL_NUMBERS: ");
          String array[] = rb.getStringArray("LBL_NUMBERS");
          for (int i=0; i<array.length; i++) 
             System.out.print(array[i] + " ");
          System.out.println();
          System.out.println("tContents for LBL_OBJECT: of " + 
                                              rb.getObject("LBL_OBJECT").getClass());
       }
    }
    

    LabelResourceBundle_nl_BE.java:

    import java.util.*;
     
    public class LabelResourceBundle_nl_BE extends ListResourceBundle
    {
       private Object[][] contents = 
          { { "LBL_NAME", 		"Naam:" },
            { "LBL_NUMBERS",	new String[] { "een", "twee", "drie" }},
            { "LBL_OBJECT", 	new Integer(10) } };
      
       public Object[][] getContents() {
          return contents;
       }
    }
    

    LabelResourceBundle_fr_BE.java:

    import java.util.*;
     
    public class LabelResourceBundle_fr_BE extends ListResourceBundle
    {
       private Object[][] contents = 
          { { "LBL_NAME", 		"Nom:" },
            { "LBL_NUMBERS",	new String[] { "un", "deux", "troi" }},
            { "LBL_OBJECT", 	new Long(100) } };
     
       public Object[][] getContents() {
          return contents;
       }
    }
    

    LabelResourceBundle_en.java:

    import java.util.*;
     
    public class LabelResourceBundle_en extends ListResourceBundle
    {
       private Object[][] contents = 
          { { "LBL_NAME", 		"Name:" },
            { "LBL_NUMBERS",	new String[] { "one", "two", "three" }},
            { "LBL_OBJECT", 	new Double(1000.1) } };
     
       public Object[][] getContents() {
          return contents;
       }
    }
    

    Output after running Main:

    For locale: en_US
            Contents for LBL_NAME: Name:
            Contents for LBL_NUMBERS: one two three
            Contents for LBL_OBJECT: of class java.lang.Double
    For locale: en
            Contents for LBL_NAME: Name:
            Contents for LBL_NUMBERS: one two three
            Contents for LBL_OBJECT: of class java.lang.Double
    For locale: nl_BE_UNIX
            Contents for LBL_NAME: Naam:
            Contents for LBL_NUMBERS: een twee drie
            Contents for LBL_OBJECT: of class java.lang.Integer
    Exception in thread "main" java.util.MissingResourceException: Can't find resource
    for base name LabelResourceBundle, locale nl
            at java.util.ResourceBundle.getBundle(ResourceBundle.java:423)
            at java.util.ResourceBundle.getBundle(ResourceBundle.java:339)
            at Main.printLabelValues(Main.java, Compiled Code)
            at Main.main(Main.java:18)
    

  • Examples of Swing borders

    You can combine these borders with CompoundBorder.

    Main.java:

    import javax.swing.border.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
     
    public class Main extends JFrame
    {
       public Main() {
          getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
     
          JLabel labels[] = new JLabel[6];
          labels[0] = new JLabel("Label with EmptyBorder, margin 20");
          labels[0].setBorder(new EmptyBorder(20, 20, 20, 20));
          labels[1] = new JLabel("Label with LineBorder, red color, thickness 3");
          labels[1].setBorder(new LineBorder(Color.red, 3));
          labels[2] = new JLabel("Label with LOWERED BevelBorder");
          labels[2].setBorder(new BevelBorder(BevelBorder.LOWERED));
          labels[3] = new JLabel("Label with RAISED EtchedBorder");
          labels[3].setBorder(new EtchedBorder(EtchedBorder.RAISED));
          labels[4] = new JLabel("Label with MatteBorder and Icon");
          labels[4].setBorder(new MatteBorder(new ImageIcon("c:\female.gif")));
          labels[5] = new JLabel("Label with BevelBorder TitledBorder");
          labels[5].setBorder(new TitledBorder(new BevelBorder(BevelBorder.LOWERED), "Title"));
     
          for (int i=0; i<labels.length; i++) {
             labels[i].setOpaque(true);
             getContentPane().add(labels[i]);
          }
          
          addWindowListener(new WindowAdapter() {
             public void windowClosing(WindowEvent we) {
                System.exit(0);
             }
          });
       }
     
       public static void main(String [] args) {
          Main main = new Main();
          main.setSize(300, 400);
          main.setVisible(true);
       } 
    } 
    

    Setting the top-left icon in a JFrame

    setIconImage (inherited method from java.awt.Frame) does the job!

     
    import javax.swing.*;
    import java.awt.*;
       
    public class IconFrame extends JFrame {
     
       public IconFrame() {
          setSize(100, 100);
    
          setIconImage(new ImageIcon("test.gif").getImage());
       }
     
       public static void main(String args[]) {
          new IconFrame().setVisible(true);     
       }
    }