Development

PGP Cryptography With The Legion of the Bouncy Castle – Part 2

Posted on Updated on

In part 1 I went over PGP Key pair generation, DSA/El Gamal key pairs to be exact, and how we can generate them using the Legion of the Bouncy Castle cryptography API. These key pairs can be imported directly into PGP for use or used programmatically via the Bouncy Castle API.

OK, so now that we know how to generate our PGP key pair we now will learn how to digitally sign and verify files. Signing files allows our recipient to verify the authenticity of the origin of the file we send them. It also verifies the integrity of the file as well.

Signing a file

  • PGP Private Key of sender
  • Private Key Passphrase

Verifying a file

  • Public Key of sender

To make a developers life easier I’ve decided to create a static class called PGPCryptoTools which include the sign and verify methods. One just has to send the appropriate parameters (as shown in the bullet points above) to sign and verify files.

Read the rest of this entry »

Advertisements

PGP Cryptography With The Legion of the Bouncy Castle – Part 1

Posted on Updated on

Some of my favorite things to do in software engineering is use libraries with cool names. Nothing beats The Legion of the Bouncy Castle. I like that name so much that I decided to just start using it! Well actually I really needed to use PGP cryptography in one of my projects and though it would be nice to blog about it, but yeah cool name though.

So one of the tricky issues with using Bouncy Castle (we seriously do it a disservice by shortening its amazing name to just 2 words) is the lack of proper, complete and friendly documentation. You may find many articles on the net or tutorials, but I found them way too complex and some just didn’t know what they were doing.

The best option was to look at the Bouncy Castle source code and go directly to their examples package. There they give some pretty good examples and enough to build your own tools for their API. In this part of my series I will go over generating a full fledged DSA/El Gamal PGP Key Ring that is importable into PGP.

Read the rest of this entry »

Android: Setting Max Length Text Field

Posted on

I have just started getting into Android programming and it is becoming quite fun. I feel the power of the XML GUI editor, but it can be quite annoying. My first “wtf” moment was when I was creating text fields (known as EditText) in the XML. I wanted to limit the number of characters the user enters and easy enough it was simple to do.

Below is the XML for creating a text username login text field limited to 30 characters. The property that limits it is android:maxLength

<EditText
        android:id="@+id/login_username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="@string/login_username"
        android:gravity="center"
        android:maxLength="30" >
      <requestFocus />
</EditText>

So this is great! And whats even better is that because I’m coding in Eclipse I can utilize the auto-complete feature (CTRL+SPACE) to see all possible properties allowed. OK so now I need to create another text field but this time programatically. Not because I wanna make my life difficult but because the program I was doing needed it.

So I create the EditText object and all that and then I am able to apply all the other properties except for android:maxLength. Why? Don’t ask me really. I don’t know if it is bad design or there was some really good reason to do so. You have to create a filter, fair enough….. no not really. Sorry, instead of having a developer friendly method like addFilter() they give us this setFilters() which takes an array of filters. This is annoying.

LinearLayout linearLayout = new LinearLayout(this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 10);

//Get my text to display on it from the strings.xml file
String displayText = getApplicationContext().getResources().getString(R.string.login_displayText);

//Create the array of filters and add my length filter to it	
InputFilter[] myTextFilterArray = new InputFilter[1];
myTextFilterArray[0] = new InputFilter.LengthFilter(5);
			
EditText myEditText = new EditText(this);
myEditText.setText(displayText);
myEditText.setLayoutParams(lp);
myEditText.setGravity(Gravity.CENTER_HORIZONTAL);
myEditText.setEms(10);
myEditText.setFilters(otpFilterArray);

//Add it to the layout			
linearLayout.addView(myEditText);

When you just want to add 1 filter you are going to be forced to create an array and and set its length and add your filter. This is tedious at best and it causes you to waste some time. Not only that it is a bit counter intuitive. Being a Java programmer we are used to the conventions of having add(), remove() and set() methods. If you can add multiple filters to an object then you should implement add() and remove() at least.

Java: Auto Adjust JTable Columns

Posted on

Perhaps the most common task to be done by a programmer after creating a JTable is to figure out how to adjust the columns to make it look good. I can not remember how many times I have created applications with many JTables and then came to the point where I needed to adjust the columns. At times you may also want to hide certain columns. This stuff comes out of the box with applications like Excel.

After extensive research and testing code (this was years ago by the way) I have come up with some nice code to adjust the columns of a JTable in a reusable way. Just call the method adjustTableColumns() and give it some parameters. See the code below to see how it works and what parameters to send.

public void adjustTableColumns(JTable table) {
	for(int i=0; i < table.getColumnCount(); i++) {
		adjustColumn(i, 5, table);
	}
}
	
public void adjustTableColumns(JTable table, int ... hiddenColumns) {
	for(int i=0; i < table.getColumnCount(); i++) {
                adjustColumn(i, 5, table, hiddenColumns);
        }
}
	
