Last Updated: November 19, 2020
· anthonylevings

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.

Related protips:

Some simple Swift Extensions (Strip HTML, RGB Color, Color invert, Dismiss modal segue)

1 Response
Add your response

//: 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)

over 1 year ago ·