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 old plebe cyber 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 = k_0 k_1 ... k_{n-1}$ of characters.
The shift is the character $sc = 42 + \left( \left( 18 + (k_0-42) + (k_1-42) + \cdots + (k_{n-1}-42) \right) \bmod 81 \right)$
Note: if any $k_i$ 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!

Example: password/key = b8T, plaintext character = X

Derive shift character sc from key = b8T:
----------------------------------	
key = b  8  T 
      k0 k1 k2   ----> 42 + (18 + 98-42 + 56-42 + 84-42) mod 81
      98 56 84              \__________________________/       |
                                       130                     |
                             \_________________________________/ 
                       42 +                     49                =   91 --> [ = sc
Encrypt with shift character sc = [, plaintext character pc = X:
---------------------------------------------------------------
k  = sc - 42 = [ - 42 = 91 - 42 = 49
p  = pc - 42 = X - 42 = 88 - 42 = 46
c  = (p + k) mod 81 = (49 + 46) mod 81 = 95 mod 81 = 14
cc = 42 + c =  42 + 14 = 56 = 8 so char '8' is the ciphertext character