Caesar Cipher Implementation
The Caesar Cipher is one of the easier ciphers to implement, but also one of the easiest to break. For a description of the Caesar cipher, have a look here. For a guide on how to break the Caesar cipher, see here.
Python Implementation §
The following code is a Python implementation of the Caesar cipher.
# we need 2 helper mappings, from letters to ints and the inverse | |
L2I = dict(zip("ABCDEFGHIJKLMNOPQRSTUVWXYZ",range(26))) | |
I2L = dict(zip(range(26),"ABCDEFGHIJKLMNOPQRSTUVWXYZ")) | |
key = 3 | |
plaintext = "DEFEND THE EAST WALL OF THE CASTLE" | |
# encipher | |
ciphertext = "" | |
for c in plaintext.upper(): | |
if c.isalpha(): ciphertext += I2L[ (L2I[c] + key)%26 ] | |
else: ciphertext += c | |
# decipher | |
plaintext2 = "" | |
for c in ciphertext.upper(): | |
if c.isalpha(): plaintext2 += I2L[ (L2I[c] - key)%26 ] | |
else: plaintext2 += c | |
print plaintext | |
print ciphertext | |
print plaintext2 |
C Implementation §
The following code is a C implementation of the Caesar cipher.
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <ctype.h> | |
int main(int argc, char *argv[]){ | |
char plaintext[] = "DEFEND THE EAST WALL OF THE CASTLE"; | |
int L = strlen(plaintext); | |
char *ciphertext = malloc(sizeof(char)*(L+1)); | |
int i, key = 3; | |
//*****encipher****** | |
for(i=0;i<L;i++){ | |
if(isalpha(plaintext[i])) ciphertext[i] = (toupper(plaintext[i]) - 'A' + key)%26 + 'A'; | |
else ciphertext[i] = plaintext[i]; | |
} | |
ciphertext[i] = 0; | |
char *plaintext2 = malloc(sizeof(char)*(L+1)); | |
//*****decipher****** | |
for(i=0;i<L;i++){ | |
if(isalpha(plaintext[i])) plaintext2[i] = (toupper(ciphertext[i]) - 'A' + 26 - key)%26 + 'A'; | |
else plaintext2[i] = ciphertext[i]; | |
} | |
plaintext2[i] = 0; | |
printf("%s\n%s\n%s\n",plaintext,ciphertext,plaintext2); | |
return 0; | |
} |
JavaScript Implementation §
The following code is a JavaScript implementation of the Caesar cipher. To play with a working version, check here.
// enciphering | |
plaintext = "DEFEND THE EAST WALL OF THE CASTLE"; | |
var key = 3; | |
ciphertext = ""; var re = /[a-z]/; | |
for(i=0; i<plaintext.length; i++){ | |
if(re.test(plaintext.charAt(i))) ciphertext += String.fromCharCode((plaintext.charCodeAt(i) - 97 + key)%26 + 97); | |
else ciphertext += plaintext.charAt(i); | |
} | |
// deciphering | |
plaintext2 = ""; | |
for(i=0; i<ciphertext.length; i++){ | |
if(re.test(ciphertext.charAt(i))) plaintext2 += String.fromCharCode((ciphertext.charCodeAt(i) - 97 + 26 - key)%26 + 97); | |
else plaintext += ciphertext.charAt(i); | |
} | |
alert(plaintext) | |
alert(ciphertext) | |
alert(plaintext2) | |
If you have implementations in other languages or for other ciphers, and you'd like me to post the code here, feel free to leave a comment.