URL中使用JavaScript的两种方式对JSON字符串进行哈希处理 [英] Two way hashing JSON String in JavaScript for use in URL
问题描述
我想获取一个JSON字符串并对其进行加密/哈希/编码,以便可以将其放入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'
然后,我想获取该加密/哈希/编码的字符串,并将其解码回其原始的JSON字符串,以便可以将其绑定到单页AngularJS应用程序上的各种元素.
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.
JSON字符串的内容不敏感,因此不需要安全性或复杂的哈希.唯一的条件是,它必须是一个"URL/URI'安全'"字符串,为实现虚荣目的而对其进行哈希处理,就像上面看到的那样.
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.
我对加密/编码的知识有限,但是我曾考虑过将字符串简单编码为Base64并再次对其进行解码.
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?
推荐答案
使用 encodeURIComponent()
为网址进行编码
Use encodeURIComponent()
to encode it for the url
要解码,请使用 decodeURIComponent()
函数
To decode use the decodeURIComponent()
function
Base64不是URL安全,因为它可以包含非url字符,例如/+-. (请参阅此问题)
Base64 is not URL safe since it can contain non url characters like / + -. (See this question)
如果您希望自己的网址与原始字符串不太相似,则可以先将其转换为base64,然后通过解码和从base 64返回covrrtibg来进行编码和反向操作
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))
这篇关于URL中使用JavaScript的两种方式对JSON字符串进行哈希处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!