如何在JavaScript中混淆字符串?

时间:2015-06-29 05:33:46

标签: javascript json string

基本上,我想用JavaScript制作游戏,并允许用户获得存储其数据的复制粘贴代码。实际上,这个“代码”实际上是混淆的JSON,以后可以由应用程序解码。

我不需要太多的安全性,因为我知道如果人们付出一些努力他们可以查看/修改保存,我没有兴趣阻止他们。我只是希望普通用户不被诱惑和/或看到不必要的信息。

提前致谢。

2 个答案:

答案 0 :(得分:2)

您可以使用base64编码对json String进行编码。这将是更快的方法。

如果你使用纯javascript:

selectedModel

如果您使用的是nodejs:

base-64编码:

var encodedData = btoa("stringToEncode");

解码为原始值:

var encodedStr = new Buffer("Hello World").toString('base64')

答案 1 :(得分:1)

嗯......鉴于没有安全问题而您只希望用户看到看似乱码的数据,您可以“编码”所有json数据

var jsonData = {"key":"value"};

// turn it into a string
var jsonString = JSON.stringify(jsonData);

// replace some letters
var awkardString = jsonString.replace(/a/g, '!Ax6'); // be carefull, you should replace a letter with a pattern that does not already exist on the string.

// encode it with some type of reversible encoding
var garbledData = encodeURI(jsonString);

// output is: %7B%22key%22:%22v!Ax6lue%22%7D

// to "decode" it do the same steps in reverse
awkardString = decodeURI(garbledData);
jsonString = awkardString.replace(/!Ax6/g, 'a'); // now you see, if '!Ax6' existed on the source string, you would loose it and get an 'a' in return. That is why the replacement should be as unique as possible
jsonData = JSON.parse(jsonString);