// CS7 // // Encrypt.java - A small program that uses a simple Caesar // cipher to encrypt a text file. // // TO RUN THIS FILE: // 1. copy it to your java directory // 2. verify that the tio package is available // 3. create a simple text file (pico can be used for this) // 4. run the program as follows: java Encrypt INPUTFILE OUTPUTFILE // (plug in the name of your text file followed by a new file name) // 5. enter a key value (pick some small integer) // 6. do a listing and cat the new file to look inside // 7. it is easy to decrypt as well - do you know how??? // import java.io.*; import tio.*; class Encrypt { public static void main(String[] args) throws IOException { // first check for proper usage if (args.length < 2) { System.out.println("Usage: java Encrypt clearFile outputFile"); System.exit(1); } // load the source file and create the output file ReadInput in = new ReadInput(args[0]); PrintWriter out = new PrintWriter(new FileWriter(args[1])); // get the key System.out.print("Please enter the encryption key (int): "); int key = Console.in.readInt(); // perform the encryption System.out.print("Now encrypting " + args[0] + "..."); encrypt(in, out, key); System.out.println("Complete."); System.out.println("Output written to " + args[1]); out.close(); }// end main() // transforms an upper case char into a new one by shifting by // key spaces (it wraps around if 'Z' is reached) public static int caeserCipher(char c, int key) { return (c - 'A' + key) % 26 + 'A'; } // encrypt() takes a source text file, runs through each char it // contains and writes the encrypted char to the output file. public static void encrypt(ReadInput source, PrintWriter dest, int key) { while (source.hasMoreElements()) { char c = (char) source.readChar(); if (Character.isLetter(c)) // uses wrapper class to check dest.print((char) caeserCipher(Character.toUpperCase(c),key)); else dest.print(c); // just copy non-letters } }// end encrypt() }// end class