Lab 3 - Shift and Affine Ciphers (Jan 31, 2014)

Task 1: Write a function shift(s,k) that takes in a string s and an integer k (the key) and shifts each alphabetic character in s by k mod 26. Return this ciphertext in upper case. Test encryption and decryption for a couple messages and keys of your choice. (Your messages should exclude punctuation, but may include spaces after every 5th character. Your program should not modify the spaces.)

Here are some Python commands that may be helpful, though not all are necessary. You can access each element of a of a string s the same way you would access elements of a list---either for x in s or individually by, e.g., s[5]. Given a character (string of length 1) x, you can obtain the numerical ASCII representation (e.g., 65 for A, 66 for B, etc) with the command chr(x). Then you can go from the ASCII representation y to the character with ord(y). You can also test if a character x (or a whole string) is alphabetic by x.isalpha(). Lastly, you can cover an entire string s to uppercase by s.upper().

Task 2: Write a function all_shifts(s) that takes in a ciphertext s and prints out all possible shifts mod 26 in lowercase, along with the amount of the shift (i.e., the key). (You can convert a string s to lowercase by s.lower().) Use this to decode the message XPPEL EXTOY TRSE.

Task 3: Write a function affine(s,a,b) that takes in a string s and applies the affine shift x -> ax+b mod 26 to each alphabetic character x in s.

Task 4: Write a function affine_dkey(a,b) that takes in an invertible affine shift encryption key (a,b) and returns the coefficients [c,d] of the inverse transformation x -> cx+d mod 26. If x -> ax+b mod 26 is not invertible, display an error message saying this. Using this and the previous task, test affine cipher encryption and decryption of some messages and keys of your choice.

Task 5: Write a function all_affine(s) that prints out all possible invertible affine transformations x -> ax+b mod 26 in lower case, along with the coefficients a and b. Use this to decode the message RMIKZ MNHMO FMGET QKZYH.

Lab 3 Homework (due Fri Feb 7): Complete the above tasks.



Labs Page
Course Home