timkvw
Last Updated: November 05, 2017
·
3.667K
· anthonylevings
Speechrocket4 square

Simple XOR Encryption and Decryption in Swift (Playground Code)

Here's a simple example of conversion of strings to UTF-8 byte arrays. Followed by a XOR encryption and decryption in Swift.

let text = [UInt8]("hello!!!".utf8)
let cipher = [UInt8]("goodbye!".utf8)

var encrypted = [UInt8]()

// encrypt bytes
for t in enumerate(text) {
    encrypted.append(t.element ^ cipher[t.index])
}

var decrypted = [UInt8]()

// decrypt bytes
for t in enumerate(encrypted) {
    decrypted.append(t.element ^ cipher[t.index])
}

String(bytes: decrypted, encoding: NSUTF8StringEncoding) // hello!!!

To read more about XOR encryption and for an interactive example see full blogpost.

Say Thanks
Respond

1 Response
Add your response

29408

//: Updated code as of Nov 5 2017
import UIKit

let text = UInt8
let cipher = UInt8

var encrypted = UInt8

// encrypt bytes
for (i,e) in text.enumerated() {
encrypted.append(e ^ cipher[i])
}

var decrypted = UInt8

// decrypt bytes
for (i,e) in encrypted.enumerated() {
decrypted.append(e ^ cipher[i])
}

String(bytes: decrypted, encoding: String.Encoding.utf8)

28 days ago ·