XOR Cipher Encryption in ActionScript 3
I typically use an external XML file in all my applications to store configuration variables outside my compiled SWF file. This allows me to make changes to those variables without needing to recompile the SWF application. This is really helpful if you’re deploying an application to multiple environments (development, staging, production). You can deploy the same application and just have a different XML file in each environment with different values.
The values in the XML file are easily read by anyone using a proxy like Charles or Service Capture. Therefore, I decided to put a simple encryption on the values I didn’t want people to be able to easily read. XOR Cipher encryption is a simple form of two-way encryption using a known key. This key would be compiled into your SWF application. So the only way someone could decrypt your variables would be if they decompiled your SWF or guessed the key. Obviously this solution is not hack proof, but it provides a road block for anyone trying to get at these values.
The following is an ActionScript 3 class that performs this XOR encryption. This encodes/decodes the XOR encrypted value using the Base64Encoder in Flex, so if you want to use this without Flex you’ll need to remove that dependancy. The xor() method performs the XOR encryption against the key. If you run a string through this method it with return and encrypted string, and if you run that encrypted string through this method it will return your original string.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | package com.dannypatterson.utils { import mx.utils.Base64Encoder; import mx.utils.Base64Decoder; public class XORcipher { public static var KEY:String = "eVBHOulunx8A6spikeRQ9UEgyaXINTyzpn3SJ7FSzmwSlewTWI3"; private static function xor(source:String):String { var key:String = KEY; var result:String = new String(); for(var i:Number = 0; i < source.length; i++) { if(i > (key.length - 1)) { key += key; } result += String.fromCharCode(source.charCodeAt(i) ^ key.charCodeAt(i)); } return result; } public static function encode(source:String):String { var encoder:Base64Encoder = new Base64Encoder(); encoder.encode(XORcrypt.xor(source)); return encoder.flush(); } public static function decode(source:String):String { var encoder:Base64Decoder = new Base64Decoder(); encoder.decode(source); return XORcrypt.xor(encoder.flush().toString()); } } } |
