How to encrypt/decrypt URL parameters in javascrip

2019-02-09 06:33发布

问题:

Before anyone jumps in and says, "Oh!! that's a bad idea", I know it is.

I want to keep both the key and value in the query string to be not easily visible to the end user. I have something like this google.com/?category=textile&user=user1 I need to make it unintelligible like this: google.com/?kasjdhfkashasdfsf32423

Is there any way to achieve this in javascript. I have already seen this

I have already seen this and this.

but I don't think encoding will solve the problem. Also, this code is entirely in client side. I know that it is not secure but I just need this is a naive, weak defense. Please help.

Edit

I apologize if my question was not clear earlier.

The URL google.com/?category=textile&user=user1 is being passed on from a different application.

The values passed in the query string directly controls what is being displayed to the user. As is, anyone with no technical knowledge can easily change the value and view the data corresponding to a different category or user. I need to make this unintelligible so that it is not obvious. If a user is a techie and figures out the encryption used, then it is fine. I need a stop-gap solution till we have a better architecture in place

回答1:

If you don't looking for serious strong crypto, you can use ROT13:

http://en.wikipedia.org/wiki/ROT13

This is enough for slightly obfuscate keys/values in the your URLs.



回答2:

You can use base64. Javascript has native functions to do that :

alert(btoa("category=textile&user=user1")); // ==> Y2F0ZWdvcnk9dGV4dGlsZSZ1c2VyPXVzZXIx

and to reverse it :

alert(atob("Y2F0ZWdvcnk9dGV4dGlsZSZ1c2VyPXVzZXIx")); // ==> category=textile&user=user1

Be careful to read the doc if you have unicode strings, it's a little different : https://developer.mozilla.org/en-US/docs/Web/API/Window.btoa