

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


import system'routines;
import system'math;
import extensions;
import extensions'text;
 
const string Letters    = "abcdefghijklmnopqrstuvwxyz";
const string BigLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const string TestText   = "Pack my box with five dozen liquor jugs.";
const int Key = 12;
 
class Encrypting : Enumerator
{
    int        theKey;
    Enumerator theEnumerator;
 
    constructor(int key, string text)
    {
        theKey := key;
        theEnumerator := text.enumerator();
    }
 
    bool next() => theEnumerator;
 
    reset() => theEnumerator;
 
    enumerable() => theEnumerator;
 
    get()
    {
        var ch := theEnumerator.get();
 
        var index := Letters.indexOf(0, ch);
 
        if (-1 < index)
        {
            ^ Letters[(theKey+index).mod:26]
        }
        else
        {
            index := BigLetters.indexOf(0, ch);
            if (-1 < index)
            {
                ^ BigLetters[(theKey+index).mod:26]
            }
            else
            {
                ^ ch
            }
        }
    }
}
 
extension encryptOp
{
    encrypt(key)
        = new Encrypting(key, self).summarize(new StringWriter()); 
 
    decrypt(key)
        = new Encrypting(26 - key, self).summarize(new StringWriter()); 
}
 
public program()
{
    console.printLine("Original text :",TestText);
 
    var encryptedText := TestText.encrypt:Key;
 
    console.printLine("Encrypted text:",encryptedText);
 
    var decryptedText := encryptedText.decrypt:Key;
 
    console.printLine("Decrypted text:",decryptedText);
 
    console.readChar()
}