Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,844 questions

51,765 answers

573 users

How to use XOR to encrypt and decrypt a string in Swift

2 Answers

0 votes
import Foundation

func xorEncryptDecrypt(input: String, key: Character) -> String {
    let keyValue = key.asciiValue!
    
    let result = input.map { char -> Character in
        let xorValue = char.asciiValue! ^ keyValue
        return Character(UnicodeScalar(xorValue))
    }
    
    return String(result)
}

let originalText = "May the Force be with you."
let key: Character = "K" // Encryption and decryption key

// Encrypt the string
let encryptedText = xorEncryptDecrypt(input: originalText, key: key)
print("Encrypted:\n \(encryptedText)")

// Decrypt the string (same function, same key)
let decryptedText = xorEncryptDecrypt(input: encryptedText, key: key)
print("Decrypted:\n \(decryptedText)")



/*
run:

Encrypted:
$9(.k).k<"?#k2$>e
Decrypted:
 May the Force be with you.

*/

 



answered Aug 17, 2025 by avibootz
0 votes
import Foundation

func xorEncryptDecrypt(input: String, key: String) -> String {
    let keyValues = key.compactMap { $0.asciiValue }
    
    let result = input.enumerated().map { (index, char) -> Character in
        guard let charValue = char.asciiValue else { return char }
        let keyCharValue = keyValues[index % keyValues.count]
        let xorValue = charValue ^ keyCharValue
        return Character(UnicodeScalar(xorValue))
    }
    
    return String(result)
}

let originalText = "May the Force be with you."
let key = "Obelus" // String key for XOR operation

// Encrypt the string
let encryptedText = xorEncryptDecrypt(input: originalText, key: key)
print("Encrypted:\n \(encryptedText)")

// Decrypt the string (same function, same key)
let decryptedText = xorEncryptDecrypt(input: encryptedText, key: key)
print("Decrypted:\n \(decryptedText)")



/*
run:

Encrypted:
L :L *B#   *B  U &
Decrypted:
 May the Force be with you.

*/

 



answered Aug 17, 2025 by avibootz
...