Month: October 2012

Java: Bytes, Hex and Serialization

Posted on

This is again another short Java development post. Here I show some convenient functions for use with byte arrays in Java.

Byte Array to Hex String

Converting byte arrays into a textual format comes in handy in many scenarios. For one instance when you need to store a cryptographic key on disk in a textual format you can choose to encode into Base64 (which will increase the size by 33%) or convert each byte to a textual hex representation. I personally found this handy when dealing with the Apache Derby embedded database, I had to feed it the cryptographic key as a hex string. Other uses I found was for debugging and when comparing objects together. Below is the function that takes a byte array as a parameter and returns its representation as a Hex String.

private static final char[] HEX_CHARS = {
	'0', '1', '2' ,'3', '4', '5', '6', '7', '8', '9',
	'a', 'b', 'c', 'd', 'e', 'f'
};

public String toHexString(byte[] bytes)
{
	StringBuilder sb = new StringBuilder();
	for(int i = 0; i < bytes.length; i++) {
		byte b = bytes[i];
		sb.append(new char[] {HEX_CHARS[(b >> 4) & 0x0f], HEX_CHARS[b & 0x0f]});
	}
	
	return sb.toString();
}

Object Serialization To and From Bytes

This has always been a common milestone for many developers when they start developing some serious applications. We tend to use Objects a lot due to the OO nature of Java (which is not a bad thing), so we need to be able to send these objects off as bytes to somewhere (I/O Streams, disk …etc) Below is the standard implementation of serializing and deserializing objects to bytes and back again.

public byte[] serializeObject(Object obj) throws IOException
{
	ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
	ObjectOutputStream oos = new ObjectOutputStream(bytesOut);
    	oos.writeObject(obj);
    	oos.flush();
    	byte[] bytes = bytesOut.toByteArray();
    	bytesOut.close();
    	oos.close();
    	return bytes;
}


public Object deserializeBytes(byte[] bytes) throws IOException, ClassNotFoundException
{
	ByteArrayInputStream bytesIn = new ByteArrayInputStream(bytes);
    	ObjectInputStream ois = new ObjectInputStream(bytesIn);
    	Object obj = ois.readObject();
	bytesIn.close();
    	ois.close();
    	return obj;
}

Password Validation Practices

Posted on

It is usually quite rare for me to stumble upon some really bad code, but to stumble upon some really stupid code… well that happens almost everyday!

So while auditing someone else’s source code at work I found something very odd in the utility that validates passwords against our policy. We have a standard password policy that only allows passwords to be at least 8 characters in length, 1 upper case, 1 lower case, 1 digit or 1 special character and no spaces. The code that is used to validate this policy is what really blew my mind. I mean, it’s not that it does not work, it does. It’s that I could not comprehend how the code was brought to life by a "senior" developer with a university degree in computer engineering.

The source code is in Java so there are many options to use like regular expressions. So the the function to validate a password against the password policy would look something like this:

/**
 * <p>Standard Password Policy
 * <ul>
 * 	<li>Minimum 8 characters</li>
 * 	<li>At least 1 upper case character</li>
 * 	<li>At least 1 lower case character</li>
 * 	<li>At least 1 digit or 1 special character</li>
 * 	<li>No spaces allowed</li>
 * 	<li>List of special characters allowed are (!@#$%^&+=.,_)</li>
 * </ul>
 * </p>
 */
private static final String PASSWORD_REGEX = "^(?=.*[a-z])(?=.*[A-Z])((?=.*[!@#$%^&+=.,_])|(?=.*[0-9]))(?=[^ ]+$).{8,}$";
private static final Pattern passPattern = Pattern.compile(PASSWORD_REGEX);
	
private boolean validatePasswordRegex(String password)
{
	return passPattern.matcher(password).matches();
}

It’s lean, clean and simple. Then I started to think that what if someone did not know anything about regular expressions (which if they did not they should have found out about by googling "password validation") So I felt compelled to re-write a function that validates the password without using regular expressions:

private boolean validatePasswordFast(String password)
{
	boolean hasUpper = false;
	boolean hasLower = false;
	boolean hasSpecial = false;
	boolean hasDigit = false;
	boolean valid = false;
		
	if(password.length() > 7) {
		char[] cPassword = password.toCharArray();
		for(int i = 0; i < cPassword.length; i++) {
			int c = cPassword[i];
				
			if(c == 32) {
				valid = false;
				break;
			}
				
			if(!hasUpper) {
				if(c >= 65 && c <= 90) {
					hasUpper = true;
				}
			}
				
			if(!hasLower) {
				if(c >= 97 && c <= 122) {
					hasLower = true;
				}
			}
				
			if(!hasDigit) {
				if(c >= 48 && c <= 57) {
					hasDigit = true;
				}
			}
				
			if(!hasSpecial) {
				switch(c)
				{
					case 33:
					case 35:
					case 36:
					case 37:
					case 38:
					case 43:
					case 44:
					case 46:
					case 61:
					case 94:
					case 95:
					{
						hasSpecial = true;
						break;
					}
				}
			}
				
			if(hasUpper && hasLower && (hasSpecial || hasDigit)) {
				valid = true;
				break;
			}
		}
	}
	
	return valid;
}

