vendredi 1 août 2014

A coding exercise: The Caesar’s Cipher

 

As one of my holidays book is “Digital Fortress” from the very well-known Dan Brown (he is the author of “The Da Vinci code”) I found interesting to implement by my self some of the message encryption method he describe in that book.

 

To describe a bit the story, the “Digital Fortress” in an unbreakable cipher and it’s potential availability is a cataclysm for the NSA. And in its introduction the author present the NSA and what the crypto science is.

 

He say that the “Caesar’s Cipher” was one of the first known ciphering technic. And after looking Wikipedia it looks like the method he described wasn’t the same. The “Caesar’s Cypher” is typically a method based on a fixed alphabet shift, but he talked about a box based method using a “magic square” (search for the “Caesar’s box cipher”).

My code is really simple, in the first implementation I made I just represented spaces by ‘_’ but you can also choose to remove all spaces using:

inputMsg.erase(remove(inputMsg.begin(), inputMsg.end(), ' '), inputMsg.end());

The trick is to find the root X of the message length and after you draw a square of X*X, write your message character by character (1 per cell) from the top-left corner to bottom-right corner and transpose the table.

auto inL = inputMsg.size();
auto sqrtInL = (unsigned int)(sqrt(inL) + .5);
auto codeL = sqrtInL * sqrtInL;

out = string(codeL, '_');
for(auto ui = 0 ; ui < sqrtInL ; ++ui) {
for(auto = 0 ; uj < sqrtInL ; ++uj) {
if(ui*sqrtInL+uj < inL) {
out[uj*sqrtInL+ui] = (in[ui*sqrtInL+uj] != ' ') ? in[ui*sqrtInL+uj] : '_' ;
}
}
}

Aucun commentaire :

Enregistrer un commentaire