Sei sulla pagina 1di 2

Transposition Cipher (Code Updted Date:10/4/2012)

package transpositioncipher; import com.sun.xml.internal.bind.WhiteSpaceProcessor; import java.util.*; /** * * @author DPK * Dil Prasad Kunwar 'SAMIR' * Email:samir_k2002@yahoo.com * Kathmandu Neal */ public class TranspositionCipher { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here System.out.println("*******TRANSPOSITION CIPHER*******"); Scanner in = new Scanner(System.in); String plainText =""; System.out.println("Enter the plain text:\n"); plainText=in.nextLine(); String cipherText = FindTranspositionCipher(plainText); System.out.println("\nCipher Text:"+cipherText); } //method to convert plain text in to cipher text public static String FindTranspositionCipher(String plainText) { String cipherText=""; //String test ="attack postponed until two am"; int key[]={4,3,1,2}; //remove whitespace plainText = plainText.replaceAll(" ", ""); int nColumn = key.length; //calculates numbers of row required to fill the character int nRow = plainText.length()/nColumn; if(nRow*nColumn<plainText.length()) { nRow +=1; } //holds the position of character in corresponding column

char[][] mat = new char[nRow][nColumn]; int cPosition =0; //fill the matrix with plain text character for(int i=0;i<nRow;i++) { for(int j=0;j<nColumn;j++) { if(cPosition<plainText.length()) { mat[i][j] = plainText.charAt(cPosition); } else { mat[i][j] ='*'; } cPosition++; } } int colIndex=0; //sequentially retrieves the character of each column in ascending order of key for(int a=1;a<=key.length;a++) { for(int k=0;k<key.length;k++) { if(key[k]==a){ colIndex = k; } } for(int i=0;i<nRow;i++) { cipherText +=mat[i][colIndex]; } cipherText +=" "; } return cipherText; }

Potrebbero piacerti anche