Merge pull request #16 from denissimon/master

Swift implementation
This commit is contained in:
Kyle Banks 2019-01-10 10:18:39 -05:00 committed by GitHub
commit 86f440ca79
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 35 additions and 1 deletions

View File

@ -10,12 +10,13 @@ Simple implementation of XOR Encryption/Decrypting in various languages, includi
- [F#](F%23/Program.fs) by [pawelizycki](https://github.com/pawelizycki)
- [Go](Go/xor.go)
- [Groovy](Groovy/XOREncryption.groovy)
- [Java \(Android Compatible\)](Java \(Android compatible\)/XOREncryption.java)
- [Java \(Android Compatible\)](Java%20\(Android%20compatible\)/XOREncryption.java)
- [JavaScript \(Node.js Compatible\)](JavaScript/XOREncryption.js)
- [Kotlin](Kotlin/XOREncryption.kt)
- [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.

33
Swift/XOREncryption.swift Normal file
View File

@ -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!