I was asked to write a program that encrypts a file by adding 5 to every byte of it and then write another program to decrypt the file. And here is the program I wrote. But it doesn't work. It encrypted a file successfully but then could not restore it back to the origin. The result of the decryption is just a file with some weird symbols in it.
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class CryptingFile
{
public static void main(String[] args)
{
if(args.length != 3 || (args[2].compareTo("-en") != 0 && args[2].compareTo("-de") != 0))
{
System.out.println("Usage: sourceFile targetFile -<option>");
System.out.println("<option>: ");
System.out.println(" en : encrypt");
System.out.println(" de: decrypt");
System.exit(0);
}
try
{
File fileInput = new File(args[0]);
File fileOutput = new File(args[1]);
FileInputStream input = new FileInputStream(fileInput);
FileOutputStream output = new FileOutputStream(fileOutput);
if(args[2] == "-en")
{
int value;
while((value = input.read()) != -1)
output.write(value + 5);
}
else
{
int value;
while((value = input.read()) != -1)
output.write(value - 5);
}
input.close();
output.close();
}
catch (FileNotFoundException ex)
{
System.out.println("Error " + args[0] + " not found");
} catch (IOException ex)
{
System.out.println("Error reading file");
}
}
}
This is a result it should look like:
This is a test file.
But it looks something like this:
J^_i_iWj[ij_b[$