Question: How would I write a program that encrypts or decrypts a file using the following substitution/encryption method as shown below? A B C D E
How would I write a program that encrypts or decrypts a file using the following substitution/encryption method as shown below?
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
substituting the above with the below
F E A T H R Z Y X W V U S Q P O N M L K J I G D C B
---------
So far I have this as my code below
--------
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
/**
This class encrypts files using the Caesar cipher.
For decryption, use an encryptor whose key is the
negative of the encryption key.
*/
public class Cipher
{
/**
Constructs a cipher object with a given key.
@param aKey the encryption key
*/
public Cipher(int aKey)
{
key = aKey;
}
/**
Encrypts the contents of a stream.
@param in the input stream
@param out the output stream
*/
public void encryptStream(InputStream in, OutputStream out)
throws IOException
{
boolean done = false;
while (!done)
{
int next = in.read();
if (next == -1) done = true;
else
{
char b = (char) next;
char c = encrypt(b);
out.write(c);
}
}
}
/**
Encrypts a char.
@param b the char to encrypt
@return the encrypted char
*/
public char encrypt(char c)
{
if ( key < 0 )
key = key + 26;
if ( Character.isUpperCase(c) )
return (char)((c - 'A' + key) % 26 + 'A');
if ( Character.isLowerCase(c) )
return (char)((c - 'a' + key) % 26 + 'a');
return c;
}
private int key;
}
----------------
I'm lost on to deciding which part of the program is reusable and which part is not. What methods and instance variables do I need to add?
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
