Skip to content

Instantly share code, notes, and snippets.

@KYC3909
Last active October 5, 2023 09:21
Show Gist options
  • Save KYC3909/4c84ac08c7b9408e1db43d5c933c665a to your computer and use it in GitHub Desktop.
Save KYC3909/4c84ac08c7b9408e1db43d5c933c665a to your computer and use it in GitHub Desktop.
Cryptography: Caesar Cipher Encryption / Decryption in Swift
let originalString = "Hello"
let encodedPlacement = 4
var cipheredString = ""
var decipheredString = ""
func CaesarCipherEncrypt(_ str: String, _ num: Int) -> String {
var result = "";
for ch in str {
if let asciiValue = ch.asciiValue {
if asciiValue > 64 && asciiValue < 91 {
let a = Int(asciiValue) + num - 65
let total = UInt8(((a) % 26) + 65)
let string = UnicodeScalar(total)
result += String(string)
}else {
let a = Int(asciiValue) + num - 97
let total = UInt8(((a) % 26) + 97)
let string = UnicodeScalar(total)
result += String(string)
}
}
}
return result;
}
func CaesarCipherDecrypt(_ str: String, _ num: Int) -> String {
var result = "";
for ch in str {
if let asciiValue = ch.asciiValue {
if asciiValue > 64 && asciiValue < 91 {
let a = Int(asciiValue) - num - 65
let total = UInt8(((a) % 26) + 65)
let string = UnicodeScalar(total)
result += String(string)
}else {
let a = Int(asciiValue) - num - 97
let total = UInt8(((a) % 26) + 97)
let string = UnicodeScalar(total)
result += String(string)
}
}
}
return result;
}
cipheredString = CaesarCipherEncrypt(originalString, encodedPlacement)
decipheredString = CaesarCipherDecrypt(cipheredString, encodedPlacement)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment