Question

8.16 Ch 8, Part 1: XOR Cipher Write this program using Eclipse. Comment and style the...

8.16 Ch 8, Part 1: XOR Cipher

Write this program using Eclipse. Comment and style the code according to CS 200 Style Guide. Submit the source code files (.java) below. Make sure your source files are encoded in UTF-8. Some strange compiler errors are due to the text encoding not being correct.

This program will implement a simple XOR cipher on an integer array, where the data to be encoded is XOR'd with a key. This idea is often used in other more robust ciphers. The XOR cipher itself can be used to obscure data and is fairly simple to implement, but is very vulnerable to attacks. One nice aspect of the XOR cipher is that encryption and decryption are the same. That is, text XOR key = encoded-text and encoded-text XOR key = text. This property of XOR is also why it is so vulnerable to attacks since encoded-text XOR text = key.

Java has a binary XOR bitwise operator: ^. The XOR operator returns 1 is one but not both bits are a 1. See an example below.

public class BitwiseXOR {
   public static void main(String[] args) {
      System.out.println("In decimal:");
      System.out.println("7 ^ 5 = " + (7 ^ 5)); // 2
      System.out.println("In binary:");
      System.out.println("   " + Integer.toBinaryString(7)); // 111
      System.out.println(" ^ " + Integer.toBinaryString(5)); // 101
      System.out.println("------");
      System.out.println("    " + Integer.toBinaryString(2)); // 010
   }
}

More information on bitwise operators can be found at: zyBooks, Ch 4, Section 12, Marc's Lecture Slides, and Geeks for Geeks.

Download the templates and put them into your Eclipse project to get started.

You are asked to implement 4 methods in the SimpleCipher.java file. The suggested order to complete the methods is: toIntArr, toCharArr, encrypt, and, finally, decrypt. The details of what these methods should do can be found in the method header comments.

There are no output tests. So, you can use your main method to test the methods that you are asked to implement. You will find some basic tests already there in the template.

import java.util.Arrays;

public class SimpleCipher
{

/**
* Encrypts an array based on the given key.
*
* The encryption will be a simple XOR cipher. Each element in the toEnc
* array is XOR'd (^) with the corresponding element in the key array. If the
* key is shorter than toEnc, then repeatedly traverse the key as needed
* in order to encode each element of toEnd.
* Hint: This is best accomplished by using the mod (%) operator.
*
* Example: int[] toEnc = {'H', 'e', 'l', 'l', 'o'} and
* int[] key = {'f', 'o', 'o'} gives
* [46, 10, 3, 10, 0] as
* 'H' ^ 'f' = 46
* 'e' ^ 'o' = 10
* 'l' ^ 'o' = 3
* 'l' ^ 'f' = 10
* 'o' ^ 'o' = 0
*
* @param toEnc The integer array to encrypt.
* @param key The key used by the cipher for encryption the array.
* @return A new int array containing the encryption of toEnc with key.
*/
public static int[] encrypt(int[] toEnc, int[] key) {

}

/**
* Decrypts an array based on a given key.
*
* The simple cipher described in the encrypt method uses XOR for the
* encryption. In this method, we want to decrypt the array. That means we
* need to do the inverse operation from the encryption. Interestingly, the
* inverse operation of XOR is XOR. That is, 7^4 = 3 and 3^4 = 7. Hence, we
* can use the encrypt method to decrypt.
*
* Call the encrypt method with the appropriate parameters...
* DON'T DUPLICATE CODE!
*
* @param toDec The integer array to decrypt.
* @param key The key used by the cipher for encryption the array.
* @return A new int array containing the decryption of toDec with key.
*/
public static int[] decrypt(int[] toDec, int[] key) {

}

/**
* A utility method to convert (with possible loss of precision) from an int
* array to a char array.
*
* This method create a new char array of the same length as intArr. Then, element i of
* intArr should be stored as a char in the new array at index i for all i of intArr.
* That is, each element in the returned array should correspond with the same index on
* the original array.
*
* @param intArr The int array to convert.
* @return A new char array with the converted values. If intArr is null,
* this method should return null.
*/
public static char[] toCharArr(int[] intArr) {

}

/**
* A utility method to convert from a char array to an int array.
*
* This method create a new int array of the same length as charArr. Then, element i of
* charArr should be stored as an int in the new array at index i for all i of charArr.
* That is, each element in the returned array should correspond with the same index on
* the original array.
*
* @param charArr The char array to convert.
* @return A new int array with the converted values. If charArr is null,
* this method should return null.
*/
public static int[] toIntArr(char[] charArr) {

}

/**
* This zyBooks only does unit tests of your methods. So, use the main method
* to test your methods.
*/
public static void main(String[] args) {
// The toIntArr and the toCharArr may be useful in testing your encrypt/decrypt methods
int arr[] = {'H', 'e', 'l', 'l', 'o'};
int key[] = {'f', 'o', 'o'};
System.out.println(Arrays.toString(encrypt(arr, key))); // Should be [46, 10, 3, 10, 0]
System.out.println(toCharArr(encrypt(encrypt(arr, key), key))); // Should be Hello
System.out.println(toCharArr(decrypt(encrypt(arr, key), key))); // Should be Hello
}
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks

// SimpleCipher.java

import java.util.Arrays;

public class SimpleCipher {

