在 C++ 节点插件中使用 Node::Buffers [英] Working with Node::Buffers in C++ Node Addons

查看:24
本文介绍了在 C++ 节点插件中使用 Node::Buffers的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个使用 Windows DPAPI 加密数据的 Node 插件.我正在使用 NAN 将两个 Javascript Uint8Array 传递给 C++ 代码.

I'm working on a Node addon that encrypts data using Windows DPAPI. I'm passing two Javascript Uint8Array to the C++ code using NAN.

这是打字稿界面的样子:

This is what the typescript interface looks like:

export interface DpapiBindings{
    protectData(dataToEncrypt: Uint8Array, optionalEntropy: Uint8Array, scope: string): Uint8Array
}

然后我想在 C++ 代码中创建一个 Node::Buffer:

I'd like to then create a Node::Buffer in the C++ code:

void ProtectData( Nan::NAN_METHOD_ARGS_TYPE info)
{
    v8::Isolate* isolate = info.GetIsolate();

   // 
    auto buffer = node::Buffer::Data(info[0]);
    auto len = node::Buffer::Length(info[0]);

    DATA_BLOB entropyBlob;
    entropyBlob.pbData = nullptr;
    if (!info[1]->IsNull())
    {
        entropyBlob.pbData = reinterpret_cast<BYTE*>(node::Buffer::Data(info[1]));
        entropyBlob.cbData = node::Buffer::Length(info[1]);
    }

    DATA_BLOB dataIn;
    DATA_BLOB dataOut;

    // initialize input data
    dataIn.pbData = reinterpret_cast<BYTE*>(buffer);
    dataIn.cbData = len;

    success = CryptProtectData(
            &dataIn,
            nullptr,
            entropyBlob.pbData ? &entropyBlob : nullptr,
            nullptr, 
            nullptr,
            flags,
            &dataOut);

    auto returnBuffer = Nan::CopyBuffer(reinterpret_cast<const char*>(dataOut.pbData), dataOut.cbData).ToLocalChecked();
    LocalFree(dataOut.pbData);

    info.GetReturnValue().Set(returnBuffer);

}

我是 C++ 新手,我的问题是:在 C++ 代码中使用 node::Buffer::Data 和 node::Buffer::Length 并调用 CryptProtectData 时,是否需要担心缓冲区溢出?如果是这样,我该如何防范?我应该向缓冲区和 len 附加一个空字符吗?

I'm new to C++, my question is: When working with node::Buffer::Data and node::Buffer::Length in C++ code, and calling into CryptProtectData, do I need to worry about buffer overflows? If so, how do I protect against it? Should I be appending a null char to buffer and len?

推荐答案

不,您无需担心溢出.dataIndataOut 结构是具有长度的指针.

No, you don't need to worry about overflow. The dataIn and dataOut structures are pointers with a length.

BufferCopy 不是您想要使用的.你想使用:Nan::MaybeLocalNan::NewBuffer(char* data, uint32_t size).

BufferCopy is not what you want to use though. You want to use: Nan::MaybeLocal<v8::Object> Nan::NewBuffer(char* data, uint32_t size).

https://github.com/nodejs/nan/blob/master/doc/buffers.md#api_nan_new_buffer

并确保在完成后释放 dataOut.pbData 内存(我看到您正在使用 LocalFree 调用.)它不能溢出的原因是 CryptProtectData 根据它需要的大小分配该缓冲区.

and make sure you free the dataOut.pbData memory when you're done (i see you are with the LocalFree call.) the reason it can't overflow is that CryptProtectData allocates that buffer based on the size it needs.

这篇关于在 C++ 节点插件中使用 Node::Buffers的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