I hate people viewsourcing my code
I hate people viewsourcing [hey ! I coined a new word :)] my code, what do I do ?
People who did not understand my newly invented word even after spending 5 or more seconds, please do not bother.. read on
Lets suppose I designed a great web page which contains some cleverly designed scripts and I want to protect its source code what do I do ? There are multiple ways, one of the common way is encoding using Microsoft Script Encoder ( It's a simple command line tool)
It's all good for a simple web page, but things are not so easy when we add a few variables like: what if your page dynamic ? ( e.g. being generated using some server side code), or what if you want to protect some XML data or HTML data ? (something important like connection string)
I recently handled one case like this, instinctively I suggested using "Microsoft Script Encoder" but on further discussion with the customer, I realized they finally need to protect HTML/XML not a script and their page is dynamically generated using ASP.
Now, running a command line tool on a web server is surely not a great idea [ok..sorry ..all generalizations are false!]. But still its not even not a great way of coding where you would need to persist your dynamically generated page to the disk then programmatically launch a commandline tool which will convert the page to the encoded page and sending this page to the user agent.
On researching further I realized that "Microsoft Script Encoder" uses "Microsoft Scripting Runtime" Scripting.Encoder object under the hoods.. so I thought of playing with it a bit..just to give you a backgrounder [oh..new word again! Are you reading this oxford !], I never used encoder object before this case came to me. When I looked for the documentation for this object, it was limited [I just want to avoid saying that there was no documentation.. but don't worry, I already looped in MSDN support].
So, the only option was playing with it, after some trial, error and testing I was able to device the following method for achieving the desired results:
1) Create an object of “Scripting.Encoder” (e.g oScrEnc)
2) Rather than directly writing the HTML that’s generated on server side wrap it in “document.write” [because script encoder or Microsoft Scripting Runtime can only encode script] and store it in a string (e.g strHTML )
3) Pass this string in EncodeScriptFile (e.g oScrEnc.EncodeScriptFile(“.js”,strHTML, 0, “js”)). This will return the encoded script.
4) Now, write the encoded script wherever you want in your page in between <script language = Jscript.Encode> </script> [note the language attribute, that’s required for the browser to understand the encoded script]
Have a look at the following code snippet for the completed code:
[We are not talking about protecting the source code from seasoned hackers, its about protecting it from the people who will do a quick view source and put the script in their web page]