Creating basic JavaScript encryption between Frontend and Backend.

Standard

One big problem with JavaScript is that it is very hard for a developer to hide JavaScript code and to create secure data transfer between browser and server. It is always possible for someone to check XHR transfers and this makes data transfer very unsecure.

I had to deal this problem, because I had to develop sweepstakes application , which gave prizes to the user live. To make this happen I had to make secure session exchange between browser and server to synchronize FrontEnd and BackEnd.

I had the following options:

1. To create JSON transfer and use “cryptic” variable names

2. Create my own encryption algorithm

3. Use some kind of JavaScript AES/DES library

I decided to take the second option. My data was in text format and it was looking like this:

Next step was to find a way how to encode this data in BackEnd and decode in FrontEnd. To do this I decided to use JavaScript bitwise XOR operator.

According to the documentation bitwise XOR operation works like this:

The ^ operator looks at the binary representation of the values of two expressions and does a bitwise exclusive OR operation on them. The result of this operation behaves as follows:

When one, and only one, of the expressions has a 1 in a digit, the result has a 1 in that digit. Otherwise, the result has a 0 in that digit.

In other words bitwise encoded string is created in two steps:

1. Partition the message into n-bit blocks
2. Bitwise XOR on the blocks

So the function had to split the string into blocks and make bitwise operation to the block.

To decode the string, you can use exactly the same function again.

*Next I had to base64encode/base64decode the string, because encoded string is in binary format and it is not possible to read it when doing XHR request. Luckily there are a lot of base64encode/base64decode solutions available for JavaScript on the internet.

It was time to create a PHP solution for BackEnd encoding. This task was much harder than I thought, because PHP ord function does not support multi byte characters.

I came up with the following class:

Using class:

Now it was possible for me to encode data on the server side and decrypt data in the browser (or vice versa). To make my application even more secure, I also used JavaScript minifier / obfuscator. My favorite here is Google Closure Compiler. Even though it is very easy to deobfuscate your code when using services like jsbeautify , it is still much harder to read and understand.

Another and more secure way to encrypt / decrypt data is to use excellent cryptojs , but I found it too heavy for a small sweepstake application. If you have a bigger project, which needs more security, you should definitely check out cryptojs.

JsEncode source code is also available on my GitHub.