How to Write a Basic Encryption Program Using Java!

Today, we are going to combine what we learned from the Introduction to Cryptography article with our Java programming skills. If you are new to Java, check out Matthew's Learn Java: Part One for a quick beginner's lesson, or check out some of the Java tutorials directly on Oracle.

The program will we use is my Caesar Cipher app. Just click here to download it and here to view and/or download the source code.

How to Encrypt and Decrypt

This program uses the Caesar Cipher algorithm, which we discussed last month. As a review, this cipher works by shifting each letter by 0 to 25 times. So, if we wanted to encrypt "ABC" with a shift of 1, then we would shift all the letters one to the right, yielding "BCD".

Here is how you would use the app to do that:

How to Write a Basic Encryption Program Using Java!

If you wanted to send a secret message to your friend, you would input the message into the top box, enter a shift factor (both people need to agree on this number), then push "Encrypt". When your friend receives the message, they put the ciphertext into the top box with the agreed "Shift Factor", then press "Decrypt". Assuming my code isn't buggy, it should then display the secret message in plain text!

Note that this encryption algorithm is not very secure. Someone who knows you are using a Caesar Cipher encryption could easily break it by hand, since there are only 26 possibilities. In later posts, we will write more secure encryption algorithms.

How the Code Works

The encryption code is relatively simple (click to enlarge): 

How to Write a Basic Encryption Program Using Java!

Decryption is very similar; we simply switch the keys and values in the hashmap so that everything is in reverse. The GUI interface is a bit beyond the scope of this article, but feel free to look it over. As always, try experimenting with the code to see what happens when you change things.

Coding Challenge

What if we forgot what shift factor we were supposed to use or suppose we intercepted an enemies message? How could we augment our Java program so that we could still successfully decrypt the message in a reasonable amount of time?

Have a solution?

Send the code to invisiblecomputer314@gmail.com. If you provide a correct solution, you will gain 10 Invisible Computer points! What are these points? Learn more about them!

Hint: You can write a method that is executed when no "Shift Factor" is entered. A brute force tactic would calculate all the possibilities, then somehow identify which of them is most likely the correct one.

If you have any questions, just ask somewhere in the forum, comments, or send me a message!

Follow us on:

Main photo by wallpaper4me

1 Comment

I remember this cipher from my old secret decoder ring! Interested to see what cryptograms you cover next.

Share Your Thoughts

  • Hot
  • Latest