Beginning with Java

Welcome to the Java Tutorial

Welcome to a new tutorial of learning how to program with java!  I have tried to make videos of myself doing all of this, but I think this will work out better.  It is my goal in this tutorial to teach anyone interested the basics of programming.  We could start in any language, but I feel that Java offers the best structure to learn Object Oriented Programming.

Object Oriented Programming (OOP) is a way to organize a program into objects.  Java makes OOP a founding philosophy that creates a language that is very robust and expandable while making a complex program easy(er) to understand.  Granted it could be said that java just makes simple tasks very complex and that would not be wrong.  But it is also a very large leap forward from C++.

Java is a very interesting language.  A few advantages are:

  • forced Exception (error) Handling.  Any error that is created and known about must be handled at design time or else the program will not “compile”
  • Strict OOP programming style
  • platform and operating system independance
  • well documented
  • plenty of online tutorials
  • free Integrated Development Environments (IDEs)
  • easy switch to other OOP languages such as Microsoft’s C#

Numerous programs have been created with Java, including games. Minecraft is one example, but there are plenty more such as Applets that run on browsers that aide in seat selection at an online ticketing service, programs that automate coffee machines, parking machines, and plenty of others.  There is no better language to start with, not even, in my opinion, Visual Basic.

Let’s set up our environment!

In order to start our programming tutorial, a few programs must be in place.  The first step is to get the Java Runtime Environment (JRE).  In many cases, this is already installed.  The easiest way to verify this is to open a command line window and give the java -version command

java -version command

java -version command

If the screen looks like the window above, regardless of which java version is displayed, than a JRE is already installed and you need not worry about downloading it.  Otherwise, it must be installed.  To do this, go to the following webpage and search for the appropriate JRE install file:
http://www.java.com/en/download/index.jsp
It is also easy to find by putting JRE Download into google.

The next step would be to download the java development tookit (JDK).  That can be done at the following website
http://www.oracle.com/technetwork/java/javase/downloads/index.html
Again, only a simple google search is needed.  All you need is the standard edition.  It is not necessary to sign up or register for any of these downloads.

The third download is also very easy to find, and it will not be “installed” into the system, just started.  For this tutorial series, we will be using eclipse Juno.  Currently the newest release is Eclipse Kepler, but the two are almost identical and it is not important to have the same version as I have.  You can download eclipse from here:
http://www.eclipse.org/downloads/
I often download the EE version, but the standard is just as well for getting into java for the first time and for mostly all projects.  Once this file downloads, extract it into a place that it can stay for a longer period of time.  I do not recommend the desktop, but that is your decision.

Once that is finished, we will want to start eclipse.  To do that, just open that folder and open the eclipse executable that has a purple icon:
EclipseFolderA window will open up where you can select your desired workspace.  The default will be located in your personal documents folder.  You can change this if desired, or even create a new folder easily.  I started out creating a new workspace for every program I worked on, but this is unnecessary.
eclipseWorkspaceWith these steps done, eclipse will start and it is possible to start programming.  In the next tutorial, we will look at where to go from here, including looking at a few basic types in Java, and creating a program that allows us to put information into the user console.

 

Java and Encryption

Welcome to a small tutorial like lesson where I go into a bit of encryption etc in Java.  This will not be a highly detailed discuss, I will just go into the basics.

First off, what is encryption?
Cryptography is, in its most basic form, preparing information for transmission in such a way that it cannot be read or understood by others.  Cryptography got its start thousands of years ago, and has taken on may forms.  My favorite historical example is a method whereby a piece of “paper” could be wrapped around a stick.  The message would then be written on the paper.  Once unwrapped, it would be difficult to know what it was saying without knowing the diameter of the stick that was used to “encrypt” the message, if you could tell what it was in the first place.  It is said that the Spartans used this system.  Later, another encryption system was used where the letters would be transposed a few spaces.  In other words, ‘A’ would become ‘C’, ‘B’ to ‘D’ and so on.  Current methods are not too different.

Why am I using encryption in BudgIt?

My use case is fairly simple.  I want to be able to store some basic program information that the normal user should not be able to see or change without my business logic.  I need the information available without a database connection, so that would not do, and although I could use some sort of a binary reader/writer, the point of BudgIt is to learn, so that is what I am going to do.

