Back
Close

Playfair Cipher

Statement

 Goal

Edith and Norman have decided to encrypt all of their messages through 'Playfair cipher'. While Norman can encrypt and decrypt on his own, Edith asks for your help with the process. Now you and Edith are both on your desk figuring it out.

This encryption method requires the use of a key table - a grid of 25 alphabets in a 5 × 5 square.

Example:
A B C D E
F G H I K
L M N O P
Q R S T U
V W X Y Z

In Playfair cipher the message is split into digraphs, pairs of two letters, and then encrypted by following these rules in order:

1) If the letters appear on the same row of your table, replace them with the letters to their immediate right respectively. (Also applies for the cases with same letters)

Example:
A B C D E
F G H I K
L M N O P
Q R S T U
V W X Y Z
Message: MO
Output: NP

2) If the letters appear on the same column of your table, replace them with the letters immediately below respectively.

Example:
A B C D E
F G H I K
L M N O P
Q R S T U
V W X Y Z
Message: GR
Output: MW

Note: In cases where letters are at the edges, replace the value of the key whose isn't present, with the key that is at the start of the row/column (according to the rules given).

Example:
A B C D E
F G H I K
L M N O P
Q R S T U
V W X Y Z
Message: CE BW
Output: DA GB

3) If neither of the preceding two rules is true, form an imaginary rectangle with the two letters as edge points. Then, replace them with the letters on the same row respectively but at the other pair of corners of the rectangle. The order is important – the first letter of the encrypted pair is the one that lies on the same row as the first letter of the plaintext pair.

Example:
A B C D E
F G H I K
L M N O P
Q R S T U
V W X Y Z
Message: GT
Output: IR

In addition, Norman has also created some additional rules to increase credibility:
- If the letters in the message are in lower case, they are supposed to be changed to their respective upper case.
- If all the letters cannot be kept in pairs, the message is a dud.
- Any characters that are not present in the key table are ignored from the message.

For decryption, you simply do the process in reverse.

If you wish to understand it further, here is a link: https://en.wikipedia.org/wiki/Playfair_cipher
Input
Line 1 - 5: The 5 rows of the key table where letters are space-separated.
Line 6: The action to be preformed, ENCRYPT or DECRYPT.
Line 7: N, the number of messages to read.
The following N lines: Each line contains a message.
Output
N lines: Each message after decryption or encryption. In the case where the message is a dud, print out DUD as output.
Constraints
0 < N < 50
0 < size of each message < 200
Example
Input
A B C D E
F G H I K
L M N O P
Q R S T U
V W X Y Z
ENCRYPT
1
HK
Output
IF

Tags
Cryptography

Difficulty
Medium

Test cases
Row Test
Input
A B C D E F G H I K L M N O P Q R S T U V W X Y Z ENCRYPT 1 HK
Output
IF

Row Validator
Input
A F K P U B G L Q V C H M R W D I N S X E J O T Y ENCRYPT 4 GQ CMDX EYTJ NNQL
Output
LV HRID JEYO SSVQ

Column Test
Input
A B C D E F G H I K L M N O P Q R S T U V W X Y Z ENCRYPT 1 GR
Output
MW

Column Validator
Input
A F K P U B G L Q V C H M R W D I N S X E J O T Y ENCRYPT 3 FJ KKKL QRCE
Output
GF PPLM RSDA

Row and Column Test
Input
A Y E I C O W P S Q B L K D F J G M T U H N R V X ENCRYPT 3 MY COOL SAFE
Output
GE AQWB OIKC

Row and Column Validator
Input
A Y E I C O W P S Q B L K D F J G M T U H N R V X ENCRYPT 3 WHATISLIFE CODINGISSFUN ANAPPLEADAYKEEPSTHEDOCTORAWAY!@#
Output
ONIJSDDYKC AQTSYNSDQDGX DUD

Invalid characters Test
Input
L X E C H P W U S R T Q K D F J Z M B O I N G V Y ENCRYPT 4 MeetM3atN00n Andy_loved_to_sleep_on_a bed_of_nails. his/7-layer/cake/only/had /6/layer$. N0b0dy*l0ves*a*p1g*wearing*l1pst1ck.
Output
GULKJKGG VQIHBYCKFJPCCCRJVZCKYOGNCP LYPCGHSHMUZYHICFHIHU VZFVCICUUIUXPYGVPTPDED

