Encrypt variables in URL

0

With @dvd solution, we pass variables to the URL via a select: link

There are several that look like this when they are passed: example.com/?fundo=img&cor=red

What I would like to do now is: encrypt the variable and its value in the URL.

More or less so: example.com/?d5t9a15d2a54ds54d5

    
asked by anonymous 04.03.2018 / 19:11

2 answers

3

You can change the URL in the browser with history.pushState . To generate a variable number, you can pick up the system time with new Date().getTime() and put in the URL preserving past variables.

The URL in the browser would look something like this:

example.com/?1520231465457

The code looks like this:

document.addEventListener("DOMContentLoaded", function(){

   var url_short = new Date().getTime(),
       url_ = location.href,
       param = url_.substring(url_.lastIndexOf("/")+1, url_.length),
       params = ['layout','sidebar']; // insira aqui os nomes das variáveis

   history.pushState(null, '', '?'+url_short);

   for(var y=0; y<params.length; y++){
      if(param.indexOf(params[y]) != -1){

         var var_ = url_.substring(url_.indexOf(params[y])+params[y].length+1,url_.length).match(/^(\d|\w){1,}/)[0],
             a_ = document.body.querySelectorAll("a");

         document.body.querySelector("#"+params[y]).value = var_;

         for(var x=0; x<a_.length; x++){
            a_[x].href += (a_[x].href.indexOf("?") == -1 ? "?" : "&")+params[y]+"="+var_;
         }
      }
   }

   var sels = document.querySelectorAll("select");

   for(var x=0; x<sels.length; x++){
      sels[x].addEventListener("change", function(){

         var sId = this.id,
             sVa = this.value;

         if(sVa && url_.indexOf(sId) == -1){

            location.href = url_+(url_.indexOf("?") == -1 ? "?" : "&")+sId+"="+sVa;

         }else if(sVa && url_.indexOf(sId+"="+sVa) == -1){

            var var_ = url_.substring(url_.indexOf(sId)+sId.length+1,url_.length).match(/^(\d|\w){1,}/)[0];

            location.href = url_.replace(sId+"="+var_, sId+"="+sVa);

         }

      });
   }

});
                                    
05.03.2018 / 07:35
1

Use the Crypto-js package

Just uncomment the first var search to get the parameters

//var search = window.location.search;
var search = '?name=fulaninho&pass=12312313&address=rua+dos+taubatucos+numero+22';
var pass   = '9090';

var enc = CryptoJS.AES.encrypt(search, pass).toString();
var dec = CryptoJS.AES.decrypt(enc, pass).toString(CryptoJS.enc.Utf8);

console.log(search);
console.log(enc);
console.log(dec);
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/crypto-js.min.js"></script>

You asked to leave the URL short, for me it has no way. But it's there, in a way it adds a bit of security to your application.

    
05.03.2018 / 02:35