java

Easy String Encryption With Bouncy Castle and Jasypt

Posted on

At times you want a an easy and straightforward way to encrypt strings without the hassle of undocumented cryptographic libraries *cough* bouncy castle *cough*. This is where Jasypt comes in. It is a powerful encryption library that makes cryptography fun and easy! What makes Jasypt nice is that it can perform simple encryption using passwords very quickly. That is quickly in terms of development time.

Below is a simple example of using Jasypt to encrypt a string using BouncyCastle as the provider.

PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
encryptor.setProviderName("BC");
encryptor.setAlgorithm("PBEWITHSHA256AND256BITAES-CBC-BC");
encryptor.setPoolSize(4);
encryptor.setSaltGenerator(new RandomSaltGenerator());
encryptor.setKeyObtentionIterations(100000);
encryptor.setPasswordCharArray("BadAssPassword12345!".toCharArray());
		
String crypted = encryptor.encrypt("Hello World!");
System.out.println(crypted);
		
String plain = encryptor.decrypt(crypted);
System.out.println(plain);

The above code should work, but you will need to download Jasypt and BouncyCastle libraries and set them on your classpath.

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

Posted on

We’re back! Back to PGP Cryptography tutorials!! Because when I want to learn something new I learn faster by writing a tutorial about it, sharing code and receiving feedback.

So in Part 4 I apologized that I did not have a lot of time and just showed how to integrate Bouncy Castle with Android by using SpongyCastle. Now I will go through how to generate and verify detached signatures. This has become important since Part 2 did teach how to sign and verify files, but the signature was embedded inside the file. Though this works, it did not work when trying to verify the file using a regular program like GPG / Kleopatra. Also not all PGP clients support ZLIB compression which could break compatibility. So I decided that the need to generate detached signatures was important.

Continuing with the previous examples we have the PGPTools file which I wrote to make cryptography easier with BC (Full source can be found here). Generating a detached signature file needs the following:

  • The file you want to sign
  • The name of signature file that will be generated
  • The PGP Key ring that contains your secret and public keys

Another interesting thing to know to go by is the naming convention of these files. Most programs look for it and makes it easier for the user to utilize and for programs to find. Supposed there is a file called “TheFile.txt”, below is how the signature file would be named:

  • ASCII Armored Signature: TheFile.txt.asc
  • Binary Signature: TheFile.txt.sig

This is not mandatory, but a nice convention to follow.

Read the rest of this entry »

Java: ISO-3166 Java Enum

Posted on Updated on

Having worked software development in a bank before I know how important it is to work with proper data structures and enumerations.

I had a program I needed to write where I had to utilize ISO country codes and there was a lot of interoperability work that needed to be done. So I tried looking for some basic library that had the standard ISO-3166 country codes. Couldn’t find any. I really just needed something I could look up a country code quickly and get its description. Like saving “SLV” or “222” as a key in a database for El Salvador’s currency. Then I can retrieve it and do a look up on a table to get the country name. Or even vice-versa.

Read the rest of this entry »

Java: Calculate Distance Between 2 Points on Earth

Posted on

Find the distance between 2 longitude/latitude points on earth must have been the one thing I thought was everywhere on the web. And it is! Only problem is that most of the libraries and code I would find were in JavaScript. This is OK if you develop in JavaScript or even in GWT.

What about Java?

Yes, for those of us developers who need to code such functions in Java I found it quite difficult to find a ready made library that would give me the distance between 2 longitude/latitude points. This is in fact very essential because one of the main ideas behind having GeoLocation support in your applications and/or server back-end is to tell someone how close everything is to them. You get the geographical coordinates of your user and you send it to a server. The server calculates the distance between that user and all burger joints within a 5 km radius, thus giving your user a list of delectable places close to them where they can go and eat.

After a long search on the Internet I came across 2 options.

  1. Read and learn how to calculate the distance my self from this really nice paper called "Finding Points Within a Distance of a Latitude/Longitude Using Bounding Coordinates"
  2. Use the source readily available from GeoDataSource