Invalid characters Validator
Input
A X E I H O W U S Q T R K D F J G M B P C N L V Y ENCRYPT 3 ###While on the first date he accidentally hit his head on the beam. -When I cook spaghetti, I like to boil it a few minute past 'al dente' so the noodles are super slippery. What is 2 + 1 ? //Isn't it three haha. I am just messing with you:)
Output
QXEVAUCRAIDHDWRFOJIAIXNNSBXLJOVVHQADAHQIIXTSCRAIMIEJ QXXLAVWWDUJHPXAKDAEVEDAKSJSAVEJOKHUGXVOKHMIOJOVKXLKAQWFAXLWWKVIUXTIUQMXKUVHBMHFN QXOJSDSDCRADFAKXIAXAXHEJMOODLUQQXVNRADQHWS

Decryption Test
Input
W Q E A H P Y O S U T C B D F R N M K L I V G X J DECRYPT 4 WPQKBRJRRDSBQS BSOSSLMYPRWASWDDEPKT DQVCSPXVGQGOOSPLSDPXMVGORC FWHBSGQHYDYLRVMV
Output
IWANTMILKTODAY DOYOUKNOWTHEPABBWORD CANYOUGIVEMEYOURASSINGMENT THEFOXWASCUNNING

Decryption Validator
Input
U V E A H P Y O S J T C B D F R Z M K L I N G X W DECRYPT 8 NIPEKFMOBARWWEBUTXTCUAOAHXUMHBHRMJTBVTERMOLPPUBV JAHBPEX/////CUWYDBGJRUBABHRZWAOPXICUMAORUGX UWPARFGRUDABMUEKDHICSDCZYGPXPDABJBmON???GNBYGBUICSDGHWWSDJKOOTUGX???UGWEFUPEKPNGUKJG FUVBMJDZINFUNGFUXPFMBEVXFCUA#$%@FZYBMS13241324GZJZUSBPSUMUEJPITXLL!@#$!UMVGCTMPGOVDEJFUUM OSPIXNZRTLGUXCMBEIUFOSPIDHEYIUBUBY#$%@@SMGUTZXPYTUM$%AHKJTECTPMEBRRBEUBRGRL FUUMNUUMPDJMUBUAEBKD!@34 FUHBXPJWXPWBUGVTXICVGFRPCJGUHRRUATLBEUHFCSJVS UAGJMUFUAOPIXNDVRKSDRXIYETRWZVPB--===BPMAUOTLBGDVCBUWGXHEUIA@$PTERRSMOOTTOBJRAHXHJCMPLEGR
Output
IWOULDBEDELIGHTEDIFTHESEAWEREFULLOFCUCUMBERJUICE SHEFOUNDHISCOMPLETEDULLNESSINTERESTING HISULTIMATEDREAMFANTASYCONSISTEDOFBEINGCONTENTASWEXXASSLYYPINGEIGHTHOURSINAROW THECLOCKWITHINTHISBLOGANDTHECLOCKONMYLAPTOPAREHOURDIKKERENTFROMEACHOTHER YOURGIRLFRIENDBOUGHTYOURFAVORITECOOKIECRISPCEREALSBUTFORGOLLOGETMILK THERIVERSTOLETHEGODS DUD HEWORETHESURGICALMASKINPUBLICNOTTOKEEPFROMCATCHINGAVIRUSBULLOKYYFFEOPLEAWAYFROMHIM

DUD Test
Input
G Q N I H P Y O S U T C B D F K E M R L A V W X J ENCRYPT 4 uwu OPYTNPSWMYDQPOC fadsf FASD asudsd32q39.xcfsdUIBFSAFIQ;SDFA.FSASFQWFAw UUEscaswnc aisduf awoef adsfnaf0821.asdf oadfw
Output
DUD DUD TJRDTTXPTXUPRDCIVDDUFSNDDUJTHNDRTJDUXPCHJBVX DUD

DUD Validator
Input
G Q N I H P Y O S U T C B D F K E M R L A V W X J ENCRYPT 10 uwuuwu OPYTNqvP23sadf.adsfSWMYDQPOCadsqvqfadsfasq fadsadsvfasdjewergvf FASD asdfasudasdvsdasd32q39.xcfsdUIBFSAFIQ;SDvFA.FSASFQWFAwasdfsad UUEscaswnc aisduf awoef adsfnaf0821asdvasvdasdva.asdf oadfwsdvasdvas asdvasdvwreva adfasidf asdf98q fqndv9q faodisfhas df9qwee fqwof asdofqhdf3490fsmapdfy1 vsldvasd pqwwr;a/avoajs;dg'2efaj0pgas akdnfao8324l faofh3200ja dfh923q2na;v/asgpjq3q;4t0.aga asdfionadsfioandfadsf 34t0jqwgnq92tnlqf sdfownm39/vow[weg]]dfgds i3ongodaf./[bhelgweg aogw9[sbv/vsfogewng
Output
OJPPJO DUD TJRDXTYXTJDRVLVMKIJCTJDRXPFTXPSFXPCXDRXPCIVDDUFSNDDUJTHNDRJCJTPXUDNVTJXVDRDUXT DUD DUD DUD DUD DUD DRBUNOEWBNVMITTHRD NSIQSBJTFNMKNAKQWPNAODWWUDPNMVIQ

