This post is currently on hackernews, please consider upvoting it if you like it
I recently wrote my first gaming webapp: a HTML5 video puzzle. It was all fun to code but as I finished the game logic I had an interesting idea: why not somehow try to hide the code. At first I came up with simple standard stuff like hiding the context menu which usually appears on right click in order to somehow restrict inspecting the DOM. The context menu doesn’t show up but it doesn’t make a lot sense at all since the user can still use the keyboard shortcuts or the menu item for “view source” to have a look at the source code.
An image is worth more than thousand words.
Actually it depends on the image size. However, I decided to encode my source code into an image. And the HTML5 canvas element was perfectly fine for doing that since it supports pixel data manipulation. A pixel is represented by 4 values (channels): red, green, blue and alpha. Each of them can have a value in the range from 0 to 255. My JS code is an array of characters, a character has an Unicode value which lies in the range from 0 to 255 so what I decided to do was to iterate through every pixel of a canvas element and set 3 characters’ Unicode values as their RGB values (you can get the charcodes easily by using the charCodeAt function. e.g.
). The result is a colorful, small image which represents my code :) For example the code for my game:
To decode it I just draw the image into the canvas, iterate through all pixels, get the string representation from the r,g and b value with
and concatenate it to a big string which then is your code – ready for execution. :)
Is this code protection?
No, not really – an experienced (and maybe also not expirienced) developer can still figure out how to decode the image and get your code, but I think it is a first measurement for preventing evil business guys from stealing your code – developers who can figure the code out are (mostly) kind enough not to steal it ;)
ADD: Jeez, don’t get me wrong, I’m not really trying to hide my code from anyone, I actually love writing open source software, it was just a fun idea to do this experiment ;)
This technique only works in modern web browsers with HTML5 canvas support. Even some modern browsers have problems with en/decoding into the alpha channel of an image so you’re limited to encoding 3 characters per pixel – which still makes an 100×100 pixel image a 30 000 characters text :)
Do you know other techniques to make it less easy for someone to copy your code? Sure you could add a text to text encryption/decryption step, but how can you ensure that the decoding process won’t be exposed too easy? Let me know what you think!