Skip to content

Instantly share code, notes, and snippets.

@darhonbek
Last active October 5, 2018 06:46
Show Gist options
  • Save darhonbek/342d27064033f8bc54590a539783eda5 to your computer and use it in GitHub Desktop.
Save darhonbek/342d27064033f8bc54590a539783eda5 to your computer and use it in GitHub Desktop.
Ceasar's Cipher Brute Force
// MARK: - Main
var cipherText = "VSRQJHEREVTXDUHSDQWU".lowercased()
let decipheredTexts = decipherText(cipherText)
for (k, s) in decipheredTexts {
print("Shifts: \(k)\t\(s)")
}
// MARK: - Actions
func decipherText(_ cipher: String) -> [(Int, String)] {
let alphabet = getEnglishAlphabet()
var tempDecipher = ""
var decipheredTexts: [(Int, String)] = []
var asciiCode: Int = 0
var shifts = 0
for i in 0 ... 25 {
tempDecipher = ""
for (_, c) in cipher.enumerated() {
asciiCode = (i + (Int(c.ascii!) - 97)) % 26
tempDecipher.append(alphabet[asciiCode])
}
shifts = 26 - i
if shifts < 0 {
shifts = shifts + 26
}
decipheredTexts.insert((shifts, tempDecipher), at: decipheredTexts.startIndex)
}
return decipheredTexts
}
func getEnglishAlphabet() -> [String] {
var alphabet: [String] = []
for i in 97 ... (97+25) {
alphabet.append(i.asciiCharacter!)
}
return alphabet
}
// MARK: - Extensions
extension String {
var ascii: [UInt32] {
return unicodeScalars.compactMap{
$0.isASCII ? $0.value : nil
}
}
}
extension Character {
var ascii: UInt32? {
return String(self).ascii.first
}
}
extension Int {
var asciiCharacter: String? {
guard let asciiCode = UnicodeScalar(self) else {
return nil
}
return String(asciiCode)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment