问题描述
我想获取一个 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 'safe'"字符串,为了虚荣目的而进行哈希处理,如上所示.
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()
为 url 编码
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)
如果您希望您的 url 与原始字符串不太相似,您可以先转换为 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))
这篇关于在 JavaScript 中使用两种方式散列 JSON 字符串以用于 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!