Some Messages Test
Input
O X E A H P W U S J T C K D F R Z M B L I N G V Y DECRYPT 5 FOAUBEYYJXORAMPEVJBEMTAKFOHMXTODOPIXLJWGTBAKPATKBORSPR FOOKPIRPVPHUKGUOTVICPROABHMUPNFOTBAHBUHTMATXRGGVSDAHKPIRMH OAPXJMTAYZVJPMYNGAYTOAMUTRFOHKOIUEPOGVXVFAXKEPBFOAOBFOWGKAIOICOATVPDXVKX OYKRXUORJHEPITOKJAOBDU IHPMAHRYMXIHPMXGPRHBXIAHJVEPPVROGIEPZLAKIPERBEDDEVNGVIEPZTHBGADSTCOMHBXIVKHVHTJRHVNGIKKEHTSXZPOREYBOVCSOPHOGICOAOXJWORHB//
Output
THESMAVVWHITEBUOYSMARKEDTHELOCATIONOFHUNDREDSOFCRABPOT THETORTOISEJUMPEDINTOTHELAKEWITHDREAMSOFBECOMINGASEATURTLE HEWOULDONLYSURVIVEIFHEKEPTTHEFIREGOINGANDHECOULDHEARTHUNDERINTHEDISTANCE HITMEWITHYOURPETSHARKS YOUREALIZEYOURENOTALONEASYOUSITINYOURBEDROOMMAKKAGINGYOURCALVESAFTERALONGDAYOFPLAYINGTUGOFWARWITHGRANDPAJOEINTHEHOSPITAL

Some Messages Validator
Input
F Q W I T D Y A G U H J B P M K E V R N O X L S C ENCRYPT 16 Sometimes you have to just give up and win by cheating. Nobody questions who built the pyramids in Mexico. Seek success, but always be prepared for random cats. Just go ahead and press that button. After exploring the abandoned building, he started to believe in ghosts. They're playing the piano while flying in the plane. He drank life before spitting it out. Nobody loves a pig wearing lipstick. Hit me with your pet shark! The fish listened intently to what the frogs had to say. She couldn't decide of the glass was half empty or half full so she drank it. The paintbrush was angry at the color the artist chose to use. Getting up at dawn is for the birds. It was a really good Monday for being a Saturday. The shark-infested South Pine channel was the only way in or out. The trick to getting kids to eat anything is to put catchup on it.
Output
CXJNFTJNXGCDBDRVFCMYCIPGRVGMUVAFTRJAOMVYFTRU KCHLYATYRXFTCKLIKFMAWSFFJKJGVGPTGOTRJNSQOX DUD DUD DWQNNVSJSXSGRUFMVYVBKUCKKYMAWSGFRUJKCIGVQNUFLHVXQRRVTRDPXCIC FMXJNVBSGATRUIJKRGUVLFPFXVWOGQRUTRFMRJWBKV JKGKUVVOTQVJKQSKRXRGFFTRPGFCMU KCHLYASXRVLGRGAIVYSGRUSWRIFTON DUD DUD OPNXCDOACUYKSTYKFDFMRYWBCCABOPBWQKHMQUSKBDOWTDSSCXOPKYVGKETF FMRJGWCUPVGCBFGLUVPSAGFFJKOXSXNIJKGVFTCIOMXCNQCDXR YRFFTRUDBGFUBARTOISKFMVJGSGO DUD FMRXBDNETRQKCIKYCXMUJMTRNXBDKKVXABCIJKCKXAABGQKCKSMU FMNQSGONFCYRFFTRDRFGCIXKUWUVUQPFRUGIFCMGUTUWOMGMCKTF

