
Rotating Grille Cipher
This is the third mission on classical cryptography. In this mission we will encrypt a message using a rotating grille.
Rotating grille cipher is a transposition cipher that uses a special square sheet of cardboard (the grille ) with holes cut in it. To encrypt a message, sender must place the grille on an empty sheet of paper and write letters of the plaintext into the holes left to right, top to bottom. After filling all the holes, the grille is rotated 90 degrees clockwise (the holes move to empty spaces) and the process continues. After the grille was rotated 2 more times, there should be no empty spaces on the paper; if the message is not finished, the algorithm is repeated on the next sheet.
For example, here's what encrypting the line Meet me at twelve PM would look like (we'll use a grille of size 4x4):
After the encryption, the ciphertext reads as tmmveeewepeatlmt .
In this task you are given a message and a key (4x4 square grille); length of the message is divisible by 16. You need to encrypt a message with the rotating grille cipher. There is a problem, though: some of the keys are defective. A "correct" key is made in such a way that, when laid over a grid and rotated around, every cell is shown exactly once. So with defective keys, either some cells are shown more than once, or after applying the key in all four directions there are still unfilled spaces on the sheet. See examples of bad keys below:
If the key is correct, return encrypted message; if the key is defective - return None.
Input: plaintext: str, grille: list of str (positions of holes are marked by "Х" )
Output: ciphertext: str or None
Example:
grille_encrypt('cardangrilletest', ['.X..', '.X..', '...X', 'X...']) == 'actilangeslrdret' grille_encrypt('quickbrownfoxjumpsoverthelazydog', ['X...', '...X', '..X.', '.X..']) == 'qxwkbnjufriumcoopyeerldsatoogvhz' grille_encrypt('quickbrownfoxjumpsoverthelazydog', ['.XX.', '.XX.', '..X.', 'X...']) == None grille_encrypt('cardangrilletest', ['...X', '....', '....', '....']) == None
Preconditions:
len(key) == 4
all(len(l) == 4 for l in key)
len(plaintext) % 16 == 0
all(all(cell == "X" or cell == "." for cell in line) for line in key)
PS: If you are interested in decryption of a Rotating Grille Cipher, check out mission Cipher Map .