Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two way hashing JSON String in JavaScript for use in URL

I would like to take a JSON string and encrypt/hash/encode it so that I can put it into a URL so that it would resemble something such as seen below:

var stringToEncode = JSON.stringify({foo: 'baz', bar: [1,2,3,4,5], baz: {fizzle: 'buzz'}});

'www.myrandomurl.com/someurl/123fas234asf1543rasfsafda'

I would then like to take that encrypted/hashed/encoded string, and decode it back to its original JSON string so that I can use it to bind to various elements on a single-page AngularJS application.

The contents of the JSON string are not sensitive so security or complex hashing is not required. The only condition is that It needs to be a "URL/URI 'safe'" string that is hashed for vanity purposes like seen above.

I am limited in knowledge of encrypting/encoding however I have thought about simply encoding the string to Base64 and decoding it again.

Is this the best approach? What is a better method if not?

like image 390
Sean Larkin Avatar asked Dec 10 '15 21:12

Sean Larkin


People also ask

How can I hash a JSON object?

The best way to sign and hash JSON objects now is to use JSON Web Tokens. This allows for an object to be signed, hashed and then verified by others based on the signature. It's offered for a bunch of different technologies and has an active development group.

How do you stringify a JSON object in JavaScript?

Stringify a JavaScript Object. Imagine we have this object in JavaScript: var obj = { name: "John", age: 30, city: "New York" }; Use the JavaScript function JSON.stringify () to convert it into a string. var myJSON = JSON.stringify(obj); The result will be a string following the JSON notation.

How to create hash from string in JavaScript?

How to create hash from string in JavaScript ? In order to create a unique hash from a specific string, it can be implemented using their own string to hash converting function. It will return the hash equivalent of a string. Also, a library named Crypto can be used to generate various types of hashes like SHA1, MD5, SHA256 and many more.

How do I convert JSON to text in JavaScript?

JSON makes it possible to store JavaScript objects as text. In JSON, date objects are not allowed. The JSON.stringify () function will convert any dates into strings. You can convert the string back into a date object at the receiver.


Video Answer


1 Answers

Use encodeURIComponent() to encode it for the url

To decode use the decodeURIComponent() function

Base64 is not URL safe since it can contain non url characters like / + -. (See this question)

If you want your url to not be too similair to the original string you can first covert to base64 and then encode and reverse by decoding and covrrtibg back from base 64

// to url
encodeURIComponent(btoa(str))

// from url
atob(decodeURIComponent(uri))
like image 50
Nachshon Schwartz Avatar answered Oct 23 '22 10:10

Nachshon Schwartz