Reputation: 153
I want to excrypt a file in java very basically. Simply read line by line the file, and change the value of the chars to "char += key", where key is an integer. The problem is that if I use a key larger or equal with 2, it doesn't work anymore.
public void encryptData(int key) {
System.out.println("Encrypt");
try {
BufferedReader br = new BufferedReader(new FileReader("encrypted.data"));
BufferedWriter out = new BufferedWriter(new FileWriter("temp_encrypted.data"));
String str;
while ((str = br.readLine()) != null) {
char[] str_array = str.toCharArray();
// Encrypt one line
for (int i = 0; i < str.length(); i++) {
str_array[i] += key;
}
// Put the line in temp file
str = String.valueOf(str_array);
out.write(str_array);
}
br.close();
out.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
The decrypt function is the same but with the input/output files interchanged and instead of adding the key value, I subtract it.
I check char by char and indeed, the header gets messed up when i use a key value > 1. Any ideas? Is it because of maximum value of the char being exceeded?
Upvotes: 0
Views: 54
Reputation: 23738
You're basically implementing a general-purpose Caesar cipher. Adding a number to a character could change a character to newline, etc which will not work if using a BufferedReader to read it back in.
Best to manipulate the text as a byte stream which would correctly encode and decode newline and any non-ASCII characters.
public void encryptData(int key) {
System.out.println("Encrypt");
try {
BufferedInputStream in = new BufferedInputStream(new FileInputStream("raw-text.data"));
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("temp_encrypted.data"));
int ch;
while((ch = in.read()) != -1) {
// NOTE: write(int) method casts int to byte
out.write(ch + key);
}
out.close();
in.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
public void decryptData(int key) {
System.out.println("Decrypt");
try {
BufferedInputStream in = new BufferedInputStream(new FileInputStream("temp_encrypted.data"));
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("decrypted.data"));
int ch;
while((ch = in.read()) != -1) {
out.write(ch - key);
}
out.close();
in.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
Upvotes: 1