From a516f8e784764cb68b6c5aeb99d20deda006adb1 Mon Sep 17 00:00:00 2001 From: Denis Simon Date: Tue, 8 Jan 2019 21:35:15 +0300 Subject: [PATCH] Swift implementation --- README.md | 1 + Swift/XOREncryption.swift | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) create mode 100644 Swift/XOREncryption.swift diff --git a/README.md b/README.md index 12f88cd..9fa85bf 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,7 @@ Simple implementation of XOR Encryption/Decrypting in various languages, includi - [Objective-C](Objective-C/main.m) - [Python](Python/XOREncryption.py) - [Ruby](Ruby/xor.rb) +- [Swift](Swift/XOREncryption.swift) - [Visual Basic.NET](VB.NET/XORCrypto.vb) This implementation goes beyond the basic single-key model to use multiple keys in a particular sequence, making it that much more difficult to brute-force. diff --git a/Swift/XOREncryption.swift b/Swift/XOREncryption.swift new file mode 100644 index 0000000..a04680d --- /dev/null +++ b/Swift/XOREncryption.swift @@ -0,0 +1,33 @@ +// +// XOREncryption.swift +// XOREncryption +// +// Created by Denis Simon on 2019-01-08. +// + +import Foundation + +extension Character { + func utf8() -> UInt8 { + let utf8 = String(self).utf8 + return utf8[utf8.startIndex] + } +} + +func encryptDecrypt(_ input: String) -> String { + let key = "KCQ".characters.map { $0 } //Can be any chars, and any length array + let length = key.count + var output = "" + + for i in input.characters.enumerated() { + let byte = [i.element.utf8() ^ key[i.offset % length].utf8()] + output.append(String(bytes: byte, encoding: .utf8)!) + } + + return output +} + +let encrypted = encryptDecrypt("Hello, World!") +print("Encrypted: \(encrypted)") // output: Encrypted: &=',}k>9/5j +let decrypted = encryptDecrypt(encrypted) +print("Decrypted: \(decrypted)") // output: Decrypted: Hello, World!