Reputation: 107
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
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,
[UInt8]
, from the stringHere 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) ?? ""
}
}
Upvotes: 15
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