timkvw
Last Updated: May 25, 2018
·
4.627K
· 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

2 Responses
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)

9 months ago ·
29937

I'm new to Swift, now I just want to translate java xor encrypt/decrypt code to Swift, which is used for transactions between server and client. Below is the Java xor code: public static String encrypt(String password, String key) { if (password == null) return ""; if (password.length() == 0) return ""; BigInteger bipasswd = new BigInteger(password.getBytes()); BigInteger bir0 = new BigInteger(key); BigInteger bir1 = bir0.xor(bipasswd); return bir1.toString(16); } public static String decrypt(String encrypted, String key) { if (encrypted == null) return ""; if (encrypted.length() == 0) return ""; BigInteger biconfuse = new BigInteger(key); try { BigInteger bir1 = new BigInteger(encrypted, 16); BigInteger bir0 = bir1.xor(biconfuse); return new String(bir0.toByteArray()); } catch (Exception e) { return ""; } } And I've searched a lot about swift xor encryption and tried the answer in the links below:
https://www.techavy.com/free-movie-sites-online/
https://pirateproxy.xyz/

about 2 months ago ·