c++ - 将 unsigned char 字符串从 native 客户端模块发送到浏览器

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

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

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

最佳答案

私有(private)的构造函数不是你想要的。尝试将密文转换为 (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);
  ...
}

关于c++ - 将 unsigned char 字符串从 native 客户端模块发送到浏览器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29210434/

相关文章:

javascript - 无法使用 chrome.app.window.get 获取 chrome.window 实例

c++ - ubuntu 12.04 中 android-ndk-r9d-linux-x86 的 ndk-gdb 出错

google-chrome-extension - ng-href 在 Chrome 扩展程序中填充链接列表时

google-chrome - Chrome 扩展 : How can I get global settings in preference

javascript - Chrome 应用程序开发

javascript - 如何将 Chrome 应用程序的最大宽度设置为小于最小化、最大化、关闭按钮的宽度?

c++ - 如何根据模板变量参数多次扩展语句

c++ - MFC编辑控件更新

c++ - Visual Studio 2012 C++ nanosleep() 哪里去了?

google-chrome - 在 chrome 扩展中获取设备的本地 IP