Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Simple XOR Encryption

Tags:

swift

xor

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!

like image 917
Kevin Sullivan Avatar asked Jan 26 '15 04:01

Kevin Sullivan


1 Answers

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) ?? ""
  }
}
like image 100
Price Ringo Avatar answered Sep 27 '22 17:09

Price Ringo