简体   繁体   中英

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?

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM