【问题标题】:Send unsigned char string from native client module to browser将无符号字符字符串从本机客户端模块发送到浏览器
【发布时间】:2015-03-23 12:39:12
【问题描述】:

在对从浏览器接收到的数据进行加密并应该通过PostMessage() 返回加密文本的 chrome NaCl 扩展中,我在为ciphertext 发送unsigned char* 的数据类型时遇到问题。 pp::Var 规范没有提到任何关于这种数据形式的内容。我尝试将unsigned char 转换为std::string,但没有找到合适的方法。我的代码sn-p如下:

if(action == "encryption")
    {
      pp::Var var_content = dict_message.Get("content");
      if (!var_action.is_string())
        return;
      std::string content = var_content.AsString();

      //encryption code starts here
      const char *password = "password";
      unsigned char key[EVP_MAX_KEY_LENGTH], iv[EVP_MAX_IV_LENGTH];
      int len = content.length()+EVP_MAX_BLOCK_LENGTH;
      unsigned char *ciphertext = (unsigned char*)malloc(len*sizeof(unsigned char));

      aes_init(password, (int)strlen(password), key, iv);
      len = encrypt((unsigned char*)(content.c_str()), (int)strlen(content.c_str()), key, iv, ciphertext);

      pp::Var var_reply(ciphertext);
      PostMessage(var_reply);
      free(ciphertext);
    }

这会返回一个编译时错误:

crest.cc:55:15: error: calling a private constructor of class 'pp::Var'
      pp::Var var_reply(ciphertext);
              ^
/home/kunal/Downloads/nacl_sdk/pepper_41/include/ppapi/cpp/var.h:318:3: note: declared private here
  Var(void* non_scriptable_object_pointer);
  ^
1 error generated.
make: *** [pnacl/Release/crest.o] Error 1

【问题讨论】:

    标签: c++ google-chrome-extension google-chrome-app google-nativeclient


    【解决方案1】:

    私有的构造函数不是你想要的。尝试将密文转换为 (const char*):

    pp::Var var_reply(static_cast<const char*>(ciphertext));
    

    请注意,这需要一个 UTF8 字符串。如果您的加密数据不是这种格式(很可能不是),这将无法正常工作。您可能希望将其作为 ArrayBuffer 发送,它允许任意字节序列(未经测试,假设 len 是加密密文的长度):

    pp::VarArrayBuffer buffer(len);
    void* buffer_ptr = buffer.Map();
    memcpy(buffer_ptr, ciphertext, len);
    buffer.Unmap();
    PostMessage(buffer);
    

    然后在 JavaScript 中,您将收到的对象是 JavaScript ArrayBuffer

    您可以使用typed array object 从中读取数据:

    function handleMessage(e) {
      var buffer = e.data;
      var view = new Uint8Array(buffer);
      ...
    }
    

    【讨论】:

      猜你喜欢
      • 2018-03-02
      • 1970-01-01
      • 1970-01-01
      • 2020-08-08
      • 2016-09-11
      • 2014-09-16
      • 1970-01-01
      • 2016-06-12
      • 1970-01-01
      相关资源
      最近更新 更多