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

Related questions

...