The above is relatively longer than the regular expression function. Knowing that each character in a String has an ordinal number and knowing of the ASCII table it was intuitive on how apply the password policy. Also I tried to make it as efficient as possible so that there are no wasted iterations.

But, dear readers, what I found was worse. I saw something so wasteful and so … "un-computer science like" that it baffled me:

private boolean validatePasswordNotSmart(String password)
{
	boolean passwdLength =true;
	boolean passwdSpace = true;
	boolean passwdSpecialChar = false;
	boolean passwdLowerCase = false;
	boolean passwdUpperCase = false;
	boolean passwdDigit = false;
		
	if(password == null || password.length() == 0) {
		return false;
	}
		
	if(password.length() < 8) {
		passwdLength = false;
	}
			
	for(int i = 0; i < password.length(); i++) {
		if (password.contains(" ")) {
			passwdSpace = false;
			break;
		}
			
		if(password.contains("$")
		   || password.contains("+")
		   || password.contains("=")
		   || password.contains("!")
		   || password.contains("#")
		   || password.contains("%")
		   || password.contains("&")
		   || password.contains("^")
		   || password.contains("@")
		   || password.contains(".")
		   || password.contains(",")
		   || password.contains("_")) {
			passwdSpecialChar = true;
		}
			
		if(password.contains("a")
		   || password.contains("b")
		   || password.contains("c")
		   || password.contains("d")
		   || password.contains("e")
		   || password.contains("f")
		   || password.contains("g")
		   || password.contains("h")
		   || password.contains("i")
		   || password.contains("j")
		   || password.contains("k")
		   || password.contains("l")
		   || password.contains("m")
		   || password.contains("n")
		   || password.contains("o")
		   || password.contains("p")
		   || password.contains("q")
		   || password.contains("r")
		   || password.contains("s")
		   || password.contains("t")
		   || password.contains("u")
		   || password.contains("v")
		   || password.contains("w")
		   || password.contains("x")
		   || password.contains("y")
		   || password.contains("z")) {
			passwdLowerCase = true;
		}
			
		if(password.contains("A")
		   || password.contains("B")
		   || password.contains("C")
		   || password.contains("D")
		   || password.contains("E")
		   || password.contains("F")
		   || password.contains("G")
		   || password.contains("H")
		   || password.contains("I")
		   || password.contains("J")
		   || password.contains("K")
		   || password.contains("L")
		   || password.contains("M")
		   || password.contains("N")
		   || password.contains("O")
		   || password.contains("P")
		   || password.contains("Q")
		   || password.contains("R")
		   || password.contains("S")
		   || password.contains("T")
		   || password.contains("U")
		   || password.contains("V")
		   || password.contains("W")
		   || password.contains("X")
		   || password.contains("Y")
		   || password.contains("Z")) {
			passwdUpperCase = true;
		}
			
		if(password.contains("0")
		   || password.contains("1")
		   || password.contains("2")
		   || password.contains("3")
		   || password.contains("4")
		   || password.contains("5")
		   || password.contains("6")
		   || password.contains("7")
		   || password.contains("8")
		   || password.contains("9")) {
			passwdDigit = true;
		}
	}

	return passwdLength && passwdSpace && (passwdSpecialChar || passwdDigit) && passwdLowerCase && passwdUpperCase;
}

How does one go through all the trouble to write that function and roll it out into production believing that what they did was good? The problems with this are that

  • Long to write
  • Uses many internal methods that affect performance
  • Shows the lack of research into the topic
  • Waste of time

I even tried bench-marking the three functions to see which was fastest:

Password to benchmark: ThisIs_A_validPassword123!
Iterations: 500,000
Validate Password Not Smart: 5491 ms
Validate Password Fast: 63 ms
Validate Password Regex: 2340 ms

Go for another round...

Password to benchmark: ThisIs_A_validPassword123!
Iterations: 500,000
Validate Password Not Smart: 5461 ms
Validate Password Fast: 48 ms
Validate Password Regex: 2356 ms

The non-regex but fast function triumphed at less than 100ms to validate a password 500,000 times. Second place was the regex function averaging at 2,300ms and last place was the not smart function which took a whopping 5,400ms.

The advantages of the regex function is that it is short to write and easy to read, but you have to have intermediate knowledge of regular expressions. The fast function is fast, but it’s a bit long and you have to scan the code a bit to figure out what it is doing. Not to leave anything out, the not smart function is the easiest to read, but sadly causing you to come to the conclusion that this is the wrong way to code it.

