Skip to content

Instantly share code, notes, and snippets.

@mehmetfarhan
Last active June 28, 2020 09:47
Show Gist options
  • Save mehmetfarhan/8765b46175884c8caab46a2d6f194a25 to your computer and use it in GitHub Desktop.
Save mehmetfarhan/8765b46175884c8caab46a2d6f194a25 to your computer and use it in GitHub Desktop.
XOR encryption and decryption
final class XOREncryptionAndDecryption {
static func encript(_ text: String, cipher: String) -> String {
let text = [UInt8](text.utf8)
let cipher = [UInt8](cipher.utf8)
var encripted = [UInt8]()
for (index, item) in text.enumerated() {
encripted.append(item ^ cipher[index])
}
return String(bytes: encripted, encoding: .utf8) ?? ""
}
static func decrypt(_ encriptedText: String, cipher: String) -> String {
let text = [UInt8](encriptedText.utf8)
let cipher = [UInt8](cipher.utf8)
var decrypted = [UInt8]()
for (index, item) in text.enumerated() {
decrypted.append(item ^ cipher[index])
}
return String(bytes: decrypted, encoding: .utf8) ?? ""
}
}
let encryptedText = XOREncryptionAndDecryption.encript("hello!!!", cipher: "goodbye!") // XD
let decryptedText = XOREncryptionAndDecryption.decrypt(encryptedText, cipher: "goodbye!") // hello!!!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment