

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


with Ada.Text_IO;
 
procedure Caesar is
 
   type modulo26 is modulo 26;
 
   function modulo26 (Character: Character; Output: Character) return modulo26 is
   begin
      return modulo26 (Character'Pos(Character)+Character'Pos(Output));
   end modulo26;
 
   function Character(Val: in  modulo26; Output: Character)
                        return Character is
   begin
      return Character'Val(Integer(Val)+Character'Pos(Output));
   end Character;
 
   function crypt (Playn: String; Key: modulo26) return String is
      Ciph: String(Playn'Range);
 
   begin
      for I in Playn'Range loop
         case Playn(I) is
            when 'A' .. 'Z' =>
               Ciph(I) := Character(modulo26(Playn(I)+Key), 'A');
            when 'a' .. 'z' =>
               Ciph(I) := Character(modulo26(Playn(I)+Key), 'a');
            when others =>
               Ciph(I) := Playn(I);
         end case;
      end loop;
      return Ciph;
   end crypt;
 
   Text:  String := Ada.Text_IO.Get_Line;
   Key: modulo26 := 3; -- Default key from "Commentarii de Bello Gallico" shift cipher
 
begin -- encryption main program
 
   Ada.Text_IO.Put_Line("Playn ------------>" & Text);
   Text := crypt(Text, Key);
   Ada.Text_IO.Put_Line("Ciphertext ----------->" & Text);
   Ada.Text_IO.Put_Line("Decrypted Ciphertext ->" & crypt(Text, -Key));
 
end Caesar;