Java: Hashcode Generation

Posted on

Creating your own Java classes you sometimes need to implement your own equals() method. When doing so you are highly encouraged by the Java compiler to also override and implement your own hashcode() function. A lot of the times we’re left wondering what to do and most of the times I see people just call super.hashcode() which is OK if you are not going to be using Hashtables in your program.

Yes, usually hashtables use your class’s hashcode for various purposes and most of the times if you have an issue with a hashtable you should check to see if you are implementing hashcode properly. According to Oracle Java API the hashcode function must follow the rules below:

Read the rest of this entry »

Java: Frame Tricks

Posted on

These are rather tiny and mundane JFrame tricks, but nice to have in your bag of useful Swing tools when coding. These methods help center a window on screen, maximize, minimize and restore a window. Simple yet powerful.

public void center(Window w) {
	int screenWidth  = Toolkit.getDefaultToolkit().getScreenSize().width;
	int screenHeight = Toolkit.getDefaultToolkit().getScreenSize().height;

	int windowWidth = w.getWidth();
	int windowHeight = w.getHeight();

	if (windowHeight > screenHeight) {
		return;
	}

	if (windowWidth > screenWidth) {
		return;
	}

	int x = (screenWidth - windowWidth) / 2;
	int y = (screenHeight - windowHeight) / 2;

	w.setLocation(x, y);
}

public void maximizeFrame(Frame frame) {
	frame.setExtendedState(Frame.MAXIMIZED_BOTH);
}

public void iconifyFrame(Frame frame) {
	frame.setExtendedState(Frame.ICONIFIED);
}

public void restoreFrame(Frame frame) {
	frame.setExtendedState(Frame.NORMAL);
}

public int getScreenHeight() {
	return Toolkit.getDefaultToolkit().getScreenSize().height;
}

public int getScreenWidth() {
	return Toolkit.getDefaultToolkit().getScreenSize().width;
}

Java: Custom Confirm Dialog and Splash Screen

Posted on

Java’s swing components library is loaded with many useful base components, especially when you need to create something quick. Although there usually comes a time when you want to do something so simple and yet it has to be complex to do so. This is a negative point on Java’s side in my expert opinion.

All I wanted to do was to create a JOptionPane with a specified width and height, that’s it. Nothing more and nothing less. I know that JOptionPane takes the preferred size of its sub-components, but I don’t want it to. I may have a component that is very big (like a text area or something similar) and I want to show it with scroll bars (no way!!) inside the JOptionPane and I do not want the JOptionPane to take up a quarter of the screen. So to do so I needed a good look at the Java 1.6.x source code for JOptionPane, Cocacola and some Acetaminophen or Paracetamol (for European readers.) The result was the code below all with complete Javadoc.

/**
 * <p>This is a wrapped method taken from the Java 1.6.x source code and modified to suite my
 * needs of a JOptionPane type functionality with the ability to specify dialog size instead
 * of it taking preferred sizes of components.</p>
 * <hr/>
 * 
 * <p>Brings up a dialog with a specified icon, where the initial choice is determined by the
 * <code>initialValue</code> parameter and the number of choices is determined by the
 * <code>optionType</code> parameter.</p>
 * 
 * <p>If <code>optionType</code> is <code>YES_NO_OPTION</code>, or
 * <code>YES_NO_CANCEL_OPTION</code> and the <code>options</code> parameter is
 * <code>null</code>, then the options are supplied by the look and feel.</p>
 * 
 * <p>The <code>messageType</code> parameter is primarily used to supply a default icon from
 * the look and feel.</p>
 * 
 * @param parentComponent
 *                determines the <code>Frame</code> in which the dialog is displayed; if
 *                <code>null</code>, or if the <code>parentComponent</code> has no
 *                <code>Frame</code>, a default <code>Frame</code> is used
 * @param message
 *                the <code>Object</code> to display
 * @param title
 *                the title string for the dialog
 * @param optionType
 *                an integer designating the options available on the dialog:
 *                <code>DEFAULT_OPTION</code>, <code>YES_NO_OPTION</code>,
 *                <code>YES_NO_CANCEL_OPTION</code>, or <code>OK_CANCEL_OPTION</code>
 * @param messageType
 *                an integer designating the kind of message this is, primarily used to
 *                determine the icon from the pluggable Look and Feel:
 *                <code>ERROR_MESSAGE</code>, <code>INFORMATION_MESSAGE</code>,
 *                <code>WARNING_MESSAGE</code>, <code>QUESTION_MESSAGE</code>, or
 *                <code>PLAIN_MESSAGE</code>
 * 
 * @return an integer indicating the option chosen by the user, or
 *         <code>CLOSED_OPTION</code> if the user closed the dialog
 * @exception HeadlessException
 *                    if <code>GraphicsEnvironment.isHeadless</code> returns
 *                    <code>true</code>
 * @see java.awt.GraphicsEnvironment#isHeadless
 */
