0

在我的项目中,我编写了 google 电子表格脚本来使用 sjcl 解密加密的单元格内容。但我失败了。

function encryptCell() {
  var masterKey = Browser.inputBox('Enter masterKey');
  var spreadSheet = SpreadsheetApp.getActiveSpreadsheet();
  var cell = spreadSheet.getActiveSheet().getActiveCell();
  var input = cell.getValue();

  var encJson = sjcl.encrypt(masterKey, input);
/*
{"iv":"4psT+LTIh/aT7WWv7Ye7qw==","v":1,"iter":1000,"ks":128,"ts":64,"mode":"ccm","adata":"","cipher":"aes","salt":"PjSOiia9TCM=","ct":"3hwmBbwQ7y/fsjk="}
*/
  var encStr = JSON.stringify(encJson);
/*
"{\"iv\":\"4psT+LTIh/aT7WWv7Ye7qw==\",\"v\":1,\"iter\":1000,\"ks\":128,\"ts\":64,\"mode\":\"ccm\",\"adata\":\"\",\"cipher\":\"aes\",\"salt\":\"PjSOiia9TCM=\",\"ct\":\"3hwmBbwQ7y/fsjk=\"}"
*/
  var encB64 = Utilities.base64Encode(encStr);
  Browser.msgBox(encB64);

  var rencStr = Utilities.base64Decode(encB64);
/*
34,123,92,34,105,118,92,34,58,92,34,52,112,115,84,43,76,84,73,104,47,97,84,55,87,87,118,55,89,101,55,113,119,61,61,92,34,44,92,34,118,92,34,58,49,44,92,34,105,116,101,114,92,34,58,49,48,48,48,44,92,34,107,115,92,34,58,49,50,56,44,92,34,116,115,92,34,58,54,52,44,92,34,109,111,100,101,92,34,58,92,34,99,99,109,92,34,44,92,34,97,100,97,116,97,92,34,58,92,34,92,34,44,92,34,99,105,112,104,101,114,92,34,58,92,34,97,101,115,92,34,44,92,34,115,97,108,116,92,34,58,92,34,80,106,83,79,105,105,97,57,84,67,77,61,92,34,44,92,34,99,116,92,34,58,92,34,51,104,119,109,66,98,119,81,55,121,47,102,115,106,107,61,92,34,125,34
*/
  var rencJson = JSON.parse(rencStr);
  var rinput = sjcl.decrypt(masterKey, rencJson);
  Browser.msgBox(rinput);
}

加密很好,我可以用这个工具解密。有问题JSON.parse()

4

2 回答 2

1

与您一起解码时,Utilities.base64Decode()如果您想取回字符串,则需要执行一个额外的步骤。如果您查看Google Scripts 参考,它会说base64Decode返回一个字节数组而不是字符串。查看您的代码,您的解码返回

var rencStr = Utilities.base64Decode(encB64);
/*34,123,92,34,105,118,92,34,58,92,34,52,112,115,84,43,76,84,73,104,47,97,84...*/

这是 Unicode 字符串的数字表示。如果您按照参考建议运行返回值Utilities.newBlob(rencStr).getDataAsString(),您将拥有可以解析回加密字符串的 JSON。

于 2015-12-09T16:25:34.360 回答
1
  var rencStr = Utilities.base64Decode(encB64);
/*
34,123,92,34,105,118,92,34,58,92,34,52,112,115,84,43,76,84,73,104,47,97,84,55,87,87,118,55,89,101,55,113,119,61,61,92,34,44,92,34,118,92,34,58,49,44,92,34,105,116,101,114,92,34,58,49,48,48,48,44,92,34,107,115,92,34,58,49,50,56,44,92,34,116,115,92,34,58,54,52,44,92,34,109,111,100,101,92,34,58,92,34,99,99,109,92,34,44,92,34,97,100,97,116,97,92,34,58,92,34,92,34,44,92,34,99,105,112,104,101,114,92,34,58,92,34,97,101,115,92,34,44,92,34,115,97,108,116,92,34,58,92,34,80,106,83,79,105,105,97,57,84,67,77,61,92,34,44,92,34,99,116,92,34,58,92,34,51,104,119,109,66,98,119,81,55,121,47,102,115,106,107,61,92,34,125,34
*/

如果你看一下,那不是 JSON。你可能错过了那 JSON.stringify();一步吗?

如果不是 JSON,则无法解析。

于 2015-09-10T07:09:10.403 回答