Skip to content
This repository has been archived by the owner. It is now read-only.
Browse files

buffer, crypto: fix buffer decoding

Before this commit, DecodeWrite() mistakenly tried to convert buffers to
UTF-8 strings which:

  a) produced invalid character sequences when the buffer contained
     octets > 127, and
  b) lead to spurious test failures because DecodeWrite() wrote less bytes
     than DecodeBytes() said it would, with the remainder either containing
     zeros or garbage

Fix that by simply copying the buffer's data to the target buffer when the
encoding is BINARY or by converting the buffer to a binary string when it's

Fixes #3651, #3866.
  • Loading branch information
bnoordhuis committed Aug 14, 2012
1 parent 100e163 commit 786e1e87129611523cd7cbf255a479fe36dcba66
Showing with 19 additions and 1 deletion.
  1. +19 −1 src/
@@ -1184,7 +1184,25 @@ ssize_t DecodeWrite(char *buf,
return -1;

Local<String> str = val->ToString();
bool is_buffer = Buffer::HasInstance(val);

if (is_buffer && encoding == BINARY) { // fast path, copy buffer data
const char* data = Buffer::Data(val.As<Object>());
size_t size = Buffer::Length(val.As<Object>());
size_t len = size < buflen ? size : buflen;
memcpy(buf, data, len);
return len;

Local<String> str;

if (is_buffer) { // slow path, convert to binary string
Local<Value> arg = String::New("binary");
str = MakeCallback(val.As<Object>(), "toString", 1, &arg)->ToString();
else {
str = val->ToString();

if (encoding == UTF8) {
str->WriteUtf8(buf, buflen, NULL, String::HINT_MANY_WRITES_EXPECTED);

0 comments on commit 786e1e8

Please sign in to comment.
You can’t perform that action at this time.