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/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 plex 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?
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./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 plex 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?
Share Improve this question edited Dec 10, 2015 at 23:12 Sean Larkin asked Dec 10, 2015 at 21:56 Sean LarkinSean Larkin 6,4301 gold badge29 silver badges43 bronze badges 4- Almost by definition a hashing function is supposed to be irreversible so that's not really what you want haha. Base64 encoding is built in so that's probably a good bet. – jered Commented Dec 10, 2015 at 22:02
- What is wrong with JSON.stringify() ? – David Commented Dec 10, 2015 at 22:02
- But I will need to 'encodeURIComponent`? – Sean Larkin Commented Dec 10, 2015 at 22:48
- @SeanLarkin no you don't - it's safe to use base64 – zerkms Commented Dec 10, 2015 at 22:49
1 Answer
Reset to default 7Use 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))