transposition cipher

You are currently browsing articles tagged transposition cipher.

This one is a bit more crafty than the simple ROT-13 we worked on earlier and was used for military secrets/communication encryption back in the good ole’ days.


#include <cmath>
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <string>
#include <algorithm>

// pad user input
void pad_message(std::string & message)
    int msglen = message.size();
    int side = static_cast < int >(std::sqrt(msglen));
    if (side * side != msglen) {

    int area = side * side;

    // random number generator

    for (int i = msglen; i < area; ++i) {
	message[i] = static_cast < char >(std::rand() % 26 + 'a');

// print columns
void print_columns(std::string const &message)
    int side = static_cast < int >(std::sqrt(message.size()));

    for (int i = 0; i < side; ++i) {
	for (int j = 0; j < side; ++j) {
	    std::cout << message[side * j + i];

int main()
    char c;
    std::string message;

// gather user input as characters
    while (std::cin >> c) {
	message += c;

// remove whitespaces/punctuation
    message.erase(remove_if(message.begin(), message.end(), isspace), message.end());
    message.erase(remove_if(message.begin(), message.end(), ispunct), message.end());
    message.erase(remove_if(message.begin(), message.end(), isdigit), message.end());

// encrypt

// print out encyphered message
    std::cout << "n";

For example, if we take this segment of lyrics by John Lennon’s “Imagine”:

Imagine there's no heaven
It's easy if you try
No hell below us
Above us only sky
Imagine all the people
Living for today

…and run it through this program, it will spit out the encrypted version:


More info on how Transposition ciphers work.