Xor in Swift 5

XOR in Swift 5?

You need to define ^ for Bool since it only exists for Ints. See the apple documentation here.

Example:

import UIKit
import PlaygroundSupport

extension Bool {
static func ^ (left: Bool, right: Bool) -> Bool {
return left != right
}
}

let a = true
let b = false
print (a^b)

Checksum and XOR in Swift

Swift 3 update:

public extension Data {

public mutating func xor(key: Data) {
for i in 0..<self.count {
self[i] ^= key[i % key.count]
}
}

public func checkSum() -> Int {
return self.map { Int($0) }.reduce(0, +) & 0xff
}
}

You can also create another function: xored(key: Data) -> Data.

Then you can chain these operators: xored(key).checksum()

Bitwise XOR on two digit hex string in Swift 3

You can use below code to get your result

let numbers = pairs.flatMap{Int($0, radix: 16)}

let xor = numbers.reduce(0, {$0^$1})

let result = String(format: "%02x", xor)

Adding hashValues together using Bitwise XOR Operator or simply adding them together

The reason to use ^ (bitwise exclusive-OR) over + is that + can overflow and crash your app.

The reason to use bitwise left and right shift operators is to generate different hash values if the array order is different. If you just ^ the hash values without shifting, then ["a", "b"] and ["b", "a"] would generate the same hash value.

What does a^b means in swift considering a,b are integers

That is a bitwise XOR operator, which you can find more information about in the Advanced Operators page of the Swift docs.

For 5^6, it's essentially doing the following:

5 = 0x00000101
6 = 0x00000110
0x00000011 = 3

XOR means "exclusive or". In other words, "one or the other but not both". In this case, the "4"-bit is on for both 5 and 6, so that one flips to off. The "1"-bit, and "2"-bit are both only on for the 5 or the 6 respectively, so they stay on.

Swift iOS XOR with a conversion from UInt8 to Int

To convert your UInt8? to Int, use an available Int initializer:

let a_int = Int(a.asciiValue!)
let b_int = Int(b.asciiValue!)
let xor = (a_int ^ b_int) // compiles

This direct approach requires force unwrapping but I assume the hex array looks like below and your characters are hard coded for safety. If not, unwrap these unsigned integers safely with if-else or guard.

let SerialNumber_hex_array: [Character] = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]

Swift 1.2 (Xcode 6.3) removed xor '^' operator for Bool value?

It's clearly intentional:

$ echo ':print_module Swift' | swift -deprecated-integrated-repl | fgrep "use the '!=' operator instead"

shows:

@availability(*, unavailable, message="use the '!=' operator instead") func ^=(inout lhs: Bool, rhs: Bool)
@availability(*, unavailable, message="use the '!=' operator instead") func ^(lhs: Bool, rhs: Bool) -> Bool

XOR Encryption in Swift IOS

Disclaimer: As explained in the comments using this kind of bit manipulation on UTF8 strings is unsafe and will not work as expected for arbitrary inputs.

I'm actually not sure whether the original Objective-C code does what you want. sizeof(key) is the size of the memory address of a char pointer (8 on my platform) and not the length of the UTF8 array. On top, sizeof(char) should always be 1. You probably want to use strlen instead.

Anyways, the equivalent of the (corrected) Objective-C code in Swift 2 could like this

func encryptDecrypt(input: String, staticKey: String) -> String? {
let key = staticKey.utf8
let bytes = input.utf8.enumerate().map({
$1 ^ key[key.startIndex.advancedBy($0 % key.count)]
})
return String(bytes: bytes, encoding: NSUTF8StringEncoding)
}

The test snippet

let key = "12345"
let string = "abcdefghijklmnopqrstuvwxyz"

let encrypted = encryptDecrypt(string, staticKey: key)!
let decrypted = encryptDecrypt(encrypted, staticKey: key)!

print(string)
print(encrypted)
print(decrypted)

will print out

abcdefghijklmnopqrstuvwxyz
PPPPPWU[]_Z^^ZZACAGADDDLLK
abcdefghijklmnopqrstuvwxyz

For Swift 1.2 you'll have to make a couple of small adaptions:

func encryptDecrypt(input: String, staticKey: String) -> String? {
let key = staticKey.utf8
let keyLength = distance(key.startIndex, key.endIndex)
let bytes = map(enumerate(input.utf8)) {
$1 ^ key[advance(key.startIndex, $0 % keyLength)]
}
return String(bytes: bytes, encoding: NSUTF8StringEncoding)
}

Update: The following snippet is closer to the original Objective-C code and works for arbitrary strings:

func encryptDecrypt(input: NSString, staticKey: NSString) -> NSString? {
let chars = (0..<input.length).map({
input.characterAtIndex($0) ^ staticKey.characterAtIndex($0 % staticKey.length)
})
return NSString(characters: chars, length: chars.count)
}

How to perform a logical XOR operation in swift to find out all textfields are empty or full?

You can do this without requiring an xor operator. This should be pretty simple to do if all your textfields are in an array. You can either create it in code or from your storyboard/xib using IBOutletCollection.

This code gets all the Bools from calling isEmpty on the textfields and puts them into a Set. If they are all true or all false, the set will only contain one value, if it's a mix of true/false then it will have two values.

let textFields: [UITextField] = ... // an array of the textfields to check
let emptyValues = Set(textFields.map { $0.text?.isEmpty ?? true })

if emptyValues.count == 1 {
print("All textfields are full or empty")
}

Swift Simple XOR Encryption

I would propose an extension to String like this.

extension String {
func encodeWithXorByte(key: UInt8) -> String {
return String(bytes: map(self.utf8){$0 ^ key}, encoding: NSUTF8StringEncoding)!
}

From the inside out,

  1. The call to self.utf8 creates a byte array, [UInt8], from the string
  2. map() is called on each element and XOR'ed with the key value
  3. A new String object is created from the XOR'ed byte array

Here is my Playground screen capture.
Sample Image

UPDATED: For Swift 2.0

extension String {
func encodeWithXorByte(key: UInt8) -> String {
return String(bytes: self.utf8.map{$0 ^ key}, encoding: NSUTF8StringEncoding) ?? ""
}
}


Related Topics



Leave a reply



Submit