Swift Simple XOR Encryption

岁酱吖の 提交于 2019-12-07 04:44:28

问题


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!


回答1:


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.

UPDATED: For Swift 2.0

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



回答2:


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))


来源:https://stackoverflow.com/questions/28144796/swift-simple-xor-encryption

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!