

Task

Implement a Caesar cipher, both encoding and decoding. 

The key is an integer from 1 to 25.

This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).

The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).

So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".

This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.

Caesar cipher is identical to Vigenère cipher with a key of length 1. 

Also, Rot-13 is identical to Caesar cipher with key 13.



Related tasks

 Rot-13
 Substitution Cipher
 Vigenère Cipher/Cryptanalysis


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
 
#define caesar(x) rot(13, x)
#define decaesar(x) rot(13, x)
#define decrypt_rot(x, y) rot((26-x), y)
 
void rot(int c, char *str)
{
	int l = strlen(str);
 
        const char*  alpha_low  = "abcdefghijklmnopqrstuvwxyz"; 
 
        const char*  alpha_high = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
 
 
       char subst;  /* substitution character */
       int idx;    /* index */
 
         int i; /* loop var */
 
	for (i = 0; i < l; i++)  /* for each letter in string */
	{
		if( 0 == isalpha(str[i]) )  continue; /* not alphabet character */
 
                idx = (int) (tolower(str[i]) - 'a') + c) % 26; /* compute index */
 
		if( isupper(str[i]) )
                    subst = alpha_high[idx]; 
                else
                    subst = alpha_low[idx]; 
 
               str[i] = subst;
 
	}
}
 
 
int main(int argc, char** argv)
{
	char str[] = "This is a top secret text message!";
 
	printf("Original: %s\n", str);
	caesar(str);
	printf("Encrypted: %s\n", str);
	decaesar(str);
	printf("Decrypted: %s\n", str);
 
	return 0;
}