public static int showConfirmDialog(Component parentComponent, Object message, String title, int optionType, int messageType, int width, int height) throws HeadlessException
{
	JOptionPane pane = new JOptionPane(message, messageType, optionType, null, null, null);
	pane.setInitialValue(null);
	if(parentComponent == null) {
		pane.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
	}
	else {
		pane.setComponentOrientation(parentComponent.getComponentOrientation());
	}

	JDialog dialog = pane.createDialog(parentComponent, title);
	dialog.setSize(width, height);
	dialog.setResizable(true);
	dialog.setVisible(true);
	dialog.dispose();

	Object selectedValue = pane.getValue();

	if(selectedValue == null) {
		return JOptionPane.CLOSED_OPTION;
	}
	else  if(selectedValue instanceof Integer) {
		return ((Integer) selectedValue).intValue();
	}
	else {
		return JOptionPane.CLOSED_OPTION;
	}
}

The next swing component I wish was made was a JSplashScreen. We see it all the time when we run applications and we always do everything we can to disable it after running the program more than once. And damn it, I want users to do the same with my applications 😀 With some more time and more Cocacola a component was created. Check it out below and hope it might be useful.

/**
 * <p>Displays a splash window with a message and for a specific amount of time.
 * The window size can be specified. Note that using this method implies some
 * default parameters such as using Sans Serif font, Bold, size 32.</p>
 * 
 * @see #showSplashWindow(String, Font, int, Dimension, Window)
 * @param message
 * 	- the text to display
 * @param duration
 * 	- how long to show the window
 * @param windowSize
 * 	- the size of the window
 */
public static void showSplashWindow(String message, int duration, Dimension windowSize) {
	showSplashWindow(message, new Font(Font.SANS_SERIF, Font.BOLD, 32), duration, windowSize, null);
}

/**
 * <p>Displays a splash window for a specific amount of time with a set of rendering parameters
 * for the message, font type, window size and frame owner.</p>
 * 
 * @param message
 * 	- the text to display
 * @param messageFont
 * 	- the font of text
 * @param duration
 * 	- how long to show the window
 * @param windowSize
 * 	- the size of the window
 * @param frameOwner
 * 	- the parent window or owner, null if none
 */
public static void showSplashWindow(String message, Font messageFont, int duration, Dimension windowSize, Window frameOwner) {
	JLabel saved = new JLabel(message);
	saved.setHorizontalAlignment(JLabel.CENTER);
	saved.setOpaque(true);
	saved.setFont(messageFont);

	final JWindow window = new JWindow(frameOwner);
	window.add(saved, BorderLayout.CENTER);
	window.setSize(windowSize);
	saved.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
	UITool.center(window);
	window.setVisible(true);

	Timer timer = new Timer(duration, new ActionListener() {
		@Override
		public void actionPerformed(ActionEvent e) {
			window.setVisible(false);
			window.dispose();
		}
	});

	timer.setRepeats(false);
	timer.start();
}

Burp Suite Plugin Supports GWT Security Scanning

Posted on Updated on

Previously I have discussed how Web Application Scanners such as Acunetix and Qualys do not provide any support for scanning (or even crawling) GWT (Google Web Toolkit) web applications. This led me to search for a vulnerability scanner that could; and up until now I found something that might be able to do the job!

PortSwigger Web Security’s Burp Suite seems to be the best candidate for performing vulnerability scans on GWT built web applications. The Burp Suite seems to have just recently added full JSON request parsing in June 28, 2012. This coupled with a GWT scanning plugin developed by alla from Germwell.com adds GWT scanning support to the Burp Suite!

Read the rest of this entry »

Java: Database Helper Routines

Posted on Updated on

Any programmer who deals with a JDBC driver for accessing a database knows that there are many tedious tasks to perform time and time again. There are 3 such tasks that I would like to highlight:

  • CLOB to String Conversion
  • Processing Batch Return Results
  • Escaping SQL Strings

Of course there are many other tedious tasks than those, but these are the ones that can at least be generic enough to fit in a library of useful tools. Others which include stuff like commitment control, managing save points, building statements efficiently …etc tend to be more specific to the programmer / project. So I’ll focus on the 3 mentioned above and provide the source code to them.

CLOB to String Conversion
Quite simple and an ideal candidate for code reuse. Can be modified to add any extra set of requirements needed such as handling charsets or internationalization.

public String convertClobToString(Clob clob) throws IOException, SQLException
{
	Reader reader = clob.getCharacterStream();
	int c = -1;
	StringBuilder sb = new StringBuilder();
	while((c = reader.read()) != -1) {
		sb.append(((char)c));
	}
	
	reader.close();
	return sb.toString();
}

Read the rest of this entry »