F
F
Frezer2019-06-30 21:35:53
JavaScript
Frezer, 2019-06-30 21:35:53

How to encrypt anchor in url in JS?

I need to encrypt an anchor in a JS URL and then decrypt it using a special key.
Example: example.com/#youtext
Approximately as it should be: example.com/#eW91dGV4dA

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Derepko, 2019-06-30
@xEpozZ

alert(window.location.hash);

S
Sergey Sokolov, 2019-06-30
@sergiks

You can primitively XOR the "secret" password and string. Very unreliable, like the whole idea of ​​storing the encryption key in the client script. However, here is an example. When the hash is changed, it is replaced with an encrypted string. beginning with an exclamation mark is a distinguishing feature. If you also insert a hash with exclamation. sign - it is decrypted and replaced with the original string:

((w) => {

  function superpooper(secret) {
    const pass = encodeURIComponent(secret);
    return function onHashChange(){
      var hash = w.location.hash.replace(/^#/,"");
      if (!hash.length) return;
      
      const xor = s => s.split('').map((c,i)=>String.fromCharCode(c.charCodeAt(0)^pass.charCodeAt(i%pass.length))).join('');
  
      if (hash[0]==='!') {
        hash = hash.substring(1);
        const decoded = decodeURIComponent(xor(atob(hash)));
        history.replaceState(null, null, document.location.pathname + '#' + decoded);
      } else {
        const encoded = btoa(xor(encodeURIComponent(hash)));
        history.replaceState(null, null, document.location.pathname + '#!' + encoded);
      }
    }
  }

  w.addEventListener("hashchange", superpooper("abrakadabra"), false);
  
})(window)

If you run through the console and add, for example, a hash in the current tab,
And vice versa, if you add this long hash to the page, it will be replaced with "My secret is that's it."
Encryption key here abrakadabra
The increase in length is obtained due to the fact that I run it through encodeURIComponent()so that it works normally with Cyrillic, emoticons and emoji.
The original example is a simple binhex
у вас похоже на binhex: btoa('youtext') // "eW91dGV4dA==" – тут никаких ключей не требуется.
atob("eW91dGV4dA==") // "youtext"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question