INFSCI 1075 Network Security Homework 5 Reading assig nment
Solution
import java.util.Scanner;
public class ShiftCipher {
   public static String encyrptDecrypt(String inputText, int offset) {
       
        StringBuffer encryptBuffer = new StringBuffer();
       
        /*
        * For each character, it checks whether it is between A-Z,
        * if yes then computes the substitute character
        */
        for (int i=0; i< inputText.length(); i++) {
            char character = inputText.charAt(i);
           
            if (character >= 65 && character<= 97) {
                character = (char) ((character -\'A\' + offset) % 26 + \'A\');
            }
            encryptBuffer.append(character);
        }
        return encryptBuffer.toString();
    }
   
    public static void main(String args[]) {
       
        Scanner scan = new Scanner(System.in);
        System.out.print(\"Encryption or Decryption ? (E/D) : \");
        String choice = scan.nextLine();
       
        if(choice.equals(\"E\") || choice.equals(\"D\")) {
           
            System.out.print(\"Enter the key (A-Z) : \");
            String key = scan.nextLine().trim();
           
            /*
            * Validate if key is a capital alphabet
            * Beacuse of the cyclic property, we can use the same functions
            * to encrypt (key=n) and decrypt(key=26-n)
            */
            if (key.length() == 1 && Character.isUpperCase(key.charAt(0))) {
               
                System.out.print(\"Enter the text : \");
                String text = scan.nextLine().trim().toUpperCase();
               
                if (choice.equals(\"E\")) {
                    System.out.println(\"Cipher is : \"+ encyrptDecrypt(text, key.charAt(0)-\'A\'));
                }
                else {
                    System.out.println(\"Cipher is : \"+ encyrptDecrypt(text, 26-(key.charAt(0)-\'A\')));
                }
            }
            else {
                System.out.println(\"Invalid key entered. Must be between A-Z\");
            }
        }
        else {
            System.out.println(\"Invalid Option Entered\");
        }
        scan.close();
    }
 }
--------------------------------------------
 Output-1
Encryption or Decryption ? (E/D) : E
 Enter the key (A-Z) : H
 Enter the text : ZUBAIR
 Cipher is : GBIHPY
-------------------------------------------
 Output-2
Encryption or Decryption ? (E/D) : D
 Enter the key (A-Z) : H
 Enter the text : GBIHPY
 Cipher is : ZUBAIR
 --------------------------------------------


