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.




About reederProgramming

I already have an about me page, so I will just put a quick bit of info here. I am a Notes/Domino developer at holistic-net GmbH located in Hannover, Germany. I use Java primarily at home and as often as I can at work. I have dabbled in C# and a few other languages and platforms. This website started out as a place for me to quickly store and access some of my most important how-tos and has started to become a place where I can really help others too!
Tagged , , , . Bookmark the permalink.

2 Responses to Java and Encryption

  1. Marcos says:

    what is a good library to use? Bouncy Castle? Is it fast?

Leave a Reply

Your email address will not be published. Required fields are marked *