Columnar Transposition Cipher
Given a plain-text message and a numeric key, cipher/de-cipher the given text using Columnar Transposition Cipher
The Columnar Transposition Cipher is a form of transposition cipher just like Rail Fence Cipher. Columnar Transposition involves writing the plaintext out in rows, and then reading the ciphertext off in columns one by one.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.
Examples:
Encryption Input : Geeks for Geeks Key = HACK Output : e kefGsGsrekoe_ Decryption Input : e kefGsGsrekoe_ Key = HACK Output : Geeks for Geeks Encryption Input : Geeks on work Key = HACK Output : e w_eoo_Gs kknr_ Decryption Input : e w_eoo_Gs kknr_ Key = HACK Output : Geeks on work
Encryption
In a transposition cipher, the order of the alphabets is re-arranged to obtain the cipher-text.
- The message is written out in rows of a fixed length, and then read out again column by column, and the columns are chosen in some scrambled order.
- Width of the rows and the permutation of the columns are usually defined by a keyword.
- For example, the word HACK is of length 4 (so the rows are of length 4), and the permutation is defined by the alphabetical order of the letters in the keyword. In this case, the order would be “3 1 2 4”.
- Any spare spaces are filled with nulls or left blank or placed by a character (Example: _).
- Finally, the message is read off in columns, in the order specified by the keyword.
Decryption
- To decipher it, the recipient has to work out the column lengths by dividing the message length by the key length.
- Then, write the message out in columns again, then re-order the columns by reforming the key word.
C++
// CPP program for illustrating// Columnar Transposition Cipher#include<bits/stdc++.h>usingnamespacestd;// Key for Columnar Transpositionstringconstkey ="HACK";map<int,int> keyMap;voidsetPermutationOrder(){// Add the permutation order into mapfor(inti=0; i < key.length(); i++){keyMap[key[i]] = i;}}// Encryptionstring encryptMessage(string msg){introw,col,j;string cipher ="";/* calculate column of the matrix*/col = key.length();/* calculate Maximum row of the matrix*/row = msg.length()/col;if(msg.length() % col)row += 1;charmatrix[row][col];for(inti=0,k=0; i < row; i++){for(intj=0; j<col; ){if(msg[k] =='\0'){/* Adding the padding character '_' */matrix[i][j] ='_';j++;}if(isalpha(msg[k]) || msg[k]==' '){/* Adding only space and alphabet into matrix*/matrix[i][j] = msg[k];j++;}k++;}}for(map<int,int>::iterator ii = keyMap.begin(); ii!=keyMap.end(); ++ii){j=ii->second;// getting cipher text from matrix column wise using permuted keyfor(inti=0; i<row; i++){if(isalpha(matrix[i][j]) || matrix[i][j]==' '|| matrix[i][j]=='_')cipher += matrix[i][j];}}returncipher;}// Decryptionstring decryptMessage(string cipher){/* calculate row and column for cipher Matrix */intcol = key.length();introw = cipher.length()/col;charcipherMat[row][col];/* add character into matrix column wise */for(intj=0,k=0; j<col; j++)for(inti=0; i<row; i++)cipherMat[i][j] = cipher[k++];/* update the order of key for decryption */intindex = 0;for( map<int,int>::iterator ii=keyMap.begin(); ii!=keyMap.end(); ++ii)ii->second = index++;/* Arrange the matrix column wise accordingto permutation order by adding into new matrix */chardecCipher[row][col];map<int,int>::iterator ii=keyMap.begin();intk = 0;for(intl=0,j; key[l]!='\0'; k++){j = keyMap[key[l++]];for(inti=0; i<row; i++){decCipher[i][k]=cipherMat[i][j];}}/* getting Message using matrix */string msg ="";for(inti=0; i<row; i++){for(intj=0; j<col; j++){if(decCipher[i][j] !='_')msg += decCipher[i][j];}}returnmsg;}// Driver Programintmain(void){/* message */string msg ="Geeks for Geeks";setPermutationOrder();// Calling encryption functionstring cipher = encryptMessage(msg);cout <<"Encrypted Message: "<< cipher << endl;// Calling Decryption functioncout <<"Decrypted Message: "<< decryptMessage(cipher) << endl;return0;}Python3
# Python3 implementation of# Columnar Transpositionimportmathkey="HACK"# EncryptiondefencryptMessage(msg):cipher=""# track key indicesk_indx=0msg_len=float(len(msg))msg_lst=list(msg)key_lst=sorted(list(key))# calculate column of the matrixcol=len(key)# calculate maximum row of the matrixrow=int(math.ceil(msg_len/col))# add the padding character '_' in empty# the empty cell of the matixfill_null=int((row*col)-msg_len)msg_lst.extend('_'*fill_null)# create Matrix and insert message and# padding characters row-wisematrix=[msg_lst[i: i+col]foriinrange(0,len(msg_lst), col)]# read matrix column-wise using keyfor_inrange(col):curr_idx=key.index(key_lst[k_indx])cipher+=''.join([row[curr_idx]forrowinmatrix])k_indx+=1returncipher# DecryptiondefdecryptMessage(cipher):msg=""# track key indicesk_indx=0# track msg indicesmsg_indx=0msg_len=float(len(cipher))msg_lst=list(cipher)# calculate column of the matrixcol=len(key)# calculate maximum row of the matrixrow=int(math.ceil(msg_len/col))# convert key into list and sort# alphabetically so we can access# each character by its alphabetical position.key_lst=sorted(list(key))# create an empty matrix to# store deciphered messagedec_cipher=[]for_inrange(row):dec_cipher+=[[None]*col]# Arrange the matrix column wise according# to permutation order by adding into new matrixfor_inrange(col):curr_idx=key.index(key_lst[k_indx])forjinrange(row):dec_cipher[j][curr_idx]=msg_lst[msg_indx]msg_indx+=1k_indx+=1# convert decrypted msg matrix into a stringtry:msg=''.join(sum(dec_cipher, []))exceptTypeError:raiseTypeError("This program cannot","handle repeating words.")null_count=msg.count('_')ifnull_count >0:returnmsg[:-null_count]returnmsg# Driver Codemsg="Geeks for Geeks"cipher=encryptMessage(msg)print("Encrypted Message: {}".format(cipher))print("Decryped Message: {}".format(decryptMessage(cipher)))# This code is contributed by Aditya K
Output:Encrypted Message: e kefGsGsrekoe_ Decrypted Message: Geeks for Geeks
Try it yourself: A double columnar transposition( It was used by the U.S. Army in World War I, and it is just a columnar transposition followed by another columnar transposition).
This article is contributed by Yasin Zafar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



