Skip to content

Instantly share code, notes, and snippets.

@mrmitew
Created September 3, 2023 16:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrmitew/6ab4dfc6824d5c76455e49c33e3c62d7 to your computer and use it in GitHub Desktop.
Save mrmitew/6ab4dfc6824d5c76455e49c33e3c62d7 to your computer and use it in GitHub Desktop.
Caeser Cipher
class CaeserCipherTests {
@Test
fun `should decipher the caeser cipher`() {
val alphabet = arrayOf("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z")
assertThat(alphabet).hasSize(26)
val cipher = "GBKXGMK UXOKTZ TKYZ XKYARZ"
val possiblePlaintexts = mutableListOf<String>()
val buffer = StringBuilder()
for (shift in 1 .. alphabet.size) {
for (char in cipher) {
val substitute = if (char != ' ') {
var letterIndex = (alphabet.indexOf(char.toString().lowercase(Locale.getDefault())) - shift) % alphabet.size
if (letterIndex < 0) {
letterIndex += alphabet.size
}
alphabet[letterIndex]
} else {
' '
}
buffer.append(substitute)
}
possiblePlaintexts.add(buffer.toString())
buffer.clear()
}
assertThat(possiblePlaintexts).containsAnyOf("average orient nest result")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment