Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

#18. File encryption is the science of writing the contents of a file in a secre

ID: 3713637 • Letter: #

Question

#18. File encryption is the science of writing the contents of a file in a secret code. Your encryption program should work like a filter, reading the contents of one file modifying the data into a code, and then writing the coded contents out to a second file. There are very complex encryption techniques, but for ours, will use a simple one from the shift category. We will take each character and shift it one place in the Unicode sequence. So ‘a’ becomes ‘b’, ‘b’ becomes ‘c’, etc. What about ‘z’? You could make it ‘a’ or just the next Unicode character, which is the choice we will take. NOTE: you must be writing and reading a text file, not a serializable one, and you must have a FileDialog ox where the user can choose the file to utilize.

     

Write a program names EncryptDecrypt.java that has the following menu choices:

Read in a file

Print the file to the console (obviously – this is for debugging only)

Encrypt the file and write it to the console

Write out the encrypted file to a text file

Clear the data in memory

Read in an encrypted file

Decrypt the file

Write out the decrypted file to the console

End

Explanation / Answer

import java.io.*;

public class Encryption
{
public static void main(String[] args) throws IOException
{
encrypt(new File("test.txt"), new File("test2.txt"));
decrypt(new File("test2.txt"), new File("test.txt"));
}
public static void encrypt(File input, File output) throws IOException
{
// open I/O streams
DataInputStream in = new DataInputStream(new FileInputStream(input));
DataOutputStream out = new DataOutputStream(new FileOutputStream(output));

// read characters, encrypt them, and output to file
char c;

try
{
// read until EOF character is found
while((c=in.readChar())!=0)
{
out.writeChar((char)(c+10));
}
}
catch(Exception ex)
{
// stop reading if an exception is thrown
}

// close I/O streams
in.close();
out.close();

}
public static void decrypt(File input, File output) throws IOException
{
// open I/O streams
DataInputStream in = new DataInputStream(new FileInputStream(input));
DataOutputStream out = new DataOutputStream(new FileOutputStream(output));

// read characters, encrypt them, and output to file
char c;

try
{
// read until EOF character is found
while((c=in.readChar())!=0)
{
out.writeChar((char)(c-10));
}
}
catch(Exception ex)
{
// stop reading if an exception is thrown
}

// close I/O streams
in.close();
out.close();

}
}