Write a program that takes two lines of input and uses the first as a key phrase to encrypt the second according to the Playfair encryption technique.
Wikipedia describes Playfair encryption in some detail, but to avoid any ambiguity, here's a brief summary:
1. Generate a key table:
Replace all occurrences of J
in the key phrase with I
, then strip all non-alphabet characters and repeated characters. Insert into a 5×5 encryption table, filling the remaining cells with the rest of the alphabet (except J
; we don't like J
).
Example:
S T A C K
O V E R F
Stack Overflow --> STACKOVERFLW --> L W B D G
H I M N P
Q U X Y Z
2. Prepare the message to be encrypted
Replace every J
with an I
, strip all non-alphabet characters and split into pairs, using an X
to break any pairs that contain the same letter twice. If you end up with an odd number of letters, add X
at the end. (Note: Numerals have to be spelt out in full — ONE
, TWO
, THREE
, etc. — but you can assume this has already been done for you.)
Example:
In:
The cat crept into the crypt, crapped, and crept out again.
Out:
TH EC AT CR EP TI NT OT HE CR YP TC RA PX PE DA ND CR EP TO UT AG AI NX
3. Encryption
Encrypt each pair of letters in turn. If they are in different rows and columns of the key table, replace each with the letter from the same row in the column where the other letter is found (e.g., VM
⇒EI
, LZ
⇒GQ
). If they are in the same row (or column), choose the two characters immediately to the right (or below), wrapping around if necessary (e.g., OE
⇒VR
, ZG
⇒KP
).
Example:
In:
TH EC AT CR EP TI NT OT HE CR YP TC RA PX PE DA ND CR EP TO UT AG AI NX
Out:
SI RA CA RD FM VU IC VS MO RD ZN AK EC MZ MF BC YN RD FM SV TV KB TM MY
The string produced by this process is the encrypted message, which your program should output.
Rules:
- The input text and key may be obtained from
stdin
, command line arguments or other such sources. Hard-coded input is not allowed. - Your program must accept both upper and lower case text for the pass phrase and message.
- The encrypted output may be upper or lower case.
- Your program should accept key phrases of at least 64 characters in length, and message texts of at least 16 KB.
- You are not required to handle non-ASCII input.
- You may ignore the possibility of the letter pair
XX
occurring during encryption. - There is no need to add whitespace to the output of the program.
- Your answer should include an example of a message, key phrase and encrypted output produced by your program.
- This is a code golf challenge, so the answer with the shortest code (in bytes) will win.
NOTE: Please remember that you only need to break consecutive letters if they appear in the same pair. So for example
MASSACHUSETTS
should be encrypted asMA SX SA CH US ET TS
— the doubleS
has to be split, but the doubleT
doesn't.
J
" Do you harbour similar sentiments about APL? \$\endgroup\$