Javascript File Name Encryption and Referencing - javascript

I want to change the JavaScript names in my application for additional security like facebook and google plus suring deployment.
Is there are an application or a library that can change the JavaScript file names and reference them in the my view (written in php) and JavaScript files.
EXAMPLE OF THE DESIRED EFFECT
Change this (Before Deployment):
In folder: js/myfunction.js
In file:<script type="text/javascript" src="https://mysite.com/myfunction.js"></script>
To this (After Deployment):
In folder: js/PuKJS78UyH.js
In file: <script type="text/javascript" src="https://mysite.com/PuKJS78UyHK.js"></script>

Instead of obfuscating and encryption you should think about optimization. Couple things that you could do:
Combine all common JS files in one file (minimizes number of requests and also solves your problem - there will be no file names to obfuscate)
Minimize JS - it's faster that way and takes less space (and in addition it becomes unreadable)
This tool looks like a good place to start: http://code.google.com/p/minify/

You should not depend on JavaScript encryption. It is not safe, and might be hacked in a short time. Using sever side languages like PHP is much safer than JavaScript.
However, if you would like to perform a simple base-64 encoding in JavaScript, for which normal people will not able to read, you are lucky, it doesn't need any library. \(^o^)/
Just use btoa() for encoding, and atob() for decoding. Then you can create a <script> tag using the encoded URL.
Read more in MDN: window.atob
Example:
var txt = "myfunction.js";
var encode = btoa(txt);
var decode = atob(encode);
console.log( encode ); //return "bXlmdW5jdGlvbi5qcw=="
console.log( decode ); //return "myfunction.js" (orginal)
//Do whatever you want with the encoded text, like
$("<script src='/js/"+encode+".js' type='text/javascript'></script>")
.appendTo("head"); //dynamically adding an script tag using jQuery
Demo: http://jsfiddle.net/DerekL/JWSUs/
Result:
Result from jsFiddle. You can see that "myfunction.js" is encoded to "bXlmdW5jdGlvbi5qcw==", which normal people will not be able to read.

Related

something better than base64 to encode data that doesn't take up too much processing power