      /**

      * Encrypts an array based on the given key.

      *

      * The encryption will be a simple XOR cipher. Each element in the toEnc

      * array is XOR'd (^) with the corresponding element in the key array. If

      * the key is shorter than toEnc, then repeatedly traverse the key as needed

      * in order to encode each element of toEnd. Hint: This is best accomplished

      * by using the mod (%) operator.

      *

      * Example: int[] toEnc = {'H', 'e', 'l', 'l', 'o'} and int[] key = {'f',

      * 'o', 'o'} gives [46, 10, 3, 10, 0] as 'H' ^ 'f' = 46 'e' ^ 'o' = 10 'l' ^

      * 'o' = 3 'l' ^ 'f' = 10 'o' ^ 'o' = 0

      *

      * @param toEnc

      *            The integer array to encrypt.

      * @param key

      *            The key used by the cipher for encryption the array.

      * @return A new int array containing the encryption of toEnc with key.

      */

      public static int[] encrypt(int[] toEnc, int[] key) {

            // returning null if toEnc is null

            if (toEnc == null) {

                  return null;

            }

            // creating an int array with same length

            int result[] = new int[toEnc.length];

            // looping through each element in toEnc

            for (int i = 0; i < toEnc.length; i++) {

                  // XORing ith element from toEnc and element at i%key.length index

                  // (that would wrap around if key length is smaller than toEnc) in

                  // key

                  int c = toEnc[i] ^ key[i % key.length];

                  // adding to result array

                  result[i] = c;

            }

            return result;

      }

      /**

      * Decrypts an array based on a given key.

      *

      * The simple cipher described in the encrypt method uses XOR for the

      * encryption. In this method, we want to decrypt the array. That means we

      * need to do the inverse operation from the encryption. Interestingly, the

      * inverse operation of XOR is XOR. That is, 7^4 = 3 and 3^4 = 7. Hence, we

      * can use the encrypt method to decrypt.

      *

      * Call the encrypt method with the appropriate parameters... DON'T

      * DUPLICATE CODE!

      *

      * @param toDec

      *            The integer array to decrypt.

      * @param key

      *            The key used by the cipher for encryption the array.

      * @return A new int array containing the decryption of toDec with key.

      */

      public static int[] decrypt(int[] toDec, int[] key) {

            // using the encrypt method with parameters toDec and key

            return encrypt(toDec, key);

      }

      /**

      * A utility method to convert (with possible loss of precision) from an int

      * array to a char array.

      *

      * This method create a new char array of the same length as intArr. Then,

      * element i of intArr should be stored as a char in the new array at index

      * i for all i of intArr. That is, each element in the returned array should

      * correspond with the same index on the original array.

      *

      * @param intArr

      *            The int array to convert.

      * @return A new char array with the converted values. If intArr is null,

      *         this method should return null.

      */

