将unsigned char字符串从本机客户端模块发送到浏览器

baw*_*nal 3 c++ google-chrome-extension google-nativeclient google-chrome-app

在Chrome氯化钠扩展,加密从浏览器接收并应该返回通过密文数据PostMessage()我有在发送的数据类型的麻烦unsigned char*ciphertext.该PP ::瓦尔规范并没有提到关于数据的这种形式的东西.我尝试过转换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);
    }
Run Code Online (Sandbox Code Playgroud)

这将返回编译时错误:

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
Run Code Online (Sandbox Code Playgroud)

小智 6

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

pp::Var var_reply(static_cast<const char*>(ciphertext));
Run Code Online (Sandbox Code Playgroud)

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

pp::VarArrayBuffer buffer(len);
void* buffer_ptr = buffer.Map();
memcpy(buffer_ptr, ciphertext, len);
buffer.Unmap();
PostMessage(buffer);
Run Code Online (Sandbox Code Playgroud)

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

您可以使用类型化数组对象从中读取数据:

function handleMessage(e) {
  var buffer = e.data;
  var view = new Uint8Array(buffer);
  ...
}
Run Code Online (Sandbox Code Playgroud)