Guess which one I took ? 🙂 Option 2 of course. Though I did read through the paper and found it interesting. At least I know how, but I am not in that much of a mood to sit down with mathematical equations on one hand and a compiler on the other hand all night. The second option, which was kinda weird because the "Sample Code" is provided and it calculates distance nicely. I see only one trademark and a copyright notice with no specified license. They talk about buying GeoDataSource products, but I doubt that "Sample Code" is the product in question. After all, it is just "Sample Code". I think they sell you a database of geographical coordinates and give you that "Sample Code" on how you would use their data.

Great! Now that I convinced my self that the "Sample Code" is not the actual product, I start to use it. I may say that is works very well. It could use a bit more documentation so I am going to reproduce the "Sample Code" here with my added extra documentation.

In a nut shell, you would call the method distance(double lat1, double lon1, double lat2, double lon2, char unit) like so

double lat1 = getMyLatitude();
double lon1 = getMyLongitude();
double lat2 = getHisLatitude();
double lon2 = getHisLongitude();
double distance = distance(lat1, lon1, lat2, lon2, 'K');
System.out.println("Distance between me and him is "+distance+" km");

The API method as I have documented them. You can also view the original at GeoDataSource

	/**
	 * <p>This routine calculates the distance between two points (given the
	 * latitude/longitude of those points). It is being used to calculate
	 * the distance between two locations.</p>
	 * 
	 * <p>Definitions: South latitudes are negative, east longitudes are positive</p>
	 * 
	 * <p>Passed to function:
	 * <ul>
	 * 		<li>lat1, lon1 = Latitude and Longitude of point 1 (in decimal degrees)</li>
	 * 		<li>lat2, lon2 = Latitude and Longitude of point 2 (in decimal degrees)</li>
	 * 		<li>unit = the unit you desire for results
	 * 			<ul>
	 * 				<li>where: 'M' is statute miles</li>
	 * 				<li>'K' is kilometers (default) </li>
	 * 				<li>'N' is nautical miles</li>
	 * 			</ul>
	 * 		</li>
	 * </ul>
	 * Worldwide cities and other features databases with latitude longitude
	 * are available at http://www.geodatasource.com</p>
	 * 
	 * <p>For enquiries, please contact sales@geodatasource.com</p>
	 * <p>Official Web site: http://www.geodatasource.com</p>
	 * <p>GeoDataSource.com (C) All Rights Reserved 2013</p>
	 * 
	 * 
	 * @param lat1 - latitude point 1
	 * @param lon1 - longitude point 1
	 * @param lat2 - latitude point 2
	 * @param lon2 - longitude point 2
	 * @param unit - unit of measure (M, K, N)
	 * @return the distance between the two points
	 */
	public static final double distance(double lat1, double lon1, double lat2, double lon2, char unit)
	{
		double theta = lon1 - lon2;
		double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
		dist = Math.acos(dist);
		dist = rad2deg(dist);
		dist = dist * 60 * 1.1515;
		
		if (unit == 'K') {
			dist = dist * 1.609344;
		}
		else if (unit == 'N') {
			dist = dist * 0.8684;
		}
		
		return (dist);
	}

	/**
	 * <p>This function converts decimal degrees to radians.</p>
	 * 
	 * @param deg - the decimal to convert to radians
	 * @return the decimal converted to radians
	 */
	private static final double deg2rad(double deg)
	{
		return (deg * Math.PI / 180.0);
	}

	/**
	 * <p>This function converts radians to decimal degrees.</p>
	 * 
	 * @param rad - the radian to convert
	 * @return the radian converted to decimal degrees
	 */
	private static final double rad2deg(double rad)
	{
		return (rad * 180 / Math.PI);
	}

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

Posted on Updated on

Continuing my 5 part series on using the Bouncy Castle API to create your own Java library to manage Private / Public key pairs. Part 2 went over digitally signing and verifying messages using the generated key pair from Part 1. Also, just a note, the signature generation from Part 2 are not detached signatures, they’re embedded within the information. I’ll talk about why I prefer to do this when we get to Part 4.

Encryption is done using the recipients public key and does not require us to enter a pass phrase. When the recipient receives the encrypted message they will need to enter their pass phrase in order to decrypt the message. This is mainly so because their public key is protected by password based symmetric encryption inside the key ring.

Below we add the encrypt and decrypt methods to our PGPCryptoTools source file.

Read the rest of this entry »

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 »

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 »