A Caesar cipher, or a shift cipher, is one of the most well known encryption techniques. It works by substituting the letters in the message with letters some fixed number of positions down the alphabet.
Your challenge is to write a function that will accept a string and a shift key. It will return the encrypted text. If something in the string is not in the alphabet (e.g. punctuation, spaces) leave it as is.
key: 1
plain: defend the east wall of the castle
cipher: efgfoe uif fbtu xbmm pg uif dbtumf
Bonus
Write a function that will crack the cipher without knowing the shift. The shift key can only be in range of [1, 26].
key: 3
cipher: dwwdfn iurp wkh zrrgv dw gdzq
plain: attack from the woods at dawn
I've used the brute-force method before (printing every possible key and manually searching for the right one). I can't wait to see other solutions to cracking this easy cipher.
Good luck!
Want to propose a challenge for a future post? Email yo+challenge@dev.to with your suggestions!
Top comments (14)
Here we go:
Without any proper dictionary, I guess I'll stick to the "bruteforce" method! Here's how it works:
[...Array(26)].map((_,i)=>26-i)
)26-n
) and the cipher (s
)I’m learning Erlang and I love it.
My solution for cracking the message tries all keys, performs frequency analysis on each result, and sorts the candidates by closeness to the frequencies of letters in the English language.
To try:
Of course, instead of decrypting the message 25 times, I should perform frequency analysis, shift the keys of the map 25 times, take the three shortest distances and then decrypt the message with the corresponding keys. I’ll update my solution later.
JavaScript
I imagine that for now, the only way to decypher a phrase would be to check each word to verify that it is valid using either a dictionary or an API. Which may be a pain.
A thing that is not going to work now, but maybe it could work in the future (big "maybe" here, but bear with me for a second):
It would be super hacky, but it would allow us to use the browser dictionary (if it's not open already, in which case, we should use it) instead of having our own dictionary or having to call an API.
Unfortunately,
::grammar-error
and::spelling-error
are not currently supported by any browser, so I cannot test this crazy idea at the moment.C#
Rept.it
C++
My solution in js
Ruby
Using English frequency analysis (but you actually need to know the language source), here is a javascript version:
You'll get results sort by entropy score:
JavaScript
ruby <3