I have a web site in which users can add multiple items and sometimes the URL can be long. I thought by using base64 encoding, I'd pass the URL along but it contains a slash which I use to separate items because my web server cannot handle path names (anything between 2 slashes) longer than 255 characters or I'd get a 403 error.
Is there another way I can encode data quickly in javascript so that theres a 0% chance that a slash will occur in the result?
I'm looking for something not too processor intensive and if possible, I want to go for something better than character swapping.
I will understand if I need to visit a library, but the only encoding built-in to javascript (to my knowledge) is base64 (via the atob function) and I want something different.
I also want to be able to make the solution work with older web browsers as well.
What you need is encodeURIComponent, which is part of the javascript spec and automatically included in all javascript environments
var url = 'example.com/someextenstion/' + encodeURIComponent(theString);
There are many ways to address this but one of the simplest is going to be to take an implementation of atob and btoa and modify it to use a - instead of a / when encoding. You'll have to rename the functions so they don't mask the standard function, but here's some JavaScript source code that does the trick: github. In that particular implementation just replace the / in _ALPHA with a - (or any character of your choosing).
It might be faster to just do as Amit suggests: use the standard functions and do a quick string replace of / on conversion: str.replace(/\//g,'-'); and perform the reverse on decoding, but it doesn't seem like performance will be critical in this application.

Multi language support

I'm developing a HTML5 application that uses jQuery. I want to make it multi language: detecting user language and changing all literals to user's language.
I think that one approach is to use one HTML file for each language supported, but it is a waste of space.
Another approach could be use jQuery to change all literals to user's language. But I'm not sure how to do this.
What do you think? Is there a better approach?
UPDATE:
I've forget it to say that I have some literals inside JavaScript too.
Coulnd't you do some sort of server-side query to the user's language and then load the appropriate text automatically? Maybe even a CMS is appropriate here.
For all the Javascript code, I would use String literals as a variable. So you can load a different language file appropriate to the user language.
File english.js:
var messages_siteA1 = "This is an alert.";
var messages_siteA2 = "...";
// ...
File german.js:
var messages_siteA1 = "Dies ist eine Warnung.";
var messages_siteA2 = "...";
// ...
And in your Javascript:
alert(messages_siteA1);
Or am I missing the point here? ;)
In the HTML5 Demo of my, the "HTML5 Word Clouds",
http://timc.idv.tw/wordcloud/
(source code can be found at https://github.com/timdream/wordcloud)
I wrote separate HTML for different languages, and includes a single set of Javascript files. For literal strings with in the script, I collect them into an object (named T) and put it into <script> block of each HTML files.
This give me the flexibility to customize pages for each language; as you can see, I listed CNN as example in English version, but list other sources in the Chinese version.
If you absolutely have to do it at client-side, how about using a json or xml file to store your translations? This avoids the trouble of creating copies of the same page. For example, in your json. you'd have "welcome_eng": "welcome" and "welcome_fr": "bienvenue", etc.
Then you load the appropriate one using javascript, as in, get the variables like this:
blablabla=["welcome_"+language]
Or, if you want even less work, your welcome text's div will have the id "welcome", then your javascript gets the id and add the appropriate content.
It mostly depends on how dynamic or static your pages are: If they contain much text, than it will be easier to duplicate the page for each language. In this case it is very important to carefully isolate HTML from CSS and scripts. All CSS and scripts should be stored in separate pages, in order to avoid having to update all translations whnever you update a style or a script.
OTOH, if it is mostly dynamic, than it makes sense to replace text snippets by their translation when creating the page. But I wouldn't do the text replacement client-side (jQuery). It's a server-side job.
Edit: If you have javascript literals, you should then of course keep them side by side with the HTML, either in the HTML file or in a separate .js file. But it remains up to the server to deliver the contents in the correct language.

Javascript localization in .net

I'm trying to determine the best way to implement localization into one of our web apps. This app is going to have a large number of javascript files, which will need to be localized as well.
Localizing the .net code is straight forward enough. We have a file called WebResources.resx which contains all strings in english (our fall back language). Then we just add additional files with alternative localized information (eg: WebResources.es-mx.resx). Then, bam! .Net pretty much takes care of the rest.
Pretty sweet. But when it comes to javascript, not so fast. Reading on MSDN they recommend:
You create a separate script file for each supported language and culture. In each script file, you include an object in JSON format that contains the localized resources values for that language and culture.
This seems like a maintenance nightmare that I'd like to avoid. Plus I'd like to avoid having to use the asp.net ScriptManager. So I got the bright idea of trying to use the resource files in my .js files. EG foobar.js:
function showGenericError(){
alert('<% =Resources.WebResources.JsGenericError %>');
}
This unfortunately does not work as the .NET does not seem to do any processing on .js files. So the next idea I got was from the answer on this thread. It recommended having a javascript file which contained all your language strings. This feels like a waist of resources since at run time I only need one language, not all of them.
This leads me to the solution I'm planning on implementing. I plan to have a generic handler that writes out JSON that is localized for the language the current user is in need of. Here is a sample of what the .ashx page will look like:
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "application/json";
StringBuilder json = new StringBuilder();
using (StringWriter jsonStringWriter = new StringWriter(json))
{
using (JsonTextWriter jsonWriter = new JsonTextWriter(jsonStringWriter))
{
jsonWriter.WriteStartObject();
jsonWriter.WritePropertyName("genericErrorMessage");
jsonWriter.WriteValue(Resources.WebResources.GenericErrorMessage);
jsonWriter.WriteEndObject();
}
}
context.Response.Write("var webResources = " + json.ToString());
}
In the head of my pages I will have:
<script type="text/javascript" src="js/webResources.js.ashx"></script>
Then my js file will look like:
function showGenericError(){
alert(webResources.genericErrorMessage);
}
Almost seems too easy, right? So my question is, does this make sense? Am I missing a "gotcha" somewhere? What are the downsides? Is there a better way to do this?
I posted a similar question a while ago, and this is what I came up with:
Localize javascript messages and validation text
The advantage here is that you can share resources used in regular .net pages.
Your approach looks fine as well.
Here is the way i did it, just in case someone finds it useful.
I didnt want to put any Razor on JS, because of CSP i kept JS files separated from the cshtml.
So I added a element in the Shared cshtml, with the content of an array of arrays, each element of the array is a Key/Value pair with the name and the localized string as returned by Razor>
<meta name="resources" content="[
['name1', '#HttpUtility.JavaScriptStringEncode(Resources.name1)'],
['name2', '#HttpUtility.JavaScriptStringEncode(name2)']
]" />
Then in the js file, i convert this into a dictionary:
let livstrResMap = document.querySelector("meta[name='resources']").getAttribute("content");
livstrResMap = livstrResMap.replace(/'/g, '"')
let lioJSN = JSON.parse(livstrResMap)
let mcvcodResources = new Map(lioJSN);
Finally i use the localized string using the Format helper defined here
alert(mcvcodResources.get('name1'));

Best way to decompress javascript files

There are many tools to compress a Javascript file (Packer YUI for example).
But how can I decompress them back to a human readable format?
I have compressed a file using a tool like Packer YUI , but I couldn't reach the source back again.
Is there any good software or tricks you can suggest to decompress the JS ?
You can't. Javascript compression is usually a lossy one, and the information is lost forever.
What you can do, is use a source formatter and a good refactoring tool and -- painfully -- reconstruct the original source. Even if you are not familiar with the code it should be possible; Jeff and a few others reverse engineered the WMD javascript code from a minified version.
Finally, you should consider using a version control system and proper backups to keep your source code safe.
This website is really cool. You can paste a minified JS, then you get a human readable view.
Try JSMinNpp (now called JSToolNpp) plugin for notepad++ (to compress and decompress).
http://www.sunjw.us/jstoolnpp/
DECOMPRESS JAVASCRIPT
A typical JavaScript compressed with /packer/ starts with the following code:
`eval(function(p,a,c,k,e,r)`…
`eval` can simply be replaced by alert.
The eval function evaluates a string argument that contains JavaScript. In most packers, eval is used, followed by document.write.
To decompress JavaScript, replace these methods by one of the following:
1. Replace eval by alert (The alert will simply print the code in a popup-window)
2. If the JavaScript appears after the <body> element, you can add a <textarea> like so:
`<textarea id="code"></textarea>`
Then, replace eval(…); by document.getElementById("code").value=…;.
A linter like ESLint can be handy as well. It can format the code using the "fix all auto-fixable problems" to a point where you can at least start doing manual editing with greater ease.
I never used Packer YUI. But if you use this javascript packer, you can always get your code back using this javascript beautifier which also decompresses the code.
Some javascipt minifier shorten the variable names while compressing the js. In that case you could never get your original code back even if you beautify it.

Javascript encoding question

We have an external .js file that we want to include in a number of different pages. The file contains code for sorting a table on the client-side, and uses the ▲ and ▼ characters in the script to indicate which column is sorted and in which direction.
The script was originally written for an ASP.Net page to offload some sorting work from the server to client (prevent sorting postbacks when javascript is enabled). In that case, the encoding is pretty much always UTF-8 and it works great in that context.
However, we also have a number of older Classic ASP pages where we want to include the script. For these pages the encoding is more of a hodgepodge depending on who wrote the page when and what tool they were using (notepad, vs6, vs2005, other html helper). Often no encoding is specified in the page so it's up to the browser to pick, but there's really no hard rule for it that I can see.
The problem is that if a different (non-UTF8) encoding is used the ▼ and ▲ characters won't show up correctly. I tried using html entities instead, but couldn't get them to work well from the javascript.
How can I make the script adjust for the various potential encodings so that the "special" characters always show up correctly? Are there different characters I could be using, or a trick I missed to make the html entities work from javascript?
Here is the snippet where the characters are used:
// get sort direction, arrow
var dir = 1;
if (self.innerHTML.indexOf(" ▲") > -1)
dir = -1;
var arrow = (dir == 1)?" ▲":" ▼";
// SORT -- function that actually sorts- not relevant to the question
if (!SimpleTableSort(t.id, self.cellIndex, dir, sortType)) return;
//remove all arrows
for (var c = 0,cl=t.rows[0].cells.length;c<cl;c+=1)
{
var cell = t.rows[0].cells[c];
cell.innerHTML = cell.innerHTML.replace(" ▲", "").replace(" ▼", "");
}
// set new arrow
self.innerHTML += arrow;
For the curious, the code points I ended up using with the accepted answer were \u25B4 and \u25BC.
The encoding of the JavaScript file depends on the encoding of the HTML page, where it is embedded. If you have a UTF-8 JavaScript file and a ISO-8859-1 HTML page the JavaScript is interpreted as ISO-8859-1.
If you load the JavaScript from as a external file you could specify the encoding of the JavaScript:
<script type="text/javascript" charset="UTF-8" src="externalJS.js"></script>
Anyway the best option is to save all files related to a webproject in one encoding, UTF-8 recommended.
You want Javascript Unicode escapes i.e. "\uxxxx", where "xxxx" is the Unicode code point for the character. I believe "\u25B2" and "\u25BC" are the two you need.
I voted for both. I think both answers put together would be your best bet.
You're probably going to have to write the script twice, putting in a part for UTF-8, and putting in a part for non UTF-8. It's more trouble, and might not work all the time, STILL.
Someone needs to come up with standards for your developers. If you all write with at least the same encoding, it'll make things a lot easier for yourselves in the future.

Categories

Resources