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.
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:
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.
The encryption code is relatively simple (click to enlarge):
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.
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?
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.
Follow us on:
Main photo by wallpaper4me