Background

The Caesar-shift Cipher is a simple (and by no means secure) cipher that apparently was used by Julius Caesar. It's very simple and can easily be done by hand. The fundamental operation is to "shift" a letter by some fixed shift-value, which is agreed upon beforehand by the participants. See the si110 symmetric encryption notes for more general-purpose information.

For our purposes, all symbols - whether in the key, plaintext or ciphertext - are characters in the ASCII range 42-122 inclusive. We will represent the shift value by a single character in that same range: 42 is a shift of zero, 43 is a shift of 1, and so on. In the following, we will go back and forth between treating a character as an integer (via ASCII) and integer as a character. In code, you must make explicit casts, like (int)c - 42 or (char)(i + 42).

Derive the shift from the key

The key is a string key = k0 k1 ... kn of characters.
The shift is the character sc = 42 + ( ( 18 + (k0 - 42) + (k1 - 42) + ... + (kn - 42) ) mod 81 )
Note: if any ki has ASCII value outside the range 42-122 it is an ERROR!

Encrypting a plaintext message based on a shift value

Given shift value character sc and a single plaintext character pc, compute ciphertext character cc:
k  = sc - 42
p  = pc - 42
c  = (p + k) mod 81
cc = 42 + c
To encrypt an entire plaintext message, simply use the above to separately encrypt each character of the plaintext.
Note: if any character in the plaintext message is outside of ASCII 42-122 it is an ERROR!

Decrypting a ciphertext message based on a shift value

Given shift value character sc and a single ciphertext character cc, compute plaintext character pc:
k  = sc - 42
c  = cc - 42
p  = (c + (81 - k)) mod 81
pc = 42 + p
To decrypt an entire ciphertext message, simply use the above to separately decrypt each character of the ciphertext.
Note: if any character in the ciphertext message is outside of ASCII 42-122 it is an ERROR!