JavaScript Ninja – Make Stored Base64 Content Harder To Reverse-Engineer

A good amount of in-app stored data (hopefully small-amount of text, unless there is something *wrong with you*) is “encrypted” as base64
– and, while encryption is ‘hardly the point’, it would be nice to make stored data (textual! small amount!) harder to rip/decipher/scrape/grab/grapes?(yumm!)

here is raw to “hidden” process (including proper Unicode handling and some “=” hiding, to avoid the most obvious base64 characteristics..)

var s, fixed_length;
s = "my password1";                  /* raw data                       */
s = unescape(encodeURIComponent(    /* to bit string  (Unicode2ASCII) */
      "my password"
    ));

s = btoa(s);
s = s.replace(/\=+$/g,"");

s = s.split("").reverse().join("");   /* make similar raw-strings significantly different (at first look)*/

s = btoa(s);
s = s.replace(/\=+$/g,"");

console.log(
s
,s.length
);

more function like, the only thing needed to remember is using same amount of “iterations”

function enc(s, iteration/*==1*/){
  s = unescape(encodeURIComponent(s));  /* handling Unicode */
  for(var i=0; i<iteration; i++)
    s = btoa(s).replace(/\=+$/g,"");
  return s;
}

function dec(s, iteration/*==1*/){
  for(var i=0; i<iteration; i++){
    s = (s + "===").substring(0, s.length + s.length % 4); /* re-(right-"="-)pad */
    s = atob(s);
  }
  s = decodeURIComponent(escape(s));    /* handling Unicode */
  return s;
}

for example:

enc("a") or enc("a",0)
"a"
enc("a",1)
"YQ"
enc("a",2)
"WVE"
enc("a",3)
"V1ZF"

dec("a") or dec("a",0) "a"
*** dec("a",1) *** "Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded." (error) *** this will happen if used iteration number larger than what actually used in "enc" function. naturally you'll need some error handling and fallbacks :]
dec("V1ZF",1) "WVE" dec("WVE",1) ...

Leave a Reply