Answer the question
In order to leave comments, you need to log in
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
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)
abrakadabra
encodeURIComponent()
so that it works normally with Cyrillic, emoticons and emoji.btoa('youtext') // "eW91dGV4dA=="
– тут никаких ключей не требуется.atob("eW91dGV4dA==") // "youtext"
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question