I'm trying to encrypt and decrypt strings using cipher text with a random keyword. The random keyword will be in a file "keyword.txt":
TROYONLINE
The string(s) will be in a separate file "input.txt":
THE QUICK BROWN FOX JUMPED OVER THE LAZY DOG
more lines here....
The cipher should use the keyword and a reversed alphabet without redundant letters. The cipher for keyword "TROYONLINE" would be:
TROYNLIEZXWVUSQPMKJHGFDCBA
Using this cipher, the above string will be encrypted to this:
HEN MGZOW RKQDS LQC XGUPNY QFNK HEN VTAB YQI
So far, I have this code:
import java.util.*;
import java.io.*;
public class reverseString
{
public static void main(String [] args)
{
String abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String cipher = "";
String newCipher;
String encrypt = "";
String ouput = "";
BufferedReader readerKeyword = null;
String key = "";
try
{
readerKeyword = new BufferedReader(new FileReader("keyword.txt"));
}
catch (FileNotFoundException fnfex)
{
System.out.println(fnfex.getMessage() + " File not found.");
System.exit(0);
}
try
{
while ((key = readerKeyword.readLine()) !=null)
{
StringBuffer sb = new StringBuffer();
int len = abc.length();
for(int i = len -1;i>=0;i--)
cipher = cipher + abc.charAt(i);
newCipher = sb.append(key).append(cipher).toString();
System.out.println(key);
System.out.println(removeDuplicates(newCipher));
}
}
catch (IOException ioex)
{
System.out.println(ioex.getMessage() + " Unable to read file.");
System.exit(0);
}
BufferedReader readerInput = null;
String lineInput;
try
{
readerInput = new BufferedReader(new FileReader ("input.txt"));
}
catch (FileNotFoundException fnfex)
{
System.out.println(fnfex.getMessage() + " File not found.");
System.exit(0);
}
try
{
while ((lineInput = readerInput.readLine()) !=null)
{
char[] inputArray = lineInput.toCharArray();
System.out.println(inputArray);
}
}
catch (IOException ioex)
{
System.out.println(ioex.getMessage() + " Unable to read file.");
}
}
static String removeDuplicates(String newCipher)
{
char[] charArr = newCipher.toCharArray();
Set<Character> charSet = new LinkedHashSet<Character>();
for(char ch : charArr)
{
charSet.add(ch);
}
StringBuffer StrBuf = new StringBuffer();
for(char c : charSet)
{
StrBuf.append(c);
}
char[] cipherArray = removeDuplicates(newCipher).toCharArray();
System.out.println(cipherArray);
return StrBuf.toString();
}
}
But I'm getting the below error:
TROYONLINE
Exception in thread "main" java.lang.StackOverflowError
at java.util.HashMap.<init>(HashMap.java:456)
at java.util.LinkedHashMap.<init>(LinkedHashMap.java:347)
at java.util.HashSet.<init>(HashSet.java:161)
at java.util.LinkedHashSet.<init>(LinkedHashSet.java:154)
at reverseString.removeDuplicates(reverseString.java:83)
at reverseString.removeDuplicates(reverseString.java:94)
With a ton of repeats of the last line ...(reverseString.java:94)