The issue in your code stems from several points, both in the C++ code and the Node.js server. Here's a breakdown of what's wrong and how to fix it:
1. Incorrect Packing in C++ Code:
In your C++ code, you're using msgpack::pack(sbuf, str.data()); to pack the string data. However, str.data() returns a const char* (a C-style string pointer), and when msgpack tries to pack this pointer, it treats it as a null-terminated string. If your encrypted string contains null bytes (which is likely, given that encryption can produce any byte value), msgpack will not pack the entire string.
Solution:
Pack the entire std::string object instead of the raw pointer:
msgpack::pack(sbuf, str);
This ensures that msgpack knows the length of the string and packs all the data, including any null bytes within the string.
2. Incorrect Content-Type Header:
You're setting the content type to "text/plain" when sending binary data. Using "text/plain" can lead to data corruption because intermediaries or frameworks might try to interpret or alter the data under the assumption that it's text.
Solution:
Use "application/octet-stream" for binary data:
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/octet-stream");
3. Node.js Server Not Configured to Handle Raw Binary Data:
Your Express.js server isn't set up to handle raw binary data for the content type you're using. Express's body parsing middleware must be explicitly configured to handle raw data for the specified content type.
Solution:
Configure Express to parse raw binary data with the correct content type:
app.use(express.raw({ type: 'application/octet-stream' }));
4. Misinterpreting the Decoded Data in Node.js:
After decoding the data with msgpack, you're assuming that the result is still a Buffer and trying to convert it to base64. However, after decoding, the data is likely a string or an object, not a Buffer.
Solution:
Adjust your logging to reflect the actual data type of the decoded message:
const decoded = decode(request);
console.log('Decoded data:', decoded);
If you want to see the base64 representation of the original binary data, log it before decoding. After decoding, you should handle the data according to its actual type.
5. Potential Encoding Issues:
If you're dealing with strings that may contain non-ASCII characters (like the encrypted string), always be cautious about character encodings when converting between byte arrays and strings.
Solution:
Ensure consistent encoding across your application. When converting buffers to strings in Node.js, you might specify the encoding:
console.log(request.toString('base64')); // Correct for binary data
Summary of Corrections:
-
In C++:
- Pack the entire string:
msgpack::pack(sbuf, str);
- Set the correct content type:
"application/octet-stream"
-
In Node.js:
By addressing these issues, your data should now be correctly encrypted, transmitted, and decoded without discrepancies.