# CS50x Week 2: Crypto

There is a lot of reading this week. Among the books in the reading list, I would recommend Absolute Beginner’s Guide to C by Greg Perry for beginners, the book is easy to follow and not boring. Programming in C by Stephen G. Kochan is a bit lengthy and harder to follow for beginners, but it is more in depth.

This week’s problem set is more challenging than the previous ones. The challenge is to program cipher programs using the Caesar cipher and Vigenere cipher.

## Caesar cipher

Caesar cipher is a method to cipher text by shifting the characters in the text by a fix number of positions. For example the text “Shaun”, when we apply a Caesar cipher of key 5, the ciphered text will be “Xmfzs”. If however, the character is ‘y’, as in ‘y’ in “Shauny”, the ciphered text will be “Xmfzsd”, looping back to the start of the alphabetical order.

When the program encounters a space or a character that is not alphatical, it will return that character without changing it. Also, uppercase alphabet has to remain uppercase and lowercase alphabet has to remain lowercase. If the key is more than 26, the cipher still works, because it will just loops around the alphabetical order additional times.

The following formula is used to implement the Caesar cipher:

ci = (pi + k) % 26

where pi is the ith character of the text, k is the key, and ci is the ith character of the ciphered text.

Following is my attempt at making a program using Caesar cipher:

## Vigenere cipher

Vigenere cipher is more secure than Caesar cipher because instead of using a single number as key, we have word as key. Each characters in the text will be shifted few positions according to the characters in the key. For example, I have a text “Shaun”, and a key “cat”, the cipher will add the first character of the text, ‘S’ to the first character of the key ‘c’, and ‘h’ to ‘a’ and ‘a’ to ‘t’. The ‘u’ will be added to ‘c’ again, because the key character used is repeated.

Formula for generating Vigenere cipher characters are as follows:

ci = (pi + ki) % 26

where pi is the ith character of the text, ki is ith character the key, and ci is the ith character of the ciphered text.

Following is my attempt at programming Vigenere cipher:

My codes: https://github.com/shaunlgs/CS50x
Other posts in the series: Harvard CS50x 2014