      public static char[] toCharArr(int[] intArr) {

            // returning null if input is null

            if (intArr == null) {

                  return null;

            }

            // creating a char array

            char[] charArr = new char[intArr.length];

            // copying all elements from intArr to charArr

            for (int i = 0; i < intArr.length; i++) {

                  // casting current element to char and adding to charArr

                  charArr[i] = (char) intArr[i];

            }

            return charArr;

      }

      /**

      * A utility method to convert from a char array to an int array.

      *

      * This method create a new int array of the same length as charArr. Then,

      * element i of charArr should be stored as an int in the new array at index

      * i for all i of charArr. That is, each element in the returned array

      * should correspond with the same index on the original array.

      *

      * @param charArr

      *            The char array to convert.

      * @return A new int array with the converted values. If charArr is null,

      *         this method should return null.

      */

      public static int[] toIntArr(char[] charArr) {

            // returning null if input is null

            if (charArr == null) {

                  return null;

            }

            // creating a int array, copying all elements from charArr to intArr and

            // returning it

            int[] intArr = new int[charArr.length];

            for (int i = 0; i < intArr.length; i++) {

                  intArr[i] = charArr[i]; // no type casting is needed

            }

            return intArr;

      }

      /**

      * This zyBooks only does unit tests of your methods. So, use the main

      * method to test your methods.

      */

      public static void main(String[] args) {

            // The toIntArr and the toCharArr may be useful in testing your

            // encrypt/decrypt methods

            int arr[] = { 'H', 'e', 'l', 'l', 'o' };

            int key[] = { 'f', 'o', 'o' };

            // Should be [46, 10, 3, 10, 0]

            System.out.println(Arrays.toString(encrypt(arr, key)));

            // Should be Hello

            System.out.println(toCharArr(encrypt(encrypt(arr, key), key)));

            // Should be Hello

            System.out.println(toCharArr(decrypt(encrypt(arr, key), key)));

            int arr2[] = { 'J', 'a', 'V', 'a' };

            int key2[] = { 'b', 'x', 'e' };

            // Should be [40, 25, 51, 3]

            System.out.println(Arrays.toString(encrypt(arr2, key2)));

            // Should be JaVa

            System.out.println(toCharArr(encrypt(encrypt(arr2, key2), key2)));

            // Should be JaVa

            System.out.println(toCharArr(decrypt(encrypt(arr2, key2), key2)));

      }

}

/*OUTPUT*/

[46, 10, 3, 10, 0]

Hello

Hello

[40, 25, 51, 3]

JaVa

JaVa

Add a comment
Know the answer?
Add Answer to:
8.16 Ch 8, Part 1: XOR Cipher Write this program using Eclipse. Comment and style the...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • 8.18 Ch 8, Part 3: Tabular Output Write this program using Eclipse. Comment and style the...

    8.18 Ch 8, Part 3: Tabular Output Write this program using Eclipse. Comment and style the code according to CS 200 Style Guide. Submit the source code files (.java) below. Make sure your source files are encoded in UTF-8. Some strange compiler errors are due to the text encoding not being correct. The program you are going to write will produce a String containing a tabular representation of a 2D String array. For the 2D arrays, assume that the first...

  • Change the following Shift Cipher program so that it uses OOP(constructor, ect.) import java.util...