More Messages Test
Input
M Q N I H D Y A X U T C B P F K E V R W O G L S J ENCRYPT 30 She borrowed the book from him many years ago and hasn't yet returned it. The door slammed on the watermelon. When he had to picnic on the beach, he purposely put sand in other people’s food. Nobody has encountered an explosive daisy and lived to tell the tale. I love eating toasted cheese and tuna sandwiches. Garlic ice-cream was her favorite. He had unknowingly taken up sleepwalking as a nighttime hobby. It was a slippery slope and he was willing to slide all the way to the deepest depths. The snow-covered path was no help in finding his way out of the back-country. When money was tight, he'd get his lunch money from the local wishing well. She did a happy dance because all of the socks from the dryer matched. He walked into the basement with the horror movie from the night before playing in his head. Abstraction is often one floor above you. Red is greener than purple, for sure. Everyone was curious about the large white blimp that appeared overnight. Dan took the deep dive down the rabbit hole. That was how he came to win $1 million. Italy is my favorite country; in fact, I plan to spend two weeks there next year. Her life in the confines of the house became her new normal. She was too short to see over the fence. They say that dogs are man's best friend, but this cat was setting out to sabotage that theory. He stepped gingerly onto the bridge knowing that enchantment awaited on the other side. A song can make or ruin a person’s day if they let it get to them. He looked behind the door and didn't like what he saw. He had decided to accept his fate of accepting his fate. The beauty of the African sunset disguised the danger lurking nearby. The mysterious diary records the voice. It's much more difficult to play tennis with a bowling ball than it is to bowl with a tennis ball. He invested some skill points in Charisma and Strength. It was a really good Monday for being a Saturday.
Output
JIVCSKKSKVTKQWTLMOPWMDMHQQBAAAVYSIYLLDMANULICDKCWVFDVIKYMP DUD DUD DUD DUD LYVSQPQPGEWVDNVUJIVWBUKLSXCK QWNUYDMVMLRHQLGABDEVHARIGVRCVUOVHILYLXIHJQCCHQWQLTCA MPVULXJSXRCREXJSSTVYMAQWVUJRNSSNQLKMJSMXVYSSFMVKXAKMFMKYVVCROPYKFCIJ DUD DUD JIKYMXUNXBCXYXQBVCGEXDGRBNSGTCQWJGTEJPKSDKQWXKCGKIDBFQKY DUD BVOPVXBCMSIHJGTCVQLMWCSGSKBVLKGCJD DUD VRVWDGQVVUGPXWMSXJBVJDCCQWNBESVKMHCKVNHQFCNUBDFFVYWVTMRVVIQSMF DUD FMDBVUJIJKQWBYQKKMRHIQNSSNLM DUD QWVSHPRQMBQWTGHBHIRGJTFMWQJDGRCVBYQKQWVIVKMLKIBN DUD DUD DUD DUD QWSGMOKYCVMHMAFMKYGGVXMAXMAMBOMRVKNUFMRGUV DUD FMVCVYDFDGTCQWUBSXBYILAHGRKTXIJYXIKYFMKYBAQGVSXWRMQLQVXVCA DUD DUD QWHIRVOPKYJGQKORNSSBSMMBIXQBNUSXOIXXMAOPWVQLFM DUD

More Messages Validator
Input
Z Q E F H P Y O S U T C B D A R N M K L I V G X J DECRYPT 35 TEKBVAAbek2tYM9ZkaaOT5wSqiGYIbeG0ouJNgAq ypYm6k7WejIDMRnSCaomL5O4VdEeEtGjVXqQqiCk JeY2RcCRKGoQyMG8N4rtQFoeXd3otQ5J4wQI0m2q HklTboTJrzLHraO2mu3EtHPHbJvFgrGCIXff5p5v kXTDWqFazJpINjD5pPWM3hulCqjxgOqDxarg2VSi wHYqdJkUdogw6Yb5MfEhehJII4oE317MJAgisYg8 eavHQ3QGma0GrZh72YwrVuGMrxnkqISuvXGPbk4e k8I6qZi7vKhHHrxdHeYnIJtulwPsietzoeZD6oTE f0EThLpL7wtCUESeMBKiVrV9nMoe8kRrexixCZkh 1Vd4ZBBDOiBGdRAPUaPqhok3ktJeUUitLNebAvXr 6uWjbcU650q5XMySA7TFLTnVzWwiBCPbwaANOENu ngOsuknZ6A57KxYNiPBP0FfKl973Drm7yoRCESOb 9waR2IXxKbIK48KhszEdRzj6OmDwSoFB1z92Ko7E gREItxFiCn869FpvdJFzABSRvCuFkXw2sf4BHv8q Gyfg3Hiu7XPR0oxr5xrgPA4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BDVKKGRLYJHOTFQCXXHZJIAJ PSOGCFHZXHRSCZRGSDTCAAGVARAOKYQT UQDSONMCLBQTYMRMTGLHVVDQTPEPUJBHNQ DUD DYERMBSFXXXAOFRJGYKEREHESRJIOQCI PAGPEIXYBDRIGDCDXIBSFRGGCKSKDHBGJQ RXUJTJMGCQYSEFMEUNJMCGLZYQDBFYBC DUD DUD NVXKRKUFPMTPSKEZSUQGYNQCNTMHGZMQYF IAYMTCITHFBUQGOEGEBSRNLMHMQMUBJVNBGVFS XJGHCYZUZGQYRODLQRPCTXQJTLACCMCL DUD CZAQTUFNISKYUTPMTRZONIPQAYCENZKCHU

Solution language

Solution

Stub generator input