Kevin Sullivan
Kevin Sullivan

Reputation: 107

Swift Simple XOR Encryption

I am trying to do a simple xor encryption routine in Swift. I know this is not a particularly secure or great method but I just need it to be simple. I know how the code is implemented in Javascript I'm just having trouble translating it to Swift.

Javascript:

function xor_str()
{
  var to_enc = "string to encrypt";

  var xor_key=28
  var the_res="";//the result will be here
  for(i=0;i<to_enc.length;++i)
  {
    the_res+=String.fromCharCode(xor_key^to_enc.charCodeAt(i));
  }
  document.forms['the_form'].elements.res.value=the_res;
}

Any help you could provide would be great, thanks!

Upvotes: 6

Views: 6028

Answers (2)

Price Ringo
Price Ringo

Reputation: 3440

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. enter image description here

UPDATED: For Swift 2.0

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

Upvotes: 15

Crater
Crater

Reputation: 53

I can't answer with a comment yet, but Price Ringo, i noticed a couple problems with your sandbox..

the last line has 2 errors, you should actually XOR it with the original encrypted UInt8 and you are not "decoding" the encrypted string..

you have...

println(str.encodeWithXorByte(0))

where you should have..

println(encrypted.encodeWithXorByte(28))

Upvotes: 4

Related Questions