Decoding base64 input with a Buffer object
I have a client interface that sends binary data encoded in base64. The data is a 29 byte custom formatted payload of bytes that describes an event. The 29 bytes is made up of a number of fields; each with unique lengths.
I need the server to decode that so I can extract the fields. I've tried using the Buffer Object as I did with another use case where the data was passed in hex format, without success.
buff = new Buffer('AR0AAAEKCgsLDAwAAATSAAAADsgAAAAAAAAAzMQ=', 'base64'); // track the current position // ... get out to the data portion of the message var position = 3; // event type var event_type = buff.slice(position,(position+3)).toString('utf8'); position += 3; console.log('... event type: ' + event_type + ' /'); // address var addr = buff.slice(position,(position+3)).toString('utf8'); position += 3; console.log('... addr: ' + addr + ' /');
The .toString('utf8') is likely the root cause. How can I get to a String that represents the desired bytes in these slice() calls?
I'm not storying binary data on the server as one might normally do with base64 encoding. So should I be going from base64 to some other encoding to access the individual bytes?
I've used the same code on a known text string that is encoded with base64 to verify the basic logic. But when the source data is binary before being encoded, the console statements don't print anything. Can I go from binary to base64 to strings?
The problem with this implementation is the use of slice() to dissect the byte stream. The parameters to slice() are indexes - not byte offsets. This seems like a pretty big flaw. I'm not sure why anyone would do that when interacting with a buffer.
Regardless, the solution is to access the buff as an array.
// event type var event_type = buff[position].toString('utf8'); position += 1; console.log('... event type: ' + event_type + ' /'); // address var addr = buff[position].toString('utf8'); position += 1; console.log('... addr: ' + addr + ' /');
If you want to concatenate multiple bytes (the original example has 3 byte lengths), you have to loop over the array indexes.