private void adjustColumn(int columnIndex, int margin, JTable table) {
	int width = 0;
	DefaultTableColumnModel colModel = (DefaultTableColumnModel)table.getColumnModel();
	TableColumn column = colModel.getColumn(columnIndex);

	TableCellRenderer renderer = column.getHeaderRenderer();
	if(renderer == null) {
		renderer = table.getTableHeader().getDefaultRenderer();
	}

	Component component = renderer.getTableCellRendererComponent(table, column.getHeaderValue(), false, false, 0, 0);
	width = component.getPreferredSize().width;

	for(int i=1; i < table.getRowCount(); i++) {
		renderer = table.getCellRenderer(i, columnIndex);
		component = renderer.getTableCellRendererComponent(table, table.getValueAt(i, columnIndex), false, false, i, columnIndex);
		width = Math.max(width, component.getPreferredSize().width);
	}

	width += 2*margin;
	column.setPreferredWidth(width);
}

private void adjustColumn(int columnIndex, int margin, JTable table, int ... hiddenColumns) {
	int width = 0;
	DefaultTableColumnModel colModel = (DefaultTableColumnModel)table.getColumnModel();
	TableColumn column = colModel.getColumn(columnIndex);

	for(int j = 0; j < hiddenColumns.length; j++) {
		if(hiddenColumns[j] == columnIndex) {
			column.setMaxWidth(0);
			column.setMinWidth(0);
			column.setPreferredWidth(0);
			column.setResizable(false);
		}
		else {
			TableCellRenderer renderer = column.getHeaderRenderer();
			if(renderer == null) {
				renderer = table.getTableHeader().getDefaultRenderer();
			}

			Component component = renderer.getTableCellRendererComponent(table, column.getHeaderValue(), false, false, 0, 0);
			width = component.getPreferredSize().width;

			for(int i=1; i < table.getRowCount(); i++) {
				renderer = table.getCellRenderer(i, columnIndex);
				component = renderer.getTableCellRendererComponent(table, table.getValueAt(i, columnIndex), false, false, i, columnIndex);
				width = Math.max(width, component.getPreferredSize().width);
			}

			width += 2*margin;
			column.setPreferredWidth(width);
		}
	}
}

Java: Copy Directory & Recursive Delete

Posted on

There are a few tasks that are not easily done in Java. Two of the ones that I encountered are to recursively copy a directory from one location to another and to recursively delete a directory. Oracle’s Java API provides a function to delete a directory but only when it is empty. A bit a annoying since most operating systems provide you with a command to recursively delete directories, why re-invent the wheel?

public void recursiveDelete(File rootDir) {
	recursiveDelete(rootDir, true);
}

public void recursiveDelete(File rootDir, boolean deleteRoot) {
	File[] childDirs = rootDir.listFiles();
	for(int i = 0; i < childDirs.length; i++) {
		if(childDirs[i].isFile()) {
			childDirs[i].delete();
		}
		else {
			recursiveDelete(childDirs[i], deleteRoot);
			childDirs[i].delete();
		}
	}
		
	if(deleteRoot) {
		rootDir.delete();
	}
}

Copying directories is another issue that is not supported in Java (at least until 1.6.x) It seems Java 7 has some support for this, though I have not tested it. Though you would still want some common code that would run on Java 5, 6, and 7 for backwards compatibility.

public void copyDirectory(File sourceLocation, File targetLocation) throws IOException {
	if(sourceLocation.isDirectory()) {
		if(!targetLocation.exists()) {
			targetLocation.mkdir();
		}

		String[] children = sourceLocation.list();
		for(int i = 0; i < children.length; i++) {
			copyDirectory(new File(sourceLocation, children[i]), new File(targetLocation, children[i]));
		}
	}
	else {
		InputStream in = new FileInputStream(sourceLocation);
		OutputStream out = new FileOutputStream(targetLocation);
		
		try {
			byte[] buf = new byte[1024];
			int len;
			while((len = in.read(buf)) > 0) {
				out.write(buf, 0, len);
			}
		}
		finally {
			in.close();
			out.close();
		}
	}
}

MySQL Replication & Cluster Evaluation

Posted on Updated on

I have recently written a short evaluation of MySQL Replication and Cluster. This was done mainly as a study to evaluate which setup of MySQL Replication or Cluster is better suited to my needs for certain projects.

MySQL Replication

  • Scales the database beyond the single instance capacity constraints
  • Load balance read/write queries
  • Highly Available setup
  • Increase read performance and decrease database load

MySQL replication setups usually consists of a master and slave server. The master server handles reads and writes while slave servers handle only reads. In a situation where SELECT queries dominate over INSERT/UPDATE/DELETE it is ideal to have 1 master handle only writes and many slaves handle all the reads. It is common practice to see a setup of 1 master and 30 slaves.


Read the rest of this entry »

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;
}