    Change the following Shift Cipher program so that it uses OOP(constructor, ect.) import java.util.*; import java.lang.*; /** * * @author STEP */ public class ShiftCipher { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here Scanner input = new Scanner(System.in); String plainText; System.out.print("Please enter your string: "); // get message plainText = input.nextLine(); System.out.print("Please enter your shift cipher key: "); // get s int s = input.nextInt(); int...

  • Caesar Cipher v3 Decription Description A Caesar cipher is one of the first and most simple...

    Caesar Cipher v3 Decription Description A Caesar cipher is one of the first and most simple encryption methods. It works by shifting all letters in the original message (plaintext) by a certain fixed amount (the amounts represents the encryption key). The resulting encoded text is called ciphertext. Example Key (Shift): 3 Plaintext: Abc Ciphertext: Def Task Your goal is to implement a Caesar cipher program that receives the key and an encrypted paragraph (with uppercase and lowercase letters, punctuations, and...

  • JAVA programming 9.9 Ch 9, Part 2: ArrayList Searching import java.util.ArrayList; public class ArrayListSet {    ...

    JAVA programming 9.9 Ch 9, Part 2: ArrayList Searching import java.util.ArrayList; public class ArrayListSet {     /**      * Searches through the ArrayList arr, from the first index to the last, returning an ArrayList      * containing all the indexes of Strings in arr that match String s. For this method, two Strings,      * p and q, match when p.equals(q) returns true or if both of the compared references are null.      *      * @param s The string...

  • Cryptography, the study of secret writing, has been around for a very long time, from simplistic...

    Cryptography, the study of secret writing, has been around for a very long time, from simplistic techniques to sophisticated mathematical techniques. No matter what the form however, there are some underlying things that must be done – encrypt the message and decrypt the encoded message. One of the earliest and simplest methods ever used to encrypt and decrypt messages is called the Caesar cipher method, used by Julius Caesar during the Gallic war. According to this method, letters of the...

  • This is Crypto Manager blank public class CryptoManager { private static final char LOWER_BOUND = '...

    This is Crypto Manager blank public class CryptoManager { private static final char LOWER_BOUND = ' '; private static final char UPPER_BOUND = '_'; private static final int RANGE = UPPER_BOUND - LOWER_BOUND + 1; /** * This method determines if a string is within the allowable bounds of ASCII codes * according to the LOWER_BOUND and UPPER_BOUND characters * @param plainText a string to be encrypted, if it is within the allowable bounds * @return true if all characters...

  • I am currently using eclipse to write in java. A snapshot of the output would be...

    I am currently using eclipse to write in java. A snapshot of the output would be greatly appreciated to verify that the program is indeed working. Thanks in advance for both your time and effort. Here is the previous exercise code: /////////////////////////////////////////////////////Main /******************************************* * Week 5 lab - exercise 1 and exercise 2: * * ArrayList class with search algorithms * ********************************************/ import java.util.*; /** * Class to test sequential search, sorted search, and binary search algorithms * implemented in...

  • I need to write a program in java that reads a text file with a list...

    I need to write a program in java that reads a text file with a list of numbers and sorts them from least to greatest. This is the starter file. import java.util.*; import java.io.*; public class Lab3 { static final int INITIAL_CAPACITY = 5; public static void main( String args[] ) throws Exception { // ALWAYS TEST FOR REQUIRED INPUT FILE NAME ON THE COMMAND LINE if (args.length < 1 ) { System.out.println("\nusage: C:\\> java Lab3 L3input.txt\n"); System.exit(0); } //...

  • I need to program 3 and add to program 2 bellows: Add the merge sort and...

    I need to program 3 and add to program 2 bellows: Add the merge sort and quick sort to program 2 and do the same timings, now with all 5 sorts and a 100,000 element array. Display the timing results from the sorts. DO NOT display the array. ____________________>>>>>>>>>>>>>>>>>>>>___________________________ (This is program 2 code that I did : ) ---->>>>>> code bellow from program 2 java program - Algorithms Write a program that randomly generates 100,000 integers into an array....

  • must provide the following public interface: public static void insertSort(int [] arr); public static void selectSort(int...

    must provide the following public interface: public static void insertSort(int [] arr); public static void selectSort(int [] arr); public static void quickSort(int [] arr); public static void mergeSort(int [] arr); The quick sort and merge sort must be implemented by using recursive thinking. So the students may provide the following private static methods: //merge method //merge two sorted portions of given array arr, namely, from start to middle //and from middle + 1 to end into one sorted portion, namely,...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT