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!
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) ?? ""
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With