Thursday, September 17, 2015

Shift Cipher

Problem 

The code below decrypts a shift cipher and outputs all possible shift ciphers (26 of them), From which you can easily detect if the given text is a shift cipher or if it is a shift cipher, find out the plaintext manually from the output.

Note: This code was written to decrypt shift ciphers (such as caesar's cipher) for Chapter 2 Problems of Mark Stamp's Cryptography and Information Security book for CS265 module at San Jose State University

Example

Input:VSRQJHEREVTXDUHSDQWV
Output:
0= WTSRKIFSFWUYEVITERXW
1= XUTSLJGTGXVZFWJUFSYX
2= YVUTMKHUHYWAGXKVGTZY
3= ZWVUNLIVIZXBHYLWHUAZ
4= AXWVOMJWJAYCIZMXIVBA
5= BYXWPNKXKBZDJANYJWCB
6= CZYXQOLYLCAEKBOZKXDC
7= DAZYRPMZMDBFLCPALYED
8= EBAZSQNANECGMDQBMZFE
9= FCBATROBOFDHNERCNAGF
10= GDCBUSPCPGEIOFSDOBHG
11= HEDCVTQDQHFJPGTEPCIH
12= IFEDWURERIGKQHUFQDJI
13= JGFEXVSFSJHLRIVGREKJ
14= KHGFYWTGTKIMSJWHSFLK
15= LIHGZXUHULJNTKXITGML
16= MJIHAYVIVMKOULYJUHNM
17= NKJIBZWJWNLPVMZKVION
18= OLKJCAXKXOMQWNALWJPO
19= PMLKDBYLYPNRXOBMXKQP
20= QNMLECZMZQOSYPCNYLRQ
21= RONMFDANARPTZQDOZMSR
22= SPONGEBOBSQUAREPANTS
23= TQPOHFCPCTRVBSFQBOUT
24= URQPIGDQDUSWCTGRCPVU

From the above list, we can find out that text at #22 is the decrypted text.

Solution

package Cypto;
import java.util.ArrayList;
import java.util.HashMap;

public class AlphaShift {

 char[] alphabets = new char[26];
 ArrayList> mapList 
 = new ArrayList >();
 
 public AlphaShift(){
  initAlphabet();
  storePermutations();
 }

 public void initAlphabet() {
  for(int i = 0; i < 26; i++){
   alphabets[i] = (char)('A' + i); 
  }
//  System.out.println(alphabets);
 }


 public void storePermutations()
 {
  int increment = 1;
  while(increment<= 25){
   HashMap map =  new HashMap();
   for(int i=0; i< alphabets.length; i++)
   {
    int newAlpha = (alphabets[i] - alphabets[0] + increment)%alphabets.length;
    map.put(alphabets[i], (char) alphabets[newAlpha]);
   }
//   System.out.println(map);
   mapList.add(map);
   increment++;
  }
 }

 public void possibleDecryptions(String input)
 {
  for(int i=0; i < mapList.size(); i++) {
   System.out.print(i + "= ");
   for(int j = 0; j < input.length(); j++) {
    System.out.print(mapList.get(i).get(input.charAt(j)));
   }
   System.out.println();
  }
 }
 
 public static void main(String[] args) {

  AlphaShift ob =  new AlphaShift();
//  ob.initAlphabet();
//  ob.storePermutations();
//  ob.possibleDecryptions("MXDXBVTZWVMXNSPBQXLIMSCCSGXSC");
  ob.possibleDecryptions("VSRQJHEREVTXDUHSDQWV"); 
 }
}

No comments:

Post a Comment