index | submit | rank | book

caesar – Caesar cipher

Gaius Julius Caesar was a general and dictator of ancient Rome who lived between 100 BC - 44 BC.

Caesar reading a scroll: "Ohw xv phhw qhdu wkh Wkhdwuh ri Srpshb dw vxqgrzq.  Dyh Fdhvdu!"

When writing confidential correspondence, Caesar would encrypt his messages by replacing each letter with the third letter coming after it while wrapping around the end of the alphabet. A would become D; B would become E; C would become F; … X would become A; Y would become B; and Z would become C. To decrypt any messages, the process was reversed.

This encryption method became known as the Caesar cypher. It can be generalized to any shift of alphabet positions: one, two, four, five, etc letters to the right or the left. In this generalization, a positive key k indicates encryption should use the k-th subsequent letter and a negative key -k indicates encryption should use the k-th preceding letter. For example:

In this way, when a text is encrypted with a key k, it can be decrypted with a key of -k. Just flip the signal to decrypt.

Caesar cypher encryption and decryption represented in a circle

One can use the above circles to encrypt or decrypt a text using the Caesar cypher for the keys of 3 and -12 by replacing letters on the outer circle by adjacent letters in the inner circle.

In this exercise, you should write a program that performs encryption and decryption under the Caesar cypher for an arbitrary key k.

Arguments, input and output

Your program will be run with a numeric command line argument k indicating the encryption/decryption key. When k argument is not given as a command line argument, assume it to be 13.

Input will contain several lines containing the text to be encrypted or decrypted using the key k. For each line of input, output should contain the encrypted or decrypted text.

Example input and output 1

With a command line argument of 3, i.e.: ./caesar 3

input.

Dear Julius,
Let us meet near
the Theatre of Pompey
at sundown.
Ave Caesar!

output.

Ghdu Mxolxv,
Ohw xv phhw qhdu
wkh Wkhdwuh ri Srpshb
dw vxqgrzq.
Dyh Fdhvdu!

Example input and output 2

With a command line argument of -12, i.e.: ./caesar -12

input.

Ftq cguow ndaiz raj
vgybe ahqd ftq xmlk pas.
Ftq ruhq najuzs
iulmdpe vgyb cguowxk.

output.

The quick brown fox
jumps over the lazy dog.
The five boxing
wizards jump quickly.

Scoring

Hints

Here are a few tips:

try first: rot13 hello-cmd

try next: brutus

index | submit | rank | book

Copyright © 2020-2023 Rudy Matela
All rights reserved