Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to encrypt/decrypt URL parameters in javascript?

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

like image 425
Raghav Avatar asked Nov 06 '13 18:11

Raghav


People also ask

How do you escape a parameter in a URL?

URL escape codes for characters that must be escaped lists the characters that must be escaped in URLs. If you must escape a character in a string literal, you must use the dollar sign ($) instead of percent (%); for example, use query=title%20EQ%20"$3CMy title$3E" instead of query=title%20EQ%20'%3CMy title%3E' .

Can you use Javascript to get URL parameter values?

The short answer is yes Javascript can parse URL parameter values. You can do this by leveraging URL Parameters to: Pass values from one page to another using the Javascript Get Method. Pass custom values to Google Analytics using the Google Tag Manager URL Variable which works the same as using a Javascript function.


2 Answers

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

like image 193
Sebastien C. Avatar answered Sep 30 '22 19:09

Sebastien C.


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.

like image 9
olegarch Avatar answered Oct 02 '22 19:10

olegarch