Skip to content
This repository has been archived by the owner on Apr 22, 2023. It is now read-only.

Commit

Permalink
string_bytes: strip padding from base64 strings
Browse files Browse the repository at this point in the history
Because of variations in different base64 implementation, it's been
decided to strip all padding from the end of a base64 string and
calculate its size from that.
  • Loading branch information
trevnorris committed May 20, 2013
1 parent f57ff78 commit d5d5170
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 8 deletions.
15 changes: 7 additions & 8 deletions src/string_bytes.cc
Expand Up @@ -63,16 +63,15 @@ static inline size_t base64_decoded_size_fast(size_t size) {
}

static inline size_t base64_decoded_size(const char* src, size_t size) {
size = base64_decoded_size_fast(size);
if (size == 0)
return 0;

const char* end = src + size;
// check for trailing padding (1 or 2 bytes)
if (size > 0) {
if (end[-1] == '=') size--;
if (size > 0 && end[-2] == '=') size--;
}
if (src[size - 1] == '=')
size--;
if (size > 0 && src[size - 1] == '=')
size--;

return size;
return base64_decoded_size_fast(size);
}


Expand Down
4 changes: 4 additions & 0 deletions test/simple/test-buffer.js
Expand Up @@ -980,6 +980,10 @@ assert.throws(function() {
}
})();

// Make sure byteLength properly checks for base64 padding
assert.equal(Buffer.byteLength('aaa=', 'base64'), 2);
assert.equal(Buffer.byteLength('aaaa==', 'base64'), 3);

// Regression test for #5482: should throw but not assert in C++ land.
assert.throws(function() {
Buffer('', 'buffer');
Expand Down

0 comments on commit d5d5170

Please sign in to comment.