I have researched a lot on this question and finally understood this, that encrypting and decryption using just XOR is not a suggested way of encryption but as it is an academic question I have to do it.
In my scenario I have to save java objects(space delimited strings with xor encryption by a key of our choice) in a file(.txt file) line by line and retrieve them later on if needed. So saving a xor string in a file is not a problem but while decrpytion its getting truncated. Below is a sample similar code which I have implemented for my project.
public class TestingXor {
private static String XorString(String input){
String key = "computing";
Charset charSet = Charset.forName("UTF-8");
byte[] inputBytes = input.getBytes(charSet);
byte[] keyBytes = key.getBytes(charSet);
for(int i=0;i<inputBytes.length;i++){
inputBytes[i] = (byte)(inputBytes[i] ^ keyBytes[i%keyBytes.length]);
}
return (new String(inputBytes,charSet));
}
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
File testFile = new File("addressBook.txt");
Scanner scanObj = new Scanner(testFile);
String testString = "asd asdasd 07/08/2015 asdasdasd 198546125";
BufferedWriter writer = new BufferedWriter(new FileWriter(testFile));
writer.write(XorString(testString));
writer.close();
System.out.println(XorString(scanObj.nextLine()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The above code returns "asd as" where as I need the whole string .If I am not saving the file I am able to encrypt and decrypt properly, but If I am saving the string to a file and retrieving the string from the file and decrypting it does'nt work. I think it is related to saving of the string(\0 getting saved in the middle of the line) but what is the work around this. I dont know the length of the string when I am reading from a file. If this question is already answered you can redirect me to that question.