New Home Old Home Site Map Books Tips & Tricks Tutorials Stories Performance Essays Links Q & A New in VB6 Free Stuff Pictures Awards Received Banners Newsletter Feedback
 Tutorial: One-Time Pad This tutorial explains Caesar substitution ciphers.

## Caesar Substitution

There are many reversible mathematical operations. For example, suppose you add the value K to M to get C:
`    C = M + K`
Then if you know C and K, you can subtract to get M:
`    M = C - K`
Now suppose M is a plaintext message and K is a key. C is the ciphertext of M encoded using the key K. To send the value of M to Betty, Andy adds the key K and sends the result C. Betty subtracts K and recovers M.

This is how a Caesar substitution cipher works. The key is a number. Andy adds the number to each letter in the message. Supposedly Julius Caesar used this technique around 2000 years ago with a key value of 3. In that case, the letter A encodes to A + 3 = D, B encodes to E, and so on. If you reach the end of the alphabet, you wrap around so X + 3 = A, Y + 3 = B, and Z + 3 = C.

## Exercises

1. Decode this message using the key value 3:
`    LFDPH LVDZL FRQTX HUHG`
Solution
2. Decode this message using the key value -5:
```    RCZID IRJMM TJMDI YJPWO MPIDI
XDMXG ZNNXM ZVHVI YNCJP O```
Solution
3. Write a Visual Basic program that encodes and decodes text using Caesar substitution. Hint: You only need one routine that adds an offset to a letter for both coding and decoding.
4. The xor (exclusive "or") operation is also reversible and is easier to implement using a computer. To encode:
`    C = M Xor K`
Now if you Xor the key to C you get:
```    C Xor K = (M Xor K) Xor K
= M Xor (K Xor K)
= M Xor 0 = M```
Write a program that takes a key and file name as inputs. It opens and reads the file, Xors the key value to each byte, and creates an encoded file with extension "x1".

The program should then be able to open the new file and reproduce the original.

5. Rewrite the program from exercise 3 so it uses Xor. The program should handle all visible characters between " " (space) and "~" (tilde).

Note that Xoring some letters may map them to an invisible character like tab or form feed. Be sure to remap the characters so they are all encoded as visible characters.