-
Notifications
You must be signed in to change notification settings - Fork 0
/
3A_CaesarCipher.kt
48 lines (38 loc) · 1.06 KB
/
3A_CaesarCipher.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package ciphers
/**
* The Caesar cipher shifts each letter n-letters down the alphabet.
*/
fun main() {
val message = "meet me at secret location next wednesday afternoon"
val secretKey = 6
val ciphertext = encrypt(message, secretKey)
println("Ciphertext: $ciphertext")
bruteForce(ciphertext)
}
private fun bruteForce(ciphertext: String) {
println("Brute forcing key... ")
val dictionary = arrayOf("secret")
for (i in 0 downTo -26 + 1) {
val candidate = decrypt(ciphertext, i)
println(candidate)
for (s in dictionary) {
if (candidate.contains(s)) {
println("Plaintext found! Terminating...")
return
}
}
}
}
private fun decrypt(ciphertext: String, key: Int): String =
encrypt(ciphertext, -key)
private fun encrypt(string: String, key: Int): String =
string.map { getShiftChar(it, key) }.joinToString("")
private fun getShiftChar(c: Char, shift: Int): Char {
if(!c.isLetter())
return c
val x = c.code + shift
val y = x - 97
val z = Math.floorMod(y, 26)
val i = (z + 97).toChar()
return i
}