Encryption would probably be better if the goal is to transfer data across the internet.  This would hopefully prevent eavesdroppers from getting personal and sensitive information. although you still have to worry about the NSA.  😀  In fact, it has even been reported that they have overseen the development of a few ciphers in order to make sure that they have a “master key” that can unlock any encrypted transmission.  But alas: politics is not the reason for this post, so lets just jump into it.

Lets create a key in java

private void createKey(){
		String msg;
		KeyGenerator keygenerator;
		SecretKey key;
		String keyfile = FILE_KEY;
		ObjectOutputStream oos = null;
		File f = new File(keyfile);
		if(f.exists()){
			//Warning: Key already exists!  Would you like to generate a new key?  This could make information that already exists unreadable.;

		}
		try{
			keygenerator = KeyGenerator.getInstance("DES"); // this says to use the DES algorithm when it creates the key file.
			keygenerator.init(new SecureRandom());
			key = keygenerator.generateKey();
//initiate the key generator and create a key
			SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
			Class<?> spec = Class.forName("javax.crypto.spec.DESKeySpec");
			DESKeySpec ks = (DESKeySpec) skf.getKeySpec(key,  spec);

			oos = new ObjectOutputStream(new FileOutputStream(keyfile));
			oos.writeObject(ks.getKey());

			Cipher c = Cipher.getInstance("DES/CFB8/NoPadding");
			c.init(Cipher.ENCRYPT_MODE, key);
			oos.writeObject(c.getIV());
			oos.close();

		} catch(NoSuchAlgorithmException e) + many others that I will skip{
			//The encryption algorithm DES is unknown to this system.
		} finally{
			if (oos != null){
				try {
					oos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

This is a very complex bit of code to wade through and I do not really want to rip it to pieces explaining what each part does, but I will say this.  This bit of code is creating a key and saving that key to a file to be used later by an encryption and decryption function.  It is important to note that if this key is lost, the files saved using this key will no longer be able to be read.  (unless you are the NSA).

 

Next, we are going to use that file to encrypt an array of strings.  Again, I am not going to go line by line through it, but it is pretty self explanatory.  It looks more scary than it really is.

public void encryptToFile(String fileName, String[] strings) {

		// check existance of the key
		File f = new File(FILE_KEY);
		if (!f.exists()){
			//An encryption key could not be found!  
		}

		ObjectInputStream ois = null;
		PrintWriter pw = null;

		try{
			ois = new ObjectInputStream(new FileInputStream(f));
			DESKeySpec ks = new DESKeySpec((byte[])ois.readObject());
			SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
			SecretKey key = skf.generateSecret(ks);

			Cipher c = Cipher.getInstance("DES/CFB8/NoPadding");
			c.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec((byte[])ois.readObject()));
			CipherOutputStream cos = new CipherOutputStream(new FileOutputStream(fileName), c);
			pw = new PrintWriter(new OutputStreamWriter(cos));
			for (String s : strings){
				pw.println(s);
			}
			pw.flush();
		} catch long list of exceptions {

		} finally{
			if(ois != null){
				try {
					ois.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (pw != null){
				pw.close();
			}
		}
	}

Here we are decrypting a file that we already saved.  This must use the same key that we used to encrypt the file.

 
public ArrayList<String> dycryptFile(String fileName) throws FileNotFoundException, IOException{

		ArrayList strings = new ArrayList();

		String msg;
		// check existance of the key
		File f = new File(FILE_KEY);
		if (!f.exists()){
			//An encryption key could not be found!
		}

		ObjectInputStream ois = null;
		CipherInputStream cis = null;
		BufferedReader br = null;
		String input = "";

		try{
			//********************************************** get cipher**********************************
			ois = new ObjectInputStream(new FileInputStream(f));
			DESKeySpec ks = new DESKeySpec((byte[])ois.readObject());
			SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
			SecretKey key = skf.generateSecret(ks);

			Cipher c = Cipher.getInstance("DES/CFB8/NoPadding");
			c.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec((byte[])ois.readObject()));
			// ************************************************* decrypt file********************************

			cis = new CipherInputStream(new FileInputStream(fileName), c);
			br = new BufferedReader( new InputStreamReader(cis));

			while ((input = br.readLine()) != null){
				strings.add(input);
			}

		} 
		//... catch long list of exceptions ...

		} finally {
			if(ois != null){
				try {
					ois.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(br != null){
				br.close();
			}
		}
		return strings;
	}

This is just a quick block to get all of you interested people an example to look at.  I do hope to write again soon and go into each of the methods and say what each part is actually doing and why it is important, but for now I